---
title: "Raft Consensus"
description: "Leader election and log replication"
source: https://vizlearn.app/cs/distributed/raft
access: premium (interactive player requires Lifetime; this doc is free)
---

# Raft Consensus

Raft consensus keeps a replicated log safe while servers time out, messages arrive late, and leaders change. This lesson follows a five-server cluster through leader election and current-term commitment, then breaks the network in two to show the boundary that matters: a minority may store an entry, but only a majority can commit it.

Picture five clerks maintaining identical numbered ledgers. One clerk is allowed to assign the next line. Before that line becomes official, at least three clerks must hold the same text. A clerk can write something in pencil on two ledgers, but a later leader may erase it. The majority line is what separates a tentative note from the history everyone must preserve.

## How Raft consensus works

Every server carries three pieces of state that matter on this canvas: a **role**, a **current term**, and a **log**. Roles are `Follower`, `Candidate`, or `Leader`. Terms are election epochs. A log entry is identified by both its index and its term; `4/t5` and `4/t6` occupy the same position but are not the same entry.

Followers expect periodic `AppendEntries` heartbeats from a leader. If one follower's election timer expires, it increments its term, becomes a candidate, votes for itself, and sends `RequestVote`. A server grants at most one vote per term, and only to a candidate whose log is at least as up to date as its own. In a five-server configuration, three votes elect a leader. A timeout or one vote does not.

The leader accepts a client command by appending it to its own log, then sends `AppendEntries` to followers. Each RPC names the previous log index and term. That pair checks that leader and follower share the same prefix before the follower stores the new suffix.

The animation keeps storage and commitment separate. An entry can appear in blue, purple, or green log cells before the leader's `commitIndex` moves. For a current-term entry, the leader advances `commitIndex` after it knows that a majority stores the entry. Followers learn that boundary later through the `leaderCommit` field in another `AppendEntries` RPC. There is no global commit switch that flips on every server at once.

Election and replication use the same three-of-five threshold, but they count different evidence. The quorum strip says `votes` during an election and `replicas(index n)` during replication. Watch the label before reading the filled boxes.

## Raft consensus step by step

The default **Minority partition** run starts healthy, then follows one write on each side of a `2 | 3` split. These are causal stops rather than a transcript of every moving RPC.

1. **S1 leads term 5.** All five servers have committed through index 3.
2. **The network splits `2 | 3`.** S1 still believes it is leader, but it can reach only S2.
3. **S1 accepts `set y=7`.** It stores `4/t5` locally as a tentative, pencil entry.
4. **S2 stores the same entry and replies.** S1 knows about two copies; both `commitIndex` values stay at 3.
5. **The minority stalls at `2 / 5`.** Two matching disks are evidence of storage, not a commitment certificate.
6. **The quorum comparison explains the boundary.** Two-server certificates can be disjoint; any two three-server majorities must overlap.
7. **S3 times out on the other side.** It enters term 6 and votes for itself.
8. **S4 and S5 grant votes.** `{S3, S4, S5}` reaches `3 / 5`, so S3 becomes the higher-term leader.
9. **S3 accepts `set z=8`.** It assigns the same index 4 in term 6.
10. **S4 stores `4/t6` and acknowledges.** Two copies still do not commit.
11. **S5 stores the third copy.** Its acknowledgement tells S3 that the majority exists.
12. **S3 crosses the replication quorum.** Only now does it advance `commitIndex` to 4 and apply `set z=8`.
13. **The network heals.** S1 has `4/t5`; S3 has the committed `4/t6`.
14. **S1 observes term 6 and steps down.** Role correction happens before suffix repair.
15. **S1 compares the matching prefix.** Both logs agree through `3/t5`, then conflict at index 4.
16. **S1 erases the pencil entry.** It deletes uncommitted `4/t5`, installs `4/t6`, and applies the committed command.
17. **The safety result is visible.** A minority write may occupy disk space, but it cannot enter committed history.

For a clean first pass through election and replication, switch to **Election + commit**. Its central four beats stay separate on purpose: the third copy exists, its acknowledgement reaches the leader, the quorum becomes explicit, and only then does `commitIndex` move.

## Why Raft consensus needs overlapping majorities

Any two majorities of a fixed five-server set overlap. Pick any three servers twice and at least one server appears in both groups. Raft uses that overlap to carry information across leadership changes: a candidate must win votes from a majority, and its log must pass the voters' up-to-date check.

