← Back to Home

πŸ—³οΈ Consensus: Raft, Visualized

A live 5-server Raft cluster in your browser: crash servers, kill the leader and watch elections, log replication, commits and the safety rules that keep etcd consistent.

Kubernetes stores every pod, secret and deployment in etcd. If etcd's servers ever disagreed about the state of your cluster, with one saying a pod exists and another saying it doesn't, the control plane would start making contradictory decisions. etcd prevents that using Raft, an algorithm that gets several machines to agree on one sequence of changes even while some of them crash and the network delays messages.

This tutorial explains Raft from first principles, and lets you run it: below is a working 5-server Raft cluster in your browser. You can crash servers, kill the leader, send client requests, and watch elections and log replication happen message by message.

Context: the CAP article showed that a system which stays consistent during a partition must refuse requests on the minority side. Raft is how real CP systems (etcd, Consul, CockroachDB, TiKV, Kafka's KRaft mode) implement exactly that.

The Problem: Agreeing Over an Unreliable Network

Consensus means getting a group of servers to agree on a value, and in practice on a sequence of values: an ordered log of commands. The rules of the game are harsh:

What we want, despite all that:

Property Meaning
Safety Servers never disagree about a committed entry. Once something is committed, it stays committed, at the same position, everywhere
Liveness As long as a majority of servers are up and can talk to each other, the cluster keeps making progress

The replicated state machine

Raft doesn't replicate data directly. It replicates a log of commands. If every server starts from the same state and applies the same commands in the same order, every server ends in the same state. This works because the commands are deterministic.

        client: "set x = 3"
               β”‚
               β–Ό
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      replicate      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚ S1 (leader)          β”‚ ──────────────────▢ β”‚ S2 … S5 (followers)  β”‚
   β”‚ log: [x=1][y=2][x=3] β”‚                     β”‚ log: [x=1][y=2][x=3] β”‚
   β”‚        β–Ό apply        β”‚                     β”‚        β–Ό apply        β”‚
   β”‚ state: x=3, y=2      β”‚                     β”‚ state: x=3, y=2      β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
   same log + same order + deterministic commands = same state everywhere

The whole job of Raft is to keep that log identical on every server, even through failures.

Raft's Big Idea: One Leader at a Time

Paxos, the classic consensus algorithm, is famously hard to understand. Raft (Ongaro and Ousterhout, 2014) was designed to be understandable, and its main trick is to split the problem into pieces:

  1. Leader election: pick one server to be in charge.
  2. Log replication: the leader accepts commands and copies them to the followers.
  3. Safety: rules that guarantee a new leader never loses committed entries.

Every server is in one of three states:

                  election timeout,                 receives votes
                  no word from a leader             from a MAJORITY
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” ───────────────────▢ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” ───────────────▢ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚ FOLLOWER  β”‚                      β”‚ CANDIDATE β”‚                  β”‚  LEADER  β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ◀─────────────────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
        β–²          discovers a leader      β”‚ timeout: split vote,          β”‚
        β”‚          or a higher term        └── start a new election        β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              discovers a server with a higher term

Terms: Raft's logical clock

Time is divided into terms, numbered 1, 2, 3 and so on. Each term starts with an election, and has at most one leader. Every message carries the sender's term. If a server sees a higher term than its own, it immediately updates its term and becomes a follower. That one rule makes stale leaders step down automatically.

Try It: A Live Raft Cluster

The view: each circle is a server. The blue ring around a follower is its election timer running down. Moving dots are messages: orange is a vote request, green or red a vote reply, blue is AppendEntries (a heartbeat, or bigger when it carries log entries), and grey is the reply. The table underneath shows each server's log: dashed cells are uncommitted, solid cells are committed, and the colour shows the term each entry was created in.

5-server Raft cluster (click a server to crash or restart it)

followercandidateleadercrashed

    Experiments to try:

    1. Watch the first election. All servers start as followers with random timers. The first to time out becomes a candidate, asks for votes, and (usually) wins.
    2. Send client requests. Each one appears dashed on the leader, travels to the followers, and turns solid once a majority has stored it.
    3. Crash the leader. The followers stop getting heartbeats, one times out, and a new leader is elected in a higher term. No committed entry is lost.
    4. Crash two followers, then send requests. Three of five is still a majority, so everything still commits.
    5. Crash three servers. Requests still reach the leader but stay dashed forever: there's no majority to commit them. This is CAP's "CP" choice, made visible.
    6. Restart a crashed server. It comes back with its old log and an old term, and the leader fills in what it missed.

    Leader Election in Detail

    A follower that hears nothing from a leader for its election timeout (here 1.5–3 seconds; in etcd 1 second by default) assumes the leader is dead and starts an election:

       1. term = term + 1
       2. state = candidate, vote for myself
       3. send RequestVote(term, lastLogIndex, lastLogTerm) to every other server
       4. wait:
            β€’ votes from a MAJORITY      β†’ become leader, send heartbeats immediately
            β€’ AppendEntries from a valid leader (term β‰₯ mine) β†’ become follower
            β€’ timeout again (split vote) β†’ go back to step 1
    

    A server grants its vote if all of these are true:

    Why random timeouts?

    If every follower had the same timeout, they'd all become candidates at once, split the vote, time out together, and repeat forever. Randomising the timeout means one server usually times out first and wins before the others even start. The run below (from this simulator's test suite) shows a near-tie that still resolves:

       1.56 S2 timed out β†’ candidate for term 1, requests votes
       1.61 S4 timed out β†’ candidate for term 1, requests votes
       2.28 S2 won 3/5 votes β†’ LEADER for term 1
    

    S4 started only 50 ms after S2, but S2's requests reached a majority first. Each server votes only once per term, so S4 couldn't also win.

    Why a majority?

    Any two majorities of the same cluster overlap in at least one server. With 5 servers, two groups of 3 must share someone. Since each server votes once per term, two candidates can't both collect a majority in the same term. At most one leader per term follows directly.

       servers:    S1   S2   S3   S4   S5
       majority A: β–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆ
       majority B:           β–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆ  β–ˆβ–ˆβ–ˆ      ← S3 is in both; it can only vote once
    

    Log Replication in Detail

    Once elected, the leader handles all client requests:

       client          leader S1               followers S2…S5
         β”‚  "x=7"         β”‚                          β”‚
         │──────────────▢ β”‚ append to own log         β”‚
         β”‚                β”‚ (index 6, term 2)         β”‚
         β”‚                │── AppendEntries ─────────▢│ append to their logs, reply OK
         β”‚                │◀───────────────── OK ─────│ (from 2 followers so far)
         β”‚                β”‚                          β”‚
         β”‚                β”‚ stored on 3/5 = MAJORITY β†’ COMMITTED; apply to state machine
         │◀── "ok" ───────│                          β”‚
         β”‚                │── next AppendEntries carries leaderCommit = 6 ─▢ followers apply too
    

    Each AppendEntries message carries:

    Field Purpose
    term Lets followers reject a stale leader
    prevLogIndex, prevLogTerm "The entry just before these new ones is at index N with term T. Do you have it?"
    entries[] New entries (empty for a heartbeat)
    leaderCommit How far the leader has committed, so followers can apply entries too

    The consistency check

    The prevLogIndex/prevLogTerm check is the core of log replication. A follower only accepts new entries if its log matches the leader's at the previous position. If it doesn't match, the follower says no, and the leader steps back one entry and tries again, until it finds the point where the logs agree. Everything after that point is overwritten with the leader's entries.

       leader   S1 (term 3): [1:x=1][1:x=2][3:x=3][3:x=4][3:x=5]
       follower S4:          [1:x=1][1:x=2][2:y=8][2:y=9]      ← entries from a term-2 leader
                                                                 that crashed before committing them
    
       AppendEntries(prev = index 4, term 3)  β†’ S4's index 4 has term 2   β†’ reject
       AppendEntries(prev = index 3, term 3)  β†’ S4's index 3 has term 2   β†’ reject
       AppendEntries(prev = index 2, term 1)  β†’ match!  S4 deletes y=8, y=9 and appends x=3, x=4, x=5
    
       follower S4:          [1:x=1][1:x=2][3:x=3][3:x=4][3:x=5]  ← identical to the leader
    

    By induction this gives the Log Matching Property: if two logs have an entry with the same index and term, the logs are identical up to that point. This is what makes the whole log provably consistent, not just the latest entry.

    When is an entry committed?

    An entry is committed once the leader that created it has stored it on a majority of servers. Committed entries are durable: Raft guarantees that every future leader will have them. Only committed entries are applied to the state machine and acknowledged to the client.

    Safety: Why a New Leader Never Loses Committed Data

    Here's the danger. Suppose an entry is committed on S1, S2 and S3, and then S1 (the leader) crashes. What if S5, which never got the entry, wins the next election? It would overwrite everyone with a log that lacks a committed entry, and that's data loss.

    Raft prevents this with the election restriction: a voter refuses to vote for a candidate whose log is less up-to-date than its own. "More up-to-date" means a higher last term, or the same last term and a longer log.

       committed entry at index 6 lives on S1, S2, S3 (a majority)
       S1 crashes. S5 (missing index 6) times out and asks for votes:
    
       S2: "my log ends with index 6; yours ends at 5"     β†’ NO
       S3: "my log ends with index 6; yours ends at 5"     β†’ NO
       S4: (also missing index 6)                            β†’ yes
       S5 gets 2/5 votes. Not a majority. S5 can never win.
    
       Why: any majority S5 could gather must include someone from {S1, S2, S3},
       because two majorities always overlap, and that server will refuse.
    

    The same overlap argument again: the majority that stored the entry and the majority that elects the next leader must share at least one server, and that server's vote enforces the guarantee.

    The subtle rule: only commit entries from your own term

    One more rule is needed, and it's the trickiest part of the Raft paper (its "Figure 8"). A leader must not consider an entry from a previous term committed just because it's now on a majority. It only counts replicas for entries from its current term. Committing one of those then implicitly commits everything before it. Without this rule, an entry that reached a majority could still be overwritten by a later leader. The simulator implements this rule, and its test suite checks the safety properties after every step of 300 randomised runs with crashes and restarts:

    fuzz: 300 seeds Γ— 400 steps, 684 leader terms, 15883 committed entries, safety invariants held
    

    The checked invariants are election safety (at most one leader per term), state machine safety (no two servers ever commit different entries at the same index), and leader completeness (every leader's log contains every committed entry).

    Raft in Production

    Fault tolerance

    A cluster of 2f + 1 servers tolerates f failures:

    Servers Majority Failures tolerated Notes
    1 1 0 No fault tolerance
    3 2 1 The usual minimum (small etcd clusters)
    4 3 1 No better than 3, and slower: avoid even sizes
    5 3 2 Survives a failure during maintenance of another server
    7 4 3 Rare: every write waits for more servers

    More servers means more fault tolerance but slower writes, because each commit waits for a larger majority. That's why etcd recommends 3 or 5 members, not 9.

    What it costs

    Every committed write requires:

    So write latency is about one network round trip + two disk syncs, and throughput is limited by disk latency (see the commit costs in How a Database Works Inside). etcd's documentation is blunt about it: put etcd on fast SSDs, because slow fsyncs show up as election timeouts and leader changes.

    What real implementations add

    Feature Why
    Snapshots / log compaction The log can't grow forever. Periodically save the state machine and discard the log before it
    Membership changes Add or remove servers safely (joint consensus, or one server at a time)
    Pre-vote A server that was partitioned asks "would you vote for me?" before bumping its term, so it can't disrupt a healthy cluster when it rejoins
    Leader leases / ReadIndex Serve linearizable reads without writing a log entry for every read
    Batching and pipelining Many client commands per AppendEntries, without waiting for each reply

    Where you'll find Raft

    System Uses Raft for
    etcd All Kubernetes cluster state
    Consul Service catalogue and key-value store
    CockroachDB, TiKV, YugabyteDB One Raft group per data range, thousands per cluster
    Kafka (KRaft mode) Cluster metadata, replacing ZooKeeper
    HashiCorp Vault (integrated storage), Nomad Their own state
    RabbitMQ quorum queues Replicating queue contents

    Reading etcd's Raft state

    You can see the same concepts on a real etcd cluster:

    etcdctl endpoint status --cluster -w table
    # columns include: ENDPOINT, ID, IS LEADER, RAFT TERM, RAFT INDEX, RAFT APPLIED INDEX
    
    etcdctl endpoint status -w json | jq '.[].Status.header.raft_term'
    

    RAFT TERM increasing often means leader elections are happening, usually because of slow disks or network trouble. RAFT INDEX is the log length. RAFT APPLIED INDEX lagging far behind it means the state machine can't keep up.

    The Core Algorithm in Code

    The simulator on this page is about 290 lines of JavaScript: about 180 for the Raft core and the rest for drawing. Here is the heart of it, the follower's AppendEntries handler, which carries most of Raft's safety:

    // on a follower, when AppendEntries arrives from a leader
    if (b.term < s.term) return reply(false);                 // stale leader: reject
    s.state = 'follower';
    resetElectionTimer(s);                                     // a live leader exists
    const ok = b.prevLogIndex === 0 ||
      (s.log.length >= b.prevLogIndex && s.log[b.prevLogIndex - 1].term === b.prevLogTerm);
    if (!ok) return reply(false);                              // logs diverge: leader backs up
    b.entries.forEach((e, k) => {
      const idx = b.prevLogIndex + k;
      if (s.log[idx] && s.log[idx].term !== e.term) s.log.length = idx;   // drop conflicting suffix
      if (!s.log[idx]) s.log.push(e);
    });
    const match = b.prevLogIndex + b.entries.length;
    s.commitIndex = Math.max(s.commitIndex, Math.min(b.leaderCommit, match));
    reply(true, match);
    

    And the leader's commit rule:

    // on the leader, after a successful reply: find the highest index stored on a majority
    for (let N = s.log.length; N > s.commitIndex; N--) {
      const count = servers.filter((p) => matchIndex(p) >= N).length;
      if (s.log[N - 1].term === s.term && count >= majority) {  // only entries from MY term
        s.commitIndex = N;
        break;
      }
    }
    

    Go deeper: the Raft paper, In Search of an Understandable Consensus Algorithm, is unusually readable, and its Figure 2 fits the whole algorithm on one page. After this tutorial, read Figure 2 and you'll recognise every line.

    Copied to clipboard!