RAFT

Leader election by majority vote

L320 MINDISTRIBUTED SYSTEMS
PREDICT

Three nodes. The leader N1 crashes. N2 and N3 use the same fixed 150 ms election timeout, so both time out at the same instant and start an election for term 2 (terms are numbered election rounds; a node gets one vote per term). What happens?

Raft keeps one ordered log on every server. One leader appends client writes and copies them to followers; an entry is committed once a majority holds it. Time is split into numbered terms, each with at most one leader.

When followers stop hearing heartbeats, one times out, increments the term, votes for itself and asks the others. A voter grants at most one vote per term, and only to a candidate whose log is at least as up to date as its own. A majority of votes makes a leader. Randomized timeouts make ties rare. A follower whose log disagrees rejects AppendEntries until the leader backs up to the point where they match.

▶ SIMULATION
N1
role: LEADER · term 1
votedFor: N1
log: 1:a · commit 1
nextIndex N2=2 N3=2
N2
role: FOLLOWER · term 1
votedFor: N1
log: 1:a · commit 1
hearing a leader
N3
role: FOLLOWER · term 1
votedFor: N1
log: 1:a · commit 1
hearing a leader
clockt = 0 ms · timers random 150–300 ms, seed 1 · voting rule Raft
leaders by termt1: N1
committed (majority)#1 1:a
eventN1 leads term 1; entry 1:a is committed on all 3 nodes
✓ at most one leader per term✓ a committed entry is never overwritten
SCHEDULE
01[SYS]seed 4 for election timers (random 150–300 ms)
02[N1]N1: client write x
03[LOG]N1: AppendEntries to every reachable follower — x reaches a majority
04[N1]N1: CRASHES
05[SYS]clock: the earliest election timer fires (the shortest random draw)
06[VOTES]the candidate sends RequestVote to every reachable node
07[CLIENT]client write y to the new leader
08[LOG]new leader: AppendEntries to every reachable follower — y reaches a majority
09[LOG]new leader: AppendEntries to every reachable follower — heartbeat carries the commit index
10[SYS]clock: does any election timer fire? (heartbeats reset them)
11[VOTES]any candidate sends RequestVote to every reachable node
12[SYS]check: every term's leaders, every committed entry, every log
Start of clean election scenario. 12 steps.
RequestVote(term, candidateId, lastLogIndex, lastLogTerm)
  if term < currentTerm:                 reject
  if term > currentTerm:                 currentTerm = term; votedFor = null; become follower
  if votedFor not in (null, candidateId): reject          // one vote per term
  if candidate log older than mine:      reject          // compare last term, then length
  votedFor = candidateId; reset election timer; grant

Election
  timer fires (random 150-300 ms) -> currentTerm++, vote for self, ask everyone
  votes from a majority  -> LEADER; set nextIndex[i] = lastLogIndex + 1
  hears a higher term    -> FOLLOWER
  timer fires again      -> new term, new election (split vote)

AppendEntries(term, prevLogIndex, prevLogTerm, entries, leaderCommit)
  if term < currentTerm:                          reject (leader steps down)
  if log[prevLogIndex].term != prevLogTerm:       reject; leader decrements nextIndex
  for each entry: conflict -> delete it and all after; then append
  commitIndex = min(leaderCommit, index of last new entry)

Commit: a leader marks entry N committed when a majority hold it
        AND log[N].term == currentTerm (older-term entries commit only with it).

Safety: two majorities overlap, so one vote per term means one leader per term;
        the overlap also holds the newest committed entry, so the log check means
        every new leader already has every committed entry.

Watch the two invariants and the “leaders by term” row. Every Raft scenario keeps both green, even STALE LEADER REJOINS, where two nodes show LEADER at once in different terms. The two BUG scenarios break the voting rule. VOTE TWICE drops the one-vote-per-term rule (this sim’s version also skips the log check, which changes nothing here because the logs are equal) and elects two leaders in term 2. NO LOG CHECK keeps one vote per term but never compares logs, so it elects N1 with a stale log, and N1 overwrites the committed 2:c.

In LOG DIVERGENCE, N1’s term-3 RequestVote makes the healthy term-2 leader N3 step down, even though N1 cannot win. That is correct Raft, not a sim bug: a node that rejoins with a higher term disrupts the cluster. The PreVote extension (etcd and others use it) stops this by having a candidate first check that it could win before it raises its term.

BREAK IT NOT YET

N1 is going to crash. Inject one more crash or partition so that the survivors can never elect a new leader. Then try the same fault with NODES at 4 and at 5.

GOAL: no leader is elected after term 1

FIX IT NOT YET

Make onRequestVote safe. Grant at most one vote per term, and only to a candidate whose log is at least as up to date as yours (compare the last entry's term first, then the length). A higher term always updates currentTerm and clears votedFor, even if you then refuse.

Mental model:

Raft’s safety is two rules on one vote. One vote per term plus overlapping majorities gives one leader per term. Only vote for an up-to-date log plus overlapping majorities means every new leader already has every committed entry. Everything else (randomized timeouts, heartbeats, nextIndex backoff) is for liveness: getting a leader elected and followers repaired, never deciding what is true.

IN PRODUCTION

etcd (and therefore Kubernetes), Consul, CockroachDB, TiKV, Kafka's KRaft controller and most new replicated databases run Raft. You meet it as leader-election storms, a 3- versus 5-node sizing decision, or a cluster that goes read-only when it loses its majority.

IN INTERVIEWS

“How does Raft elect a leader, and why can there not be two?” Walk the term, the one persisted vote, the majority, and the randomized timeout. The follow-up is “what stops a node with a stale log from winning?”: the up-to-date check on lastLogTerm then lastLogIndex. Mention that 4 nodes tolerate no more failures than 3.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.

USED IN

Chapters that build on this lesson.

NEXT: PAXOS →