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.

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).

Follower Candidate Leader start or restart times out majority of votes times out again: term + 1 sees a leader or a higher term sees a higher term
Figure 5.1. Server roles and transitions. Every server starts (and restarts after a crash) as a follower. Seeing a higher term sends any server back to follower.

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 :

  1. (Adopt) If , then sets , clears its vote () and becomes a follower, before handling the message.
  2. (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.

term 1 term 2 term 3 term 4 split vote: no leader time election normal operation under one leader
Figure 5.2. Terms divide time. Each term starts with an election; a term whose election splits the vote ends without a leader and a new term begins. Different servers may see the term changes at different times.

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:

  1. the value of on stable storage never decreases;
  2. 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.

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.

  1. (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.
  2. (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.
  3. (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
LineWhy it matters for safety
votedFor := selfa 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 replyinga crash cannot erase a vote that someone already counted
term == currentTerm in VoteReplylate 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 votes, not . The majority is always taken over the configured cluster.

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 3.14, Corollary 3.15); we restate the majority case with its short proof, since everything below depends on it.

Lemma 5.8 (Two majorities intersect).

Let be a set of servers and with and . Then .

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.

A voted B B voted B C voted B D not voted E not voted A, B, C voted for B in term 3 C, D, E: no majority without C's vote
Figure 5.3. Lecture 06.03's example. A, B and C have voted for B in term 3, so B has a majority. Any other majority, such as C, D, E, contains a server that has already voted, so no second leader of term 3 can exist.

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.

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.

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 . Nobody can change their vote, so term 4 ends without a leader (Figure 5.2, term 3, shows the same situation on the time line). Both candidates time out again and start term 5.

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.

A B C D E RequestVote votes heartbeats B times out: term 1 B is leader of term 1 followers reset their timers
Figure 5.4. One election (the raft-sim election scenario). B's timer fires first; B enters term 1, votes for itself and sends RequestVote. With its own vote and two more it has 3 of 5 and becomes leader; its heartbeats reset everyone else's 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.

A B C D term 4: 2 votes each, no leader term 5: D wins with 4 of 4 dashed: refused, already voted D leader
Figure 5.5. A split vote with four servers (lecture 07.03). In term 4, A and D each hold two votes and neither reaches three. D's randomized timer fires first, D starts term 5, and the others vote for it.

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.

A B C partition: A cut off B leads term 2 A sends AppendEntries, term 1 A steps down C refuses: term 2 lost
Figure 5.6. A stale leader (Kleppmann slide 109). A leads term 1 but is cut off from B and C, which elect B in term 2. A still believes it leads. Its next request reaches C after the partition heals; C answers with term 2 and refuses, and A steps down.

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- request only if its own term is (by the reject rule, after the adopt rule has run), the following proposition says that a voted-out leader can no longer complete a quorum.

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.

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, , ), with F, C, L for follower, candidate, leader.

StepEventA, BCD, E
0start(F, 0, null)(F, 0, null)(F, 0, null)
1B times outB: (C, 1, B)(F, 0, null)(F, 0, null)
2RequestVote(1) arrivesA: (F, 1, B)(F, 1, B)(F, 1, B)
3B counts 3 votesB: (L, 1, B)(F, 1, B)(F, 1, B)
4partition A, B / C, D, Eno changeno changeno change
5C times outunchanged(C, 2, C)(F, 1, B)
6RequestVote(2) to D, Eunchanged(C, 2, C)(F, 2, C)
7C counts C, D, EB still (L, 1, B)(L, 2, C)(F, 2, C)
8heal; 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.

1.
Kleppmann M. Distributed Systems: Lecture Notes [Internet]. University of Cambridge, Computer Science Tripos Part IB; 2021. Available from: https://www.cl.cam.ac.uk/teaching/2122/ConcDisSys/dist-sys-notes.pdf
2.
Ongaro D, Ousterhout J. In Search of an Understandable Consensus Algorithm. In: Proceedings of the USENIX Annual Technical Conference (ATC). 2014. p. 305–19.
3.
Ongaro D. Consensus: Bridging Theory and Practice [phdthesis]. Stanford University; 2014.
4.
Chandra TD, Toueg S. Unreliable Failure Detectors for Reliable Distributed Systems. Journal of the ACM. 1996;43(2):225–67.
5.
Dwork C, Lynch N, Stockmeyer L. Consensus in the Presence of Partial Synchrony. Journal of the ACM. 1988;35(2):288–323.
6.
Howard H, Mortier R. Paxos vs Raft: Have We Reached Consensus on Distributed Consensus? In: Proceedings of the 7th Workshop on Principles and Practice of Consistency for Distributed Data (PaPoC). 2020.