Course contents

08. Distributed Systems Lesson 7 of 10

Raft

Watch Raft elect a leader with terms and votes, replicate a log with AppendEntries, commit on a majority, and recover from follower and leader crashes.

18 minAdvanced9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Servers are followers, candidates or the leader; terms number the leaderships, with at most one leader per term.
  • A follower that hears nothing for a randomised election timeout starts an election; a majority of votes makes it leader.
  • The leader replicates log entries with AppendEntries; an entry is committed once a majority stores it.
  • Followers that fall behind are repaired from the leader’s log (or a snapshot), checked by prevLogIndex and prevLogTerm.
  • Voters only elect a candidate whose log is at least as up-to-date, so every new leader has every committed entry.
  • A leader that sees a higher term steps down; its uncommitted entries are overwritten.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Raft is a consensus algorithm for managing a replicated log, published by Diego Ongaro and John Ousterhout in 2014 ("In Search of an Understandable Consensus Algorithm"). It provides the same guarantees as Multi-Paxos but splits the problem into three parts that are easier to reason about: leader election, log replication and safety. A cluster of 2f + 1 servers keeps working with up to f of them down. Raft is used in etcd (and therefore Kubernetes), Consul, CockroachDB, TiKV, YugabyteDB, Kafka's KRaft metadata quorum, RabbitMQ quorum queues and many others.

Why it exists

State machine replication needs every replica to apply the same commands in the same order. Paxos solves this but is famously hard to understand and to turn into a complete system (membership changes, log compaction, client interaction). Raft was designed for understandability: one strong leader, a log that only flows from leader to followers, and a small number of rules that are easy to check.

How it works

Roles and terms. Each server is a follower, a candidate or the leader. Time is divided into terms, numbered with consecutive integers. Each term begins with an election; if it succeeds, one leader serves the rest of the term. Every message carries the sender's term. A server that sees a higher term adopts it and becomes a follower; a request with a stale term is rejected.

Persistent state. Each server stores currentTerm, votedFor and its log on stable storage before answering any RPC, so a restart cannot make it vote twice in a term or forget acknowledged entries.

Leader election. Followers expect periodic heartbeats (AppendEntries without entries). A follower that hears nothing for its election timeout, chosen at random (the paper uses 150–300 ms), becomes a candidate: it increments its term, votes for itself and sends RequestVote to all others. A server grants at most one vote per term, on a first-come basis, and only to a candidate whose log is at least as up-to-date as its own (see safety). A candidate with votes from a majority becomes leader and immediately sends heartbeats. If the vote splits, candidates time out and try again with new random timeouts. The paper's timing requirement is broadcastTime ≪ electionTimeout ≪ MTBF.

Log replication. The leader appends each client command to its log as an entry (index, term, command) and sends AppendEntries to every follower with the entries, the index and term of the entry just before them (prevLogIndex, prevLogTerm) and its leaderCommit. A follower accepts only if its log contains an entry at prevLogIndex with term prevLogTerm; it deletes any conflicting entries after that point and appends the new ones. Once an entry from the current term is stored on a majority, the leader marks it committed, applies it to its state machine and answers the client. Followers apply entries up to leaderCommit.

Repairing followers. The leader keeps a nextIndex and matchIndex per follower. When a consistency check fails, it decrements nextIndex and retries until the logs match, then overwrites the follower's divergent suffix. A follower that is too far behind (because the leader compacted its log) receives a snapshot via InstallSnapshot. Unanswered RPCs are simply retried.

Safety. The election restriction says a voter denies its vote if its own log is more up-to-date than the candidate's: a higher last term wins, and with equal last terms the longer log wins. Since a committed entry is on a majority and a winner needs a majority of votes, at least one voter holds every committed entry and refuses candidates without it. Hence every leader contains all committed entries (Leader Completeness). A subtle rule completes the picture: a leader only counts replicas to commit entries from its own term; older entries become committed indirectly when a newer entry after them commits. That is why a new leader commonly appends a no-op entry at the start of its term.

Clients. Clients send requests to the leader; a follower rejects them and names the leader it last heard from. Clients attach unique serial numbers to commands so the state machine can discard duplicates of retried requests. For linearizable reads the leader must confirm it is still leader (a heartbeat round to a majority, called ReadIndex in etcd/raft) or rely on a clock-based lease.

Membership changes use joint consensus or, as most implementations do, single-server changes, so the old and new configurations can never form disjoint majorities.

