Goal
After this module you can explain why practical consensus systems elect a leader, state the three voting rules that Raft uses, prove that they give at most one leader per term (Election Safety), and explain precisely why a leader from an older term that still believes it leads cannot do any damage.
The sequencer of Module 2 gives total order broadcast cheaply: one node numbers every message and everybody delivers in that order. Its weakness is equally simple. When the sequencer crashes, nobody numbers messages any more, and the system stops. Module 4 showed that fixing this weakness in general is the consensus problem (Theorem 4.11), and that no deterministic algorithm can solve it in a purely asynchronous system (Theorem 4.16). Practical systems therefore assume partial synchrony and use timeouts.
This module isolates the first half of every leader-based consensus algorithm: choosing a leader, and replacing it when it seems to have failed, without ever ending up with two leaders that both make decisions. The central tools are terms (a counter that names each leadership period), one vote per server per term, and majority quorums. Together they give the first of Raft’s five safety properties, Election Safety, which every later proof in Module 6 and Module 7 uses.
The module follows lecture 06.03 (leader election) and the election parts of lectures 07.01 to 07.03 and 08.01, Kleppmann’s notes §6.1 (slides 108 to 110) (1), and §5.1 to §5.2 of the Raft paper (2).
Why a leader, and why replacing it is hard
The question here is why consensus algorithms such as Raft, Multi-Paxos and ZooKeeper’s Zab funnel every decision through one node, and what has to be true for that to be safe.
Lecture 07.02 puts the design choice this way: a leader-based algorithm makes one hard decision, namely who leads, and then lets the leader make all other decisions alone until it fails. Ordering commands is then as cheap as in the sequencer of Module 2: one round trip from the leader to a majority per command. A leaderless design runs the full agreement protocol for every decision. (The lecture calls Paxos leaderless; that describes single-decree Paxos of Module 8, while Multi-Paxos also works through a distinguished leader, see Module 4 and Module 9.) When failures are rare, as in a data center, the leader-based design wins on cost; the price is a pause while a new leader is chosen after a failure.
To replace a failed leader, the other nodes must first notice the failure. That is the job of a failure detector.
Definition 5.1 (Failure detector).A failure detector is a local module at each node that outputs a set of nodes it currently suspects to have crashed.
- It is perfect if (completeness) every crashed node is eventually suspected forever by every correct node, and (accuracy) no node is suspected before it crashes.
- It is eventually perfect if it has completeness and, after some unknown time, accuracy: it may wrongly suspect correct nodes for a while, but eventually it stops doing so.
The usual implementation is a heartbeat with a timeout: the monitored node sends a message every
milliseconds, and the monitor suspects it after hearing nothing for a timeout .
Lecture 06.03 notes that perfect failure detectors are impossible in the system model we use (see also Remark 4.17). The reason is short enough to prove.
Proposition 5.2 (No perfect failure detector under partial synchrony).In a partially synchronous system (message delays are unbounded before an unknown global stabilization time), no failure detector is perfect, even if at most one node may crash.
Proof
Suppose a failure detector at node
is perfect, and consider two executions that agree on everything observes. In execution
the monitored node crashes at time . By completeness, suspects at some finite time . In execution
node never crashes, but every message that sends at or after time , to any node, is delayed until after ; all other messages have the same delays as in . Partial synchrony allows this, because the global stabilization time may be later than . Delaying only the messages to would not be enough, since a third node could hear from and relay that is alive. Up to time , no node receives anything that sent at or after time , in because has crashed and in because those messages are delayed. Then, by induction over steps, every node other than receives the same messages at the same times and behaves identically in and up to , and so does ‘s detector, whose local clock also reads the same values. The detector is a deterministic function of what has observed, so in it also suspects at time . But is correct in , which violates accuracy. Hence no detector is both complete and accurate.
Intuition
A crashed node and a slow node look identical from outside until the slow node’s message finally arrives. Any timeout short enough to notice a crash quickly will sometimes fire on a node that is merely slow or cut off by the network. Timeouts give eventual accuracy only after the network settles down.
The consequence shapes everything that follows. A timeout will sometimes fire while the leader is alive, so the system may elect a new leader while the old one still runs. If both could make decisions, they could order commands differently and the replicas would diverge; Kleppmann calls this split brain (slide 108). The algorithm therefore has to be safe even when the failure detector is wrong. Timeouts may only influence liveness (whether a leader is eventually elected), never safety (whether two leaders can make conflicting decisions). Appendix A traces this ambiguity back to a single RPC whose reply does not arrive.
The three roles a Raft server can be in, and the moves between them, are shown in Figure 5.1. A follower is passive: it answers requests and waits. A candidate is trying to become leader. A leader handles clients and replicates the log (Module 6).
Terms: a logical clock for leadership
The question now is how servers can talk about “the current leader” when they may disagree about who it is. Raft’s answer is to number leadership periods.
Definition 5.3 (Term).A term is a positive integer naming one leadership period. Each server
stores , the latest term it has seen, initially . A term begins when some server starts an election in it; it has at most one leader (we prove this below), and it may have none if the election fails. Every message carries the sender’s .
Terms play the role that Lamport clocks played in Module 1: they are a logical clock, not a wall clock (2). Figure 5.2 shows the picture. Two rules attached to every message keep the clock consistent.
Definition 5.4 (Term rules).For every server
and every message (request or reply) carrying term :
- (Adopt) If
, then sets , clears its vote ( ) and becomes a follower, before handling the message. - (Reject) If
, then refuses the request and replies with its own , so the sender learns that it is behind. Besides rule 1, the only change to
is when starts an election. Both and are written to stable storage, as one record, before sends any message that depends on them.
Rule 1 is what makes an old leader step down; lecture 06.03 ends on exactly this point, that a server noticing it is in an old term turns into a follower at once. Rule 2 is what stops an old leader’s requests from having any effect. The following lemma is used in every proof in Modules 5 to 7.
Lemma 5.5 (Terms never decrease).For every server
, during an execution:
- the value of
on stable storage never decreases; - if
has sent a message carrying term or granted a vote for term , then at every later time, including after crashes and restarts of . In words: a server never returns to a term below one it has acted on.
Proof
Write
for the value of on stable storage. We show by induction over the steps of (receiving a message, a timer firing, crashing, restarting) that never decreases and that at all times. Base: initially both values are
. Step: by the term rules, a step that changes the in-memory
either adds (starting an election) or replaces it by a message term with . Both increase it, so is kept. A write to stable storage copies the in-memory value, which is at least , so does not decrease and afterwards equals . A crash loses the in-memory value but not , and a restart sets . This proves claim 1. For claim 2: when
sends a message carrying term or grants a vote for term , its in-memory equals , and by the persistence rule this value is on stable storage before the message (or the vote reply) leaves . So from then on by claim 1, and at every later time .
Remark 5.6 (The in-memory term can go back).The in-memory value of
may decrease across a crash. Say has term 3 on stable storage, adopts term 5 from a reply, and crashes before writing it; after the restart its term is 3 again. But never sent a message or a vote with term 5, so no other server can tell that was ever in term 5: to them the run looks like one in which that reply was lost. This is why it is enough to persist before sending, as the Raft paper’s Figure 2 asks (“before responding to RPCs”), and why the proofs below only use claim 2, the version about terms a server has acted on.
Exam trap: a restarted server in term 0
“Terms are just counters, so after a crash a server can start again from 0.” Wrong. Lecture 08.01 gives the reason: a server that restarts in term 0 would accept requests from long-dead terms and could vote again in a term where it already voted. If several servers did this together, they could elect a second leader for an old term. This is why
is persistent state in the Raft paper’s Figure 2.
Voting: one vote per term, majority to win
The question is how a candidate becomes leader so that no other candidate can become leader of the same term.
Definition 5.7 (Voting rules).Let the cluster be a fixed, configured set of
servers.
- (Start) A server that starts an election increments
, becomes a candidate, votes for itself ( ), stores both on stable storage, and sends RequestVote to all other servers. - (One vote) A server grants at most one vote per term: it grants a vote to candidate
for term only if, after applying the term rules, and ; it then sets and stores it on stable storage before replying. - (Majority) A candidate becomes leader of term
when it holds votes for term from at least servers of the configured cluster, its own vote included. Raft adds a fourth condition to rule 2 (the candidate’s log must be at least as up-to-date as the voter’s). It is not needed for Election Safety; it is introduced in Module 6 and used in Module 7.
The pseudocode below shows only what this module needs; Module 6 gives the complete handlers with logs.
on election timeout: // follower or candidate
currentTerm := currentTerm + 1 // persist
state := candidate
votedFor := self // persist
votesReceived := {self}
reset election timer (random)
send RequestVote(currentTerm, self) to every other server
on receive RequestVote(term, candidateId) from c:
// term rules already applied: term > currentTerm made us a follower
if term == currentTerm and votedFor in {null, candidateId}:
votedFor := candidateId // persist BEFORE replying
reset election timer
reply VoteReply(currentTerm, true)
else:
reply VoteReply(currentTerm, false)
on receive VoteReply(term, granted) from j:
if state == candidate and term == currentTerm and granted:
votesReceived := votesReceived + {j}
if |votesReceived| >= floor(n/2) + 1: // n = configured size
state := leader
send heartbeats to all servers now and periodically| Line | Why it matters for safety |
|---|---|
votedFor := self | a candidate’s own vote counts, so it cannot also vote for a rival |
votedFor in {null, candidateId} | at most one candidate per term gets this server’s vote |
| persist before replying | a crash cannot erase a vote that someone already counted |
term == currentTerm in VoteReply | late replies from an older election are not counted |
floor(n/2) + 1 of the configured | two winners would need two disjoint majorities |
Lecture 07.02 stresses the last row with an example: in a cluster of 10 servers with 2 down for maintenance, a candidate still needs
Exam trap: majority of the servers that are up
“With 2 of 10 servers down, a majority of the 8 live servers (5 votes) is enough.” Wrong. A server cannot tell a crashed peer from one on the other side of a partition. If each side of a 5 and 5 partition counted only the servers it can reach, both sides would see a “majority” of 3 out of their 5 and could elect a leader each, in the same term. Counting against the fixed configuration makes this impossible, at the price that a side with fewer than
servers cannot elect anyone.
Majorities intersect
The whole argument rests on one counting fact. Module 3 proved it for read and write quorums with
Lemma 5.8 (Two majorities intersect).Let
be a set of servers and with and . Then .
Proof
Since
, we have . By inclusion and exclusion, because
has at most elements. So and share at least one server.
Try it: here both quorums have size 3 out of 5 (think “voters for B” and “voters for anyone else”). Press Random sets a few times, or click replicas to move them in and out of a quorum, and watch that the two quorums always share at least one server; then imagine that shared server is the one that would have to vote twice.
Election Safety
Lemma 5.9 (One vote per server per term).For every server
and every term , there is at most one candidate such that grants its vote to for term (counting a candidate’s vote for itself), even if crashes and restarts any number of times.
Proof
By voting rules 1 and 2,
grants a term- vote (to itself or to another candidate) only while , and at that moment it sets to that candidate and writes it to stable storage before the vote leaves . Consider the first term-
vote of , say for . From then on, as long as , the value stays: the only operation that resets to null is the adopt rule, which also raises above ; a restart reloads from stable storage; and starting an election raises the term. So while , rule 2 only allows votes for (granting again is harmless). Once , the in-memory term can come back to only through a restart that reloads a stored term equal to (by Lemma 5.5 and its proof, the stored term never decreases and is never above the in-memory one). The record was written before the vote left , and every record written later with term is again , because while the term is the vote stays . So if the stored term is , the stored record is , and after such a restart is back in the situation above, with . Hence never votes in term for anyone but . Hence every term- vote of goes to .
Theorem 5.10 (Election Safety).For every term
, at most one server becomes leader in term . Formally, for all terms and servers : In words: two different servers are never both elected for the same term.
Proof
Suppose, for contradiction, that
both become leader in term .
- By voting rule 3,
holds term- votes from a set of servers with , and holds term- votes from a set with . Both sets are subsets of the configured cluster. - By Lemma 5.8 there is a server
. - Then
granted a term- vote to and a term- vote to . By Lemma 5.9 all term- votes of go to the same candidate, so . This contradicts
. Hence at most one server becomes leader of term .
Intuition
Think of lecture 06.03’s picture (Figure 5.3). Once A, B and C have voted for B in term 3, any other candidate needs three votes from the five servers, so its voters would have to include at least one of A, B, C. None of them can vote again in term 3. The proof uses exactly three facts: the quorums are majorities of a fixed set, each server votes at most once per term, and the vote survives crashes. Remove any one and two leaders become possible (Homework 5).
Lecture 07.02 warns that rules like this one look innocent, and that “optimizing” them (for example letting a server change its vote) is where real Raft implementations break; lecture 08.02 calls the immutable vote a bedrock of Raft. The next example shows what goes wrong if the vote is not persisted.
Example 5.11 (The forgetful voter).Five servers A to E keep
only in memory. In term 3, candidate B gets votes from A, B and C and becomes leader. Server C crashes and restarts; it reloads but is now null. Candidate D, also in term 3 (it timed out at about the same moment), asks C, D and E. Server C sees term 3, an empty vote, and grants it. D now has three votes and is also leader of term 3, contradicting Theorem 5.10. The broken step is step 3 of the proof: C voted twice in one term because the crash erased its vote.
Liveness: randomized election timeouts
Election Safety allows an election to fail. The question is how Raft makes sure that some election eventually succeeds.
If two followers time out at nearly the same moment, both become candidates in the same term, vote for themselves, and split the remaining votes. Lecture 07.03 shows this with four servers: A and D both start term 4, B votes for A and C votes for D, each candidate has 2 of 4 votes, and neither reaches
If the timeouts were equal, the same tie could repeat forever. Raft draws each election timeout at random from a fixed interval, for example 150 to 300 ms, and draws a fresh value at the start of every election. With high probability one server times out clearly before the others, collects its votes and sends heartbeats before anyone else starts an election. Module 6 computes this probability and states the timing requirement under which Raft elects a leader quickly.
Try it: step through the election. Watch the countdown of each server’s randomized timer; the first one to reach zero increments its term, votes for itself and asks the others. Notice that every server that grants a vote also resets its own timer.
Try it: with four servers, two candidates start term 4 almost together and the votes split 2 to 2. Step until one of the candidates times out again and starts term 5; check that it now collects three votes, including from servers that voted for its rival in term 4.
Exam trap: a vote binds a server forever
“B voted for A in term 4, so B cannot vote for D.” This is true only within term 4. In term 5 every server votes afresh: the adopt rule clears
whenever the term increases. One vote per term restricts the votes inside a term, not across terms.
Stale leaders: two leaders at once, safely
The question here is whether Election Safety means “at most one leader at any moment”. It does not, and it is worth seeing exactly why the weaker guarantee suffices.
Kleppmann’s slide 109 (also in lecture 06.03) gives the scenario of Figure 5.6. Server A is leader of term 1. A network partition cuts A off from B and C. They stop hearing heartbeats, B times out, starts term 2 and wins with the votes of B and C. Server A has heard nothing to the contrary, so it still believes it is the leader of term 1. At this moment there are two leaders: A for term 1 and B for term 2. Election Safety is not violated, because the terms differ. The same situation outside Raft, a lock holder that was paused while its lock expired, is why production systems attach fencing tokens to every write; see Appendix B.
Nothing can stop A from believing it leads; A cannot distinguish “B and C crashed” from “the network between us is cut”. What the protocol ensures is that A’s belief is useless. Kleppmann’s slide 110 describes the mechanism: for every decision, the leader first collects acknowledgements from a quorum in its own term. Since a follower acknowledges a term-
Proposition 5.12 (A voted-out leader cannot gather a quorum).Let
. Let be a set of at least servers each of which granted a vote for term , and let be a set of at least servers each of which acknowledged a request of term . Then some sent its term- acknowledgement before it granted its term- vote. In particular, once a leader of a higher term
has been elected, no majority of term- acknowledgements can be collected that were all sent after that election.
Proof
By Lemma 5.8 there is a server
. Server
acknowledges a term- request only while : if its term were larger it would reject (reject rule), and if it were smaller it would first adopt (adopt rule). Similarly, grants a term- vote only while (voting rule 2). Suppose
granted its term- vote first. Granting a vote is acting on term , so by Lemma 5.5 (claim 2) at every later time, including after restarts, and can never again acknowledge a term- request. Hence the acknowledgement precedes the vote in ‘s local history. For the last sentence: if a leader of term
has been elected, its voters form such a set , and every has already voted. An acknowledgement sent by after the election would come after ‘s vote, which we just showed is impossible for . So every term- quorum contains an acknowledgement sent before the election.
Intuition
The voters of the new leader are a majority, and each of them has moved to a higher term. Any majority the old leader tries to assemble must include one of them, and that server answers “no, my term is
”. So the old leader can still send messages, but it can no longer get a quorum to agree, and the “no” itself carries the higher term, which makes the old leader step down by the adopt rule. Kleppmann summarises: several leaders may exist at once, but the old ones can no longer decide anything.
The second half of the proposition is the reason why leaders in Raft do not need to know that they are still leaders. In Figure 5.6, A keeps sending AppendEntries in term 1. While the partition lasts, these messages are lost. When it heals, the first one that reaches C is refused with term 2, and A steps down.
Exam trap: at most one leader at any time
“Election Safety guarantees that the cluster never has two leaders.” Wrong. It guarantees at most one leader per term. Two servers can both be in the leader state at the same moment if their terms differ, as A (term 1) and B (term 2) in Figure 5.6. Safety comes from Proposition 5.12, which says that the leader of the older term cannot assemble a majority of acknowledgements after the newer election, so it cannot make a decision.
The collective memory of the cluster
The question here is what links an election to the decisions that earlier leaders made. Lecture 06.03 answers with the phrase collective memory of the cluster.
When a leader gets a majority to acknowledge “set x to 1”, that fact is now remembered by a majority. Any later leader is elected by a majority of voters, and by Lemma 5.8 at least one of those voters is among the servers that acknowledged. Proposition 5.12 sharpens this: that voter acknowledged before it voted, so the decision reached it before the new election. (Whether it still holds the decision at the moment it votes, despite leaders in between, is what the induction in Module 7 establishes.) In this sense the cluster as a whole cannot forget a majority-acknowledged decision, as long as a majority of servers survive with their stable storage.
Key point
A decision acknowledged by a majority in term
is known to at least one voter of every later election. Election Safety gives one leader per term; the collective memory gives continuity between terms. What remains is to make sure that the new leader actually uses that memory rather than overwriting it.
Raft’s way of doing that is a restriction on votes: a server refuses to vote for a candidate whose log is less up-to-date than its own. The voter that remembers a committed entry will therefore only vote for candidates that also have it. Module 6 states the rule, and Module 7 proves that it makes every new leader hold every committed entry (Leader Completeness).
Worked example: two elections and a stale leader
We trace five servers A to E through three terms. All logs are empty (logs enter in Module 6), and every message not mentioned is delivered promptly. The state of a server is written as (role,
| Step | Event | A, B | C | D, E |
|---|---|---|---|---|
| 0 | start | (F, 0, null) | (F, 0, null) | (F, 0, null) |
| 1 | B times out | B: (C, 1, B) | (F, 0, null) | (F, 0, null) |
| 2 | RequestVote(1) arrives | A: (F, 1, B) | (F, 1, B) | (F, 1, B) |
| 3 | B counts 3 votes | B: (L, 1, B) | (F, 1, B) | (F, 1, B) |
| 4 | partition A, B / C, D, E | no change | no change | no change |
| 5 | C times out | unchanged | (C, 2, C) | (F, 1, B) |
| 6 | RequestVote(2) to D, E | unchanged | (C, 2, C) | (F, 2, C) |
| 7 | C counts C, D, E | B still (L, 1, B) | (L, 2, C) | (F, 2, C) |
| 8 | heal; C’s heartbeat reaches A, B | (F, 2, null) | (L, 2, C) | (F, 2, C) |
Checks a reader can make line by line:
- Step 2: each follower applies the adopt rule (
), clears its vote, and then grants B’s request because is null. Step 3 needs only 3 of 5 replies. - Step 6: D and E adopt term 2, which clears their term-1 vote for B; they may now vote for C.
- Step 7: two servers are in the leader state, B in term 1 and C in term 2. Election Safety holds since the terms differ.
- Between steps 7 and 8, any request B sends in term 1 can be acknowledged by A at most. Together with B itself that is 2 of 5, so B cannot complete a quorum, exactly as Proposition 5.12 predicts.
- Step 8: A and B see term 2, adopt it, clear their votes and become followers. B learned it was voted out from the term in the heartbeat.
What breaks
- Lost stable storage. If a server loses
or (disk failure, or an implementation that keeps them in memory), Lemma 5.9 fails and two leaders of one term become possible (Example 5.11). - Byzantine servers. A server that lies about its term or votes twice breaks every proof here; tolerating that needs different algorithms with larger quorums.
- Changing the cluster. Majorities must be taken over one agreed configuration. Switching directly from an old to a new set of servers can produce two disjoint majorities, one of each configuration, and two leaders in one term; the Raft paper’s §6 uses a two-phase joint consensus to avoid this (2).
- No majority alive or connected. If fewer than
servers can talk to each other, no election succeeds and the system is unavailable. This is a liveness failure, not a safety failure. - Unlucky timing. Before the network stabilizes, elections can keep failing (split votes, lost messages). Safety never depends on timing; only progress does.
Why it matters
Election Safety is the first of Raft’s five safety properties, and every later proof starts from it: a term number identifies a unique leader, so “the entry at index 5 of term 3” means a single, well-defined entry. The term rules and Proposition 5.12 explain why a stale leader can never commit anything. Module 6 adds logs to this skeleton (RequestVote with an up-to-date check, AppendEntries with a consistency check). Module 7 turns the collective-memory idea into the Leader Completeness proof. Modules 8 to 10 show that Paxos ballots play exactly the role of terms, with promises in place of votes.
Further reading
- Raft paper §5.1 to §5.2, §5.6 and §6 on terms, elections, timing and membership changes (2); Ongaro’s thesis for a longer treatment (3).
- Kleppmann’s notes §6.1, slides 108 to 110 (1).
- Chandra and Toueg on failure detectors and why consensus needs one (4); Dwork, Lynch and Stockmeyer on partial synchrony (5).
- Howard and Mortier compare leader election in Raft and Paxos (6).
Homework
The problems for this module are in Homework 5.