0
votes

i have a doubt in undersanting the leader election algorithm of the Raft algorithm. In the paper i read that each node con give only one vote for each term. My doubt is because the terms in each node can be different, what is referred is the term of the node asking for vote or the term of the node giving the node ? Thanks

1

1 Answers

1
votes

In a raft cluster, let's have a node that wants to become the leader and call it a candidate. All other nodes, including the current leader, we'll simply call peers.

Let's see what happens when a peer receives a RequestVoteRPC from a candidate.

If the term of the peer is greater than the one received in the request (candidates term), the vote will be denied. The response will contain the term of the peer, so the candidate will convert to the follower state and update it's term as soon as it receives the response. This will ensure that the term of the peer asking for a vote is the same as the term of the peer giving the vote.

Otherwise the peer needs to decide what to do.

If the term of the peer is less than the one received in the request (candidates term), this peer will convert to a follower and will update it's current term to the one received from the candidate, before continuing with the decision. This will ensure that the term of the peer asking for a vote is the same as the term of the peer giving the vote.

There is a chance that multiple peers converted to the candidate state, and the peer we're observing already voted for a candidate. In that case, the votedFor variable will not be null and we can't grant the vote to the second (or any other) candidate. But we also need to be careful here because we can receive a duplicate RequestVoteRPC request (from the same candidate) and because of that we need to check if votedFor is equal to the candidate id whose request we're observing. If votedFor is equal to the current candidate id, we'll grant the vote.

To summarize, we'll grant the vote if the votedFor variable is null or equal to the candidate id.

I purposely excluded the condition that in order to grant the vote, the candidate log needs to be at least up to date in the example, but don't forget that this is also important.

Each peer can grant one vote during one term and since the terms will sync during the communication, the term of the peer giving the vote will be the same as the term asking for a vote.