Search code examples
consensusraftleader-election

Why Raft should grant vote when voteFor is candidateId?


I am not sure if I understand the RequestVote RPC detail in Raft correctly.

In the paper, it says

Receiver implementation:

1. Reply false if term < currentTerm (§5.1)

2. If votedFor is null or candidateId, and candidate’s log is at least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)

In which circumstance will voteFor == candidateId hold true when the receiver receives RequestVote RPC? A candidate will not send another RequestVote RPC during the same term. If it starts another election, the term will increase, so the receiver should convert to a follower and voteFor is null.

In my previous implementation of Raft, my logic is as follow:

If votedFor is null or me, and candidate’s log is at least as up-to-date as receiver’s log, grant vote 

Though it is obviously wrong, it seems to work fine, that is, the leader election and send requestVotes can work stably.

Any advice will be greatly appreciated and thanks in advance


Solution

  • I believe this is just a sanity check against network packet duplication. In a ideal case, only one RequestVoteRPC message would get to a peer during one term.

    But since the network can be in many states that are far from ideal, a network packet containing RequestVoteRpc can be duplicated, so you also need to take care of that the same way you need to check if a peer already granted you a vote, so you don't count it twice.