When to use it

  • You need a strongly consistent replicated state machine: metadata stores, configuration, lock services, the replication layer of a distributed database.
  • Leader election and fencing for a group of processes where correctness matters.
  • Through a library: etcd's raft package, HashiCorp's raft, Apache Ratis, openraft, or by running etcd or Consul rather than embedding Raft yourself.

When not to

  • High-volume data where async replication's small risk of losing the latest writes on failover is acceptable and latency matters more.
  • Wide-area deployments with clients everywhere: every write pays a round trip from the leader to a majority, so a cluster spread over continents makes every write slow.
  • When you can merge concurrent updates (CRDTs) and want the minority side of a partition to keep accepting writes.

Trade-offs

Choice You gain You pay
Short election timeout Faster failover after a leader crash Spurious elections during GC pauses or network jitter, each pausing writes
Long election timeout Stability under jitter Longer write pause when the leader really fails
5 servers instead of 3 Survives 2 failures Commits wait for the 3rd-fastest server; more replication traffic
Reads via the leader with ReadIndex Linearizable reads A majority round trip per read (batched in practice)
Lease-based leader reads No round trip per read Correctness depends on bounded clock drift
Follower reads Spreads read load Possibly stale unless the follower first asks the leader for the commit index

Alternatives

  • Multi-Paxos: the same guarantees; more flexible (for example, no requirement that the leader's log is complete) but harder to implement completely. Used in Spanner and Chubby.
  • ZAB: ZooKeeper's protocol, also leader-based with epochs; very similar in spirit to Raft.
  • Viewstamped Replication: predates both and shares many ideas with Raft.
  • EPaxos and other leaderless variants: lower latency for geo-distributed clients when commands rarely conflict, at a large complexity cost.
  • Primary–backup with an external coordinator: simpler data path, with only failover decisions going through consensus.

Failure modes

  • Frequent elections: timeouts close to the real network or disk latency, long GC pauses or an overloaded leader cause churn, and every election pauses writes. The Pre-Vote extension (a candidate first checks it could win before incrementing its term) prevents a rejoining partitioned node from disrupting a healthy leader; CheckQuorum makes a leader step down when it cannot hear from a majority.
  • Slow disks: commits wait for an fsync on a majority. A slow disk on the leader slows everything; on followers it is masked until too many are slow.
  • Losing a majority: the cluster stops accepting writes; it does not lose committed data.
  • Stale reads: serving reads from a deposed leader or a follower without ReadIndex or leases returns old data.
  • Unbounded log growth: without snapshots and compaction, restarts replay the whole log and new followers take forever to catch up.

In production

etcd's defaults are a 100 ms heartbeat interval and a 1000 ms election timeout, tuned for typical data-centre latency including disk syncs; the etcd docs recommend raising them for high-latency networks. Run three or five members across zones, alert on leader changes and on proposal or commit latency, put the log on fast disks, and snapshot regularly. Clients should retry with idempotency keys, because a timeout does not tell them whether a command was committed. Most teams use Raft through etcd, Consul or a database that embeds it, rather than writing their own.

Common misconceptions

  • "The leader waits for every follower." A majority suffices; the rest catch up later.
  • "A crashed follower makes the cluster read-only." With five servers, two can be down and writes continue.
  • "An old leader in a partition can commit writes." It cannot reach a majority, so nothing it appends commits.
  • "The longest log wins the election." The last entry's term is compared first; length only breaks ties.
  • "Committed means applied on every server." It means durable on a majority; followers apply when they learn the commit index.

Interview angle

Explain the three pieces: elections with terms and randomised timeouts, replication with AppendEntries and commit on a majority, and the election restriction that keeps committed entries. Be ready to walk through a leader crash (writes pause for roughly an election timeout, clients retry and are redirected) and a partition (the minority side cannot commit; the old leader steps down when it sees a higher term). Mentioning ReadIndex or leases for linearizable reads, Pre-Vote, snapshots and why clusters have 3 or 5 members shows real familiarity.

Model assumptions

This lesson is a scripted illustration, not a simulation: the simulator has no election, term or log model. Every RequestVote, AppendEntries and reply is a packet placed by hand, and each server's term, log and commit index are annotations and role tags. Packet colours stand for message types: request = RequestVote or a client command, ack = vote granted or AppendEntries success, error = vote denied or request rejected, replication = AppendEntries with entries, message = a heartbeat or a redirect hint. Timings are illustrative: 8–9 ms between the client and a server, 10–14 ms between servers, about 1 ms of processing, heartbeats every 50 ms and election timeouts in the paper's 150–300 ms range. Disk syncs, batching, pipelining, snapshots, Pre-Vote and membership changes are not shown.

The lesson as textEvery step of the simulation, written out.
  1. 1. Terms, timeouts and the first election

    A Raft cluster has five servers; each is a follower, a candidate or the leader. Time is divided into numbered terms; each term starts with an election and has at most one leader.

    All five start as followers in term 0, each with a randomised election timeout (150–300 ms). S3’s fires first. It becomes a candidate, moves to term 1, votes for itself and sends RequestVote to the other four. Each follower grants at most one vote per term, first come, first served. With its own vote plus S1’s and S5’s, S3 has 3 of 5 at 21 ms and becomes leader; it starts sending heartbeats (empty AppendEntries) at once, even before S4’s vote arrives. Heartbeats reset the followers’ timers, so nobody else starts an election.

    Scripted illustration: packets and annotations show the protocol, nothing is simulated.

    Scene: S3’s election timeout fires first. It asks the other four servers for votes in term 1; S1 and S5 answer first, giving S3 three of five votes, so it becomes leader and sends heartbeats to all followers before S4’s vote even arrives.

    Key idea: Randomised timeouts make one server ask first; a majority of votes in a term makes it the only leader of that term.

  2. 2. Log replication: commit on a majority

    The client sends x ← 3 to the leader. S3 appends it to its log as entry 1 (term 1) and sends AppendEntries to every follower in parallel: the new entry plus prevLogIndex = 0, prevLogTerm = 0 and its leaderCommit. Each follower checks that its log matches at prevLogIndex, appends the entry, writes it to disk and replies success.

    When S1’s and S5’s replies arrive, entry 1 is stored on 3 of 5 servers: it is committed. S3 applies it to its state machine and answers the client at 39 ms, without waiting for S2 and S4. Followers learn the new commit index from the next AppendEntries (leaderCommit = 1) and apply the entry too.

    Scripted illustration.

    Scene: The client sends a write to leader S3, which appends it as entry 1 and sends AppendEntries to all four followers. After S1 and S5 acknowledge, the entry is on three of five servers; S3 commits it, answers the client, and tells the followers the new commit index in the next heartbeat.

    Key idea: An entry is committed once the leader has stored it on a majority; only then is it applied and acknowledged.

  3. 3. A follower crashes: nothing stops

    S5 crashes with entry 1 in its log. Two more writes arrive and become entries 2 and 3. S3 sends each to all four followers, S5 included: the leader retries AppendEntries to an unresponsive follower indefinitely. S1, S2 and S4 acknowledge, so each entry reaches a majority (S3 plus two followers) and is committed.

    With five servers the cluster tolerates two failed followers. S5’s silence costs nothing but a missing copy.

    Scripted illustration.

    Scene: S5 is down. The client writes entries 2 and 3; leader S3 sends each to all followers including S5, which never answers. S1 and S2 acknowledge each entry, giving a majority, so both are committed and confirmed.

    Key idea: A majority keeps committing while a minority of followers is down; the leader keeps retrying the missing ones.

  4. 4. The follower comes back and catches up

    S5 restarts. Its log (entry 1) and its current term survived on disk: Raft persists them before answering any RPC. It comes back as a follower.

    The leader tracks a nextIndex per follower. S5 never acknowledged anything after entry 1, so S3 still sends from entry 2: AppendEntries with entries 2–3, prevLogIndex = 1, prevLogTerm = 1, leaderCommit = 3. S5’s log matches at index 1, so it appends both entries, replies success and applies them up to the commit index. One round trip and S5 is current.

    A follower that is far behind gets a snapshot (InstallSnapshot) instead of the whole log. Scripted illustration.

    Scene: S5 restarts with only entry 1. Leader S3 sends it entries 2 and 3 in one AppendEntries; S5 appends them and acknowledges, and its log matches the leader’s again.

    Key idea: A returning follower is repaired by the leader from its own log: it sends what the follower is missing, checked by prevLogIndex and prevLogTerm.

  5. 5. The leader crashes: a new election

    S3 crashes. Heartbeats stop. The client’s next write goes to S3 and gets no answer; after its 100 ms timeout it tries S2, which still believes S3 is the leader and points it back there.

    At 190 ms S1’s randomised timeout fires first. S1 moves to term 2 and asks for votes. Its log is as complete as anyone’s, so S2 and S5 grant: S1 is leader at 211 ms. It immediately replicates a no-op entry of its own term, the way a new Raft leader learns which earlier entries are committed. S2 now redirects the client to S1, and the write is committed and answered at 289 ms.

    Writes paused for about a quarter of a second: roughly one election timeout plus a round trip. Scripted illustration.

    Scene: Leader S3 is down. The client’s write gets no answer, and S2 turns it away because it still believes S3 is leader. S1’s election timeout fires at 190 ms; S2 and S5 vote for it and it becomes leader of term 2, replicating a no-op entry. S2 then redirects the client to S1, which commits the write and answers at about 289 ms.

    Key idea: Leader failure costs about one election timeout of write unavailability; clients retry and are redirected to the new leader.

  6. 6. Committed, but not everywhere

    The client writes again: entry 6 (term 2). S1’s AppendEntries reaches S2 and S4, but the message to S5 is lost. S2 and S4 acknowledge, so entry 6 is on S1, S2 and S4, a majority, and it is committed and confirmed to the client.

    S5’s log now ends at entry 5. The leader would repair that on its next AppendEntries, but suppose it never gets the chance. Which servers may become the next leader without losing entry 6?

    Scripted illustration.

    Scene: Leader S1 replicates entry 6 to S2 and S4, which acknowledge; with three of five copies the entry is committed and the client is answered. S5 never received it.

    Key idea: A committed entry is guaranteed to be on a majority, not on every server.

  7. 7. Only an up-to-date log can win

    A partition cuts S1 off from everyone else (S3 is still down). S2, S4 and S5 remain: exactly a majority, so a new leader needs all three votes. S1, still convinced it leads term 2, accepts a client write as entry 7 but can replicate it nowhere.

    S5’s timer fires first: term 3, RequestVote with its last log entry (index 5, term 2). S2 and S4 have entry 6 of term 2, a more up-to-date log (compare the last entry’s term, then the log length), so they deny the vote, although they adopt term 3. S5 cannot win.

    Next S2 times out: term 4, last entry (6, term 2). S4 and S5 grant: S2 is leader with 3 of 5 votes and repairs S5’s log, sending entry 6 and its own no-op. Committed entry 6 survived, because every majority contains a server that has it and that server refuses to vote for a log without it.

    Scripted illustration.

    Scene: S1 is cut off and S3 is down; the client’s write to S1 gets no answer. S5 asks for votes in term 3 but S2 and S4 deny them because their logs contain entry 6. S2 then asks in term 4; S4 and S5 grant, S2 becomes leader and sends S5 the missing entry.

    Key idea: The election restriction: voters refuse candidates whose log is behind theirs, so a new leader always holds every committed entry.

  8. 8. Terms unmask the old leader

    While isolated, S1 still believed it was leader of term 2. It even accepted a client write as entry 7 (term 2), but it could never reach a majority, so that entry was never committed and the client never got a success.

    The partition heals. S1 sends AppendEntries with term 2. S2, S4 and S5 are in term 4: they reject it and reply with their term. Seeing a higher term, S1 immediately steps down to follower and adopts term 4. S2’s first AppendEntries to S1 says prevLogIndex = 7, prevLogTerm = 4; S1’s entry 7 has term 2, so S1 refuses. S2 backs up one entry and sends entry 7 with prevLogIndex = 6. That matches, so S1 deletes its conflicting entry 7 and appends the leader’s. Logs converge; nothing committed was lost.

    Scripted illustration.

    Scene: The partition heals. S1 sends AppendEntries for term 2; S2, S4 and S5 reject them with term 4, so S1 steps down. S2’s first AppendEntries to S1 fails the log check at index 7; S2 retries from index 7, and S1 replaces its uncommitted entry 7 and acknowledges.

    Key idea: Every message carries a term. A leader that sees a higher term steps down; its uncommitted entries are overwritten by the current leader.

  9. 9. What to remember about Raft

    Raft elects one leader per term with randomised timeouts and majority votes. The leader appends client commands to its log, replicates them with AppendEntries and commits each entry once a majority stores it.

    Followers that fall behind are repaired from the leader’s log. When the leader fails, writes pause for about one election timeout. The election restriction guarantees that a new leader has every committed entry, and terms make stale leaders step down.

    Scene: A five-server Raft cluster with S2 as leader of term 4, S3 still down, and a client.

    Key idea: One leader per term, commit on a majority, and only up-to-date logs win elections.