Sub topic 4
Electing a Leader with RequestVote
This chapter covers the election itself: how a server becomes a candidate, what the RequestVote call carries, and how a server decides whether to grant a vote. It assumes you know what a Raft term is and the three roles (follower, candidate, leader) from the previous chapters. It also assumes you can read short Python and understand majority quorums. Timeout tuning, split votes, and pre-vote come in a later chapter.
What an election has to guarantee
Raft needs a leader because all client commands flow through one server, which orders them in the log. The election has two jobs.
- Election safety. At most one leader can win in any given term. Two leaders in the same term would hand out different entries for the same log index.
- Leader completeness. A new leader must already hold every entry that was committed in earlier terms. Otherwise it would overwrite committed data.
RequestVote handles both. A majority quorum and a one-vote-per-term rule give election safety. A log comparison in the voting rule gives leader completeness. The rest of the chapter shows how each rule produces its guarantee.
The candidate's side
A follower that hears nothing from a leader for one election timeout starts an election. It does these steps in order:
- Increment
current_term. - Change its role to candidate.
- Vote for itself by setting
voted_forto its own ID. - Write
current_termandvoted_forto disk. - Reset its election timer.
- Send a RequestVote RPC to every other server, in parallel.
Step 4 matters. Without the write, a crash and restart could let the server vote twice in one term. The persistence chapter covers this in detail.
The RequestVote request carries four fields:
| Field | Meaning |
|---|---|
| `term` | The candidate's term |
| `candidate_id` | Who is asking for the vote |
| `last_log_index` | Index of the candidate's last log entry |
| `last_log_term` | Term of the candidate's last log entry |
The reply carries two fields: the voter's term and a boolean vote_granted.
The candidate then waits for one of three outcomes, and each one has a separate trigger.
| Outcome | Trigger | Result |
|---|---|---|
| Win | Votes from a majority of the full cluster, counting its own | Becomes leader and immediately sends heartbeats (empty AppendEntries) |
| Lose | Receives AppendEntries from a server whose term is at least its own | Returns to follower |
| Timeout | Neither of the above before its election timer fires | Starts a new election with a higher term |
The majority is computed over the whole cluster, not over the servers that replied. In a five-server cluster a candidate needs three votes, including its own, even if two servers are down.
The voter's side
A server that receives RequestVote applies the rules below. It evaluates them in this order, and the order matters.
- Reject stale candidates. If
req.term < current_term, reply with the voter's term andFalse. The reply term tells the candidate it is out of date. - Adopt newer terms. If
req.term > current_term, setcurrent_term = req.term, clearvoted_for, and become a follower. This happens even if the vote is then denied. A candidate or leader that sees a higher term must step down, because its own term is obsolete. - Check that the vote is still available. The voter may vote if
voted_foris empty or already equals the candidate's ID. The second case makes retries safe. If the candidate's first reply was lost and it resends the request, it gets the same answer. - Check that the candidate's log is at least as up to date. Compare the last log terms first. If they are equal, the longer log wins.
- Grant or deny. If both checks pass, record
voted_for, write the state to disk, reset the election timer, and replyTrue. Otherwise replyFalse.
Granting a vote resets the election timer because the voter has just accepted a plausible future leader. If it did not reset, it could start a competing election right after voting.
Why the up-to-date check uses term first
It is tempting to compare only log length, on the grounds that a longer log has more data. That is wrong. Suppose server A has a long log of uncommitted entries from an old, deposed leader in term 2. Server B has a shorter log whose last entry is from term 3 and was committed on a majority. B's log is the more recent history. If A could win on length, it would overwrite committed entries.
Raft compares (last_log_term, last_log_index) as a pair, so the term decides first and the index breaks ties. Python's tuple comparison does exactly this.
Why this gives leader completeness
A committed entry is stored on a majority of servers. A candidate needs votes from a majority. Any two majorities of the same cluster share at least one server. That shared server holds the committed entry and will only vote for a candidate whose log is at least as up to date as its own. So a candidate that lacks the committed entry cannot collect that server's vote and cannot win. The log comparison and the quorum overlap work together, and neither is enough alone.
The voting handler in code
The handler below is the voter's rule set. It is wrapped in a small harness so you can run it as shown. The Server class keeps a counter in persist() so you can see when state would be written, and reset_election_timer() does nothing here. Index 0 of the log is a sentinel entry with term 0, so real entries start at index 1.
from dataclasses import dataclass, field
@dataclass
class Entry:
term: int
@dataclass
class RequestVote:
term: int
candidate_id: str
last_log_index: int
last_log_term: int
@dataclass
class Server:
current_term: int = 0
voted_for: str = None
role: str = "follower"
log: list = field(default_factory=lambda: [Entry(0)])
persist_calls: int = 0
def persist(self):
# A real server would fsync current_term, voted_for, and the log here.
self.persist_calls += 1
def reset_election_timer(self):
pass
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)
# The voter's log holds entries 1..3 with terms 1, 1, 2.
voter = Server(current_term=2, log=[Entry(0), Entry(1), Entry(1), Entry(2)])
print(handle_request_vote(voter, RequestVote(3, "B", 3, 2))) # grant
print(handle_request_vote(voter, RequestVote(3, "C", 3, 2))) # already voted for B
print(handle_request_vote(voter, RequestVote(3, "B", 3, 2))) # retry from B, granted again
print(handle_request_vote(voter, RequestVote(4, "D", 10, 1))) # longer log, older last term
print(handle_request_vote(voter, RequestVote(2, "E", 3, 2))) # stale term
print(voter.current_term, voter.voted_for)Running it prints:
(3, True)
(3, False)
(3, True)
(4, False)
(4, False)
4 NoneHere is what each line shows.
- Line 1. Candidate B has term 3 and a log matching the voter's, so it gets the vote.
- Line 2. Candidate C asks in the same term. The voter already voted for B, so it refuses. This is the one-vote-per-term rule.
- Line 3. B asks again and is granted again. A retry is safe.
- Line 4. D has a much longer log, but its last entry is from term 1 and the voter's is from term 2. D is denied. The voter still adopts term 4 and clears its vote, because rule 2 runs before the log check.
- Line 5. E's term 2 is behind the voter's term 4, so E is rejected, and the reply term 4 tells E to step down.
The last line shows the voter ended with term 4 and no vote recorded, since it denied D.
Following one election
The diagram shows a three-server cluster where S1's timer fires first. S2 votes for it. S3 is slow, and the vote count already reaches a majority without it.
S1 does not wait for S3. Once the count reaches a majority, the election is decided. The late reply from S3 changes nothing, and S3 learns of the new leader from the heartbeat.
Randomized timeouts
Each server picks its own election timeout at random, and picks again every time it resets. This keeps most servers from timing out together. The range should sit well above the heartbeat interval and the network round trip.
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) # secondsIf every server used the same timeout, they would all become candidates at once, each vote for itself, and no one would reach a majority. The next chapter covers split votes and how to tune the range.
Edge cases and common mistakes
A server can vote in a term where it already voted for itself. A candidate has voted_for set to its own ID. If a RequestVote arrives from another candidate in the same term, the vote is denied. If it arrives with a higher term, the candidate steps down first, clears its vote, and may then grant.
Replies can arrive late and from old terms. A candidate may receive a vote reply after it has already moved on to a new term. It must compare the reply's term and its own current term, and ignore stale replies. Counting a term-3 vote toward a term-5 election is a classic bug.
Counting your own vote twice. The self-vote is made once when the election starts. Keep a set of voter IDs rather than a bare counter, so a duplicated reply cannot be counted twice.
Persisting after replying. If the vote reply goes out before the write is durable, a crash can lose voted_for. After a restart the server may vote for a different candidate in the same term, and two leaders become possible. Write first, then reply. The denial path in the handler also persists, because the term may have changed.
Treating >= as strict. A candidate whose log is identical to the voter's is up to date. The comparison must allow equality, or equal logs would never win an election.
Disruptive servers. A server cut off from the cluster keeps timing out and raising its term. When it reconnects, its higher term forces the current leader to step down, even though the cluster was healthy. Pre-vote, covered in the next chapter, addresses this.
Summary of invariants
| Rule | What it protects |
|---|---|
| One vote per term, recorded durably | At most one leader per term |
| Majority required out of the full cluster | Any two winners' quorums overlap |
| Voter compares last log term, then index | Committed entries survive elections |
| Higher term always forces a step-down | Stale leaders and candidates stop acting |
| Randomized timeouts | Elections usually finish in one round |
Exercise
A voter has current term 5, votedfor set to "A", and a log whose last entry has index 7 and term 4. Candidate "B" sends RequestVote with term 6, lastlogindex 9, and lastlog_term 3. What does the voter reply, and what is its state afterward?
Show answer
The voter replies (6, False). Because 6 is greater than 5, the voter first adopts term 6, clears votedfor, and becomes a follower, so the earlier vote for "A" no longer blocks it. It then compares logs: the candidate's pair (3, 9) is less than the voter's pair (4, 7), because the last log term is compared first. B's log is longer but its last entry is older, so the vote is denied. Afterward the voter has currentterm 6 and voted_for empty, and it persists that state before replying.
Exercise
In a five-server cluster, a candidate receives granted replies from two other servers and denied replies from the remaining two. Does it win? Would your answer change in a six-server cluster with the same replies?
Show answer
In the five-server cluster it wins: its own vote plus two grants makes three, and the majority is three of five. In a six-server cluster the majority is four, so three votes are not enough, and the candidate keeps waiting until it wins, loses to another leader, or times out.