Sub topic 4
Electing a leader with RequestVote
This chapter assumes you know what a replicated log is, how terms and the three roles (follower, candidate, leader) work, and that a majority quorum is more than half of the servers. You should also be comfortable reading short Python.
What an election must guarantee
An election has two jobs. It must produce at most one leader in any term. It must also never elect a leader that is missing an entry the cluster has already committed.
Raft meets both goals with the RequestVote RPC and two rules for voters:
- A server grants at most one vote per term.
- A server grants a vote only to a candidate whose log is at least as up to date as its own.
The first rule gives at most one leader per term. Two candidates in the same term cannot both collect a majority, because any two majorities share at least one server, and that server votes only once. The second rule protects committed entries. A committed entry is stored on a majority, so any candidate that wins a majority must have asked at least one server holding that entry. A candidate whose log lacks the entry will be rejected by that server.
How a candidate starts
A follower that hears nothing from a leader before its election timeout expires becomes a candidate. It does these steps:
- Increment
current_term. - Vote for itself and record
voted_for. - Reset its election timer.
- Send
RequestVoteto every other server, carrying its term, its ID, and the index and term of its last log entry.
The timeout is random, so servers rarely expire together:
import random
def new_election_timeout():
# Randomized per server and per reset, so servers rarely time out together.
# The range must be well above the heartbeat interval and the network round trip.
return random.uniform(0.150, 0.300) # secondsHow a server handles RequestVote
def handle_request_vote(s, req):
# s.log[0] is a sentinel entry with term 0, so real entries start at index 1.
if req.term < s.current_term:
return (s.current_term, False)
if req.term > s.current_term:
s.current_term = req.term
s.voted_for = None
s.role = "follower"
last_index = len(s.log) - 1
last_term = s.log[last_index].term
# Compare last log term first, then last log index.
candidate_up_to_date = (req.last_log_term, req.last_log_index) >= (last_term, last_index)
can_vote = s.voted_for is None or s.voted_for == req.candidate_id
if can_vote and candidate_up_to_date:
s.voted_for = req.candidate_id
s.persist() # currentTerm and votedFor must be durable before replying
s.reset_election_timer()
return (s.current_term, True)
s.persist()
return (s.current_term, False)Walk through the handler in order:
- Stale term. A request from an older term is rejected, and the reply carries the voter's term so the candidate can step down.
- Newer term. The voter adopts the new term, clears its vote, and becomes a follower. A vote belongs to one term, so a new term resets it.
- Up-to-date check. The comparison uses a tuple, so the last log term decides first. Index only breaks ties between equal terms. A longer log with an older last term loses to a shorter log with a newer last term.
- One vote per term.
voted_formust be empty or already equal to this candidate. The second case makes a retransmitted request safe to answer again. - Persist before replying. The vote must survive a crash. Otherwise a restarted server could vote twice in one term.
The timer reset happens only when the vote is granted. Rejecting a candidate must not delay the server's own election timeout.
Possible outcomes
A candidate ends an attempt in one of three ways:
- It wins. It has votes from a majority, counting its own, and becomes leader. It immediately sends heartbeats to stop other elections.
- It loses. It receives an
AppendEntriesfrom a leader whose term is at least its own, or any message with a higher term. It returns to follower. - It times out. Nobody won, usually because votes split. It increments the term and tries again, with a fresh random timeout.
Worked example
Take five servers. S1 to S3 hold entries up to index 5, all from term 2. S4 and S5 hold only up to index 4. S5 times out first and becomes a candidate in term 3, with last_log_index = 4 and last_log_term = 2.
S1 compares (2, 4) with its own (2, 5). The candidate is behind, so S1 refuses. S2 and S3 refuse for the same reason. S4 grants its vote, since (2, 4) >= (2, 4). S5 has two votes out of five, short of the three it needs. It cannot win, which is correct, because the entry at index 5 may be committed.
If S1 times out next, it becomes a candidate in term 4. S2, S3, S4, and S5 all grant votes, because (2, 5) is at least as up to date as every other log. S1 becomes leader.
Common errors
- Granting a vote without persisting
voted_forfirst, which allows double voting after a restart. - Comparing log length instead of the last term first.
- Resetting the election timer on every
RequestVote, including rejected ones. A disruptive candidate can then keep a healthy cluster from electing. - Using fixed timeouts, which causes repeated split votes.
- Ignoring the term in replies, so a stale leader or candidate never steps down.
Exercise
A server has a log whose last entry is at index 7, term 2. A candidate requests its vote with lastlogindex = 5 and lastlogterm = 3, and the voter has not yet voted in this term. Does the voter grant the vote, and why?
Show answer
Yes. The up-to-date check compares the last log term first. The candidate's last term 3 is greater than the voter's term 2, so the candidate's log is more up to date even though it is shorter. Since the voter has no vote recorded for this term, it grants the vote, persists voted_for, and replies true.
Exercise
Why must a server write voted_for to disk before replying that it granted a vote?
Show answer
If the server crashed after replying but before saving, it would restart with no record of its vote. It could then vote for a different candidate in the same term, and two candidates could both collect a majority. That would produce two leaders in one term.