The **Minority partition** preset makes the argument concrete. S1 and S2 are cut off from S3, S4, and S5. Old leader S1 can append `4/t5 set y=7` to itself and S2, but its quorum strip stops at `2 / 5`. The entry stays uncommitted.

Across the partition, S3 times out, enters term 6, and wins votes from S3, S4, and S5. For a while the canvas shows two local leadership views: S1 still sees itself as leader in term 5, while S3 is leader in term 6. This is not two valid leaders in one term. Only the term-6 leader can reach a majority.

S3 assigns index 4 to `set z=8`, replicates `4/t6` to S4 and S5, and commits it with three copies. When the network heals, S1 receives a term-6 `AppendEntries`. It first steps down, then compares the matching prefix. Both logs agree through `3/t5`; their entries at index 4 conflict. S1 deletes its uncommitted `4/t5` suffix and installs committed `4/t6`.

That overwrite is why a client must not treat the minority write as committed. It was real enough to occupy disk space, but it never crossed the safety boundary.

## Engineering consequences of the majority boundary

A Raft-backed service should not report a write as committed merely because the leader appended it locally or one follower replied. The leader first needs majority evidence. Some systems reply after commitment; others wait until the state machine has also applied the command. If a client times out and retries, the service still needs request IDs or deduplication—Raft orders commands, but it does not make repeated client calls execute exactly once by itself.

Cluster size changes both fault tolerance and the write path. Three voting servers tolerate one unavailable server; five tolerate two, while each commit waits for three replicas instead of two. That tradeoff suits control-plane and metadata state, where one consistent decision is usually worth more than maximum write throughput.

## Edge Cases

- **Two leaders on screen.** During the partition, S1 has not heard about term 6 and still calls itself leader. S3 has the higher term and the reachable majority. Raft prevents two leaders from being elected in the same term; it cannot make stale local beliefs vanish before a message arrives.
- **Same index, different term.** `4/t5` and `4/t6` are conflicting entries. Comparing only index 4 would hide the exact mismatch that drives repair.
- **Stored but uncommitted.** S1 and S2 keep `set y=7` for several beats. Raft does not need to erase a minority suffix immediately. It needs to keep that suffix out of the committed history.
- **Follower commit lag.** S2 may store index 3 while its `commitIndex` remains 2. The later heartbeat is not redundant; it carries the leader's new boundary.
- **Delayed servers.** S4 and S5 do not participate in the focused **Election + commit** run's initial election or commit. Liveness tolerates the delay because three servers remain reachable.
- **One vote per term.** A recorded `votedFor` belongs to the server's current term. A new term resets the decision; it does not create a second vote in the old term.
- **Old-term commitment rule.** The canvas commits entries created in the current leader's term. Raft's full rule for committing older-term entries is subtler: the leader first commits a current-term entry, which then commits the preceding prefix indirectly.

## Common Mistakes

- **Calling the timeout winner the leader.** A timeout creates a candidate. The leader badge appears only after the vote strip reaches three.
- **Calling a local append committed.** The leader's own copy starts the replica count at one. It does not finish the job.
- **Using two as a majority of five.** Majority is `floor(5 / 2) + 1 = 3`, not half rounded down.
- **Assuming commit knowledge is simultaneous.** The leader can show `commitIndex=3` while followers still show 2. Each server owns a local boundary.
- **Believing a partition stops all work.** It stops the two-server side from committing. The three-server side can elect and commit because it still forms a majority.
- **Treating higher term as a tie-breaker after log repair.** S1 steps down before processing the suffix. Term handling controls the role; prefix matching controls which entries are replaced.
- **Thinking every stored entry must survive.** Only committed history has that guarantee. The red ghost of `4/t5` is intentionally erased.
- **Demanding unanimity.** Waiting for all five would turn two slow servers into a cluster-wide outage. Raft's safety proof is built around overlapping majorities instead.

## A Note on Simplification

This lesson fixes the cluster at five servers and presents one RPC per beat. Election deadlines are deterministic; messages do not reorder inside a scene; heartbeats, retries, batching, persistence latency, membership changes, pre-vote, joint consensus, log compaction, and snapshots are omitted. The partition repair jumps directly to the matching-prefix result instead of animating every `nextIndex` decrement. S2 is left to catch up after the final minority-partition beat because its repair repeats S1's. The vote and current-term commit rules shown here are genuine Raft rules; the timing is staged so their evidence stays readable.
