Five servers can lose two and keep working, and they never crown two leaders. The trick is a majority: any two groups of three out of five share at least one server.
Cut the network between the servers, then switch from "any side elects" to "majority". Try four servers split two and two. Then we build, piece by piece, how Raft elects a leader, copies a log and decides when an entry is safe.
You need a little Python and what a message between two machines is. Failure and Time helps. We build the rest from zero.
Illustrative toy: a client on each side tries to write x. Each side elects a leader if the rule allows it. Chapter 0 gives the arithmetic and Chapter 4 the proof.
Chapter 0
Add copies to survive a crash, then see why the copies need a majority to decide anything
One database server holds your data. Its disk dies at 2 a.m., and every write since the last backup is gone. The fix sounds easy: keep copies on three servers. If one dies, two remain.
Copies must agree. A client writes "balance = 100" to server A, and another reads 200 from server B. Worse, the network may cut A off from B and C. Each side may think the other is dead. If both sides accept writes, you get split brain: two leaders, two histories, and no way to merge them safely.
This happens in production. On 21 October 2018, a 43-second network cut at GitHub moved its primary MySQL database to the West Coast. The old primary held writes that never copied west, and the new one took writes for about 40 minutes. Both sides held writes the other lacked; the site ran degraded for 24 hours and 11 minutes.
The cure is a rule: a decision needs a majority, more than half of all servers. Two sides cannot both hold a majority, so they cannot both decide. Call the number of servers N and the number of crashes you want to survive f.
N equals two f plus one.
A majority q is half of N, rounded down, plus one. After f crashes, N minus f servers are left, and they must still be at least q. The smallest N that allows f crashes is two f plus one.
With f = 2: N = 2 × 2 + 1 = 5, and q = 3. Two servers die, three remain, and three is a majority. A fourth server does not help a cluster of three: with N = 4, q = 3, so it still survives only f = 1.
Each circle is a server. Drag the crash slider and watch the live count against the majority line. Then compare four servers with three.
Illustrative. The uptime figure assumes each server is up 99% of the time and servers fail independently. Real failures are often correlated (one rack, one bad deploy), so treat it as a best case.
By the FLP result (Failure and Time), no algorithm can promise progress in every run. So Raft and Paxos stay safe whatever the delays, and make progress when the network behaves. Both assume crash faults: a server stops, but it never lies.
Failure. Symptom: after a network cut heals, two copies hold different writes for the same rows. Measure: compare the last acknowledged write on each side. Cause: a write was acknowledged before a majority stored it. Fix: acknowledge only after a majority has the write.
Chapter 1
Replicate the list of commands instead of the data, and agree only on their order
Copying a whole database after every change is slow. There is a better idea. Treat each server as a state machine: a program whose next state depends only on its current state and the next command. Give every copy the same commands in the same order, and every copy ends in the same state.
This is state machine replication. The commands live in a log, a numbered list that only grows at the end. Each copy applies entry 1, then entry 2, and so on. So the hard problem shrinks to one question: what is entry number k? The algorithm that answers it is a consensus algorithm.
Order matters as soon as two commands do not commute. "SET x = 5" then "SET x = 8" leaves 8. The other order leaves 5. Try it with two replicas that hear the commands in different orders.
Blue cards are commands; the purple box is each replica's state. Pick a mode, then press Replay to watch the commands apply one by one.
Illustrative toy with three commands. In the third mode both replicas follow the log, but the last command asks each replica's own clock for the time.
The third mode shows the other trap. A command must give the same result on every copy, so it may not read the local clock, a random number generator or an outside service. The leader resolves these once, before it writes the entry. "SET t = now()" becomes "SET t = 10:00:00.120" in the log, and every copy stores that exact value.
Agreeing on a log order and consensus are the same problem in two forms. Chandra and Toueg (1996) showed that each one can be built from the other. Raft builds the log by running agreement on one entry after another, with one leader choosing the order.
Failure. Symptom: two replicas hold the same log but report different checksums. Measure: diff their state and find the first key that differs. Cause: a command read a local clock, a random value, or the order of a hash map. Fix: let the leader fix every such value inside the log entry.
Chapter 2
Number time in terms, give each server one vote per term, and break ties with random timers
Raft (Ongaro and Ousterhout, 2014) puts one leader in charge of every write and of the log order. The other servers are followers. Each follower runs an election timer that restarts at every heartbeat from the leader.
If the timer runs out, the follower becomes a candidate. It adds one to its term, a counter that numbers each election. It votes for itself and sends a RequestVote message to every server. A server grants at most one vote per term, and stores that vote on disk before it answers. A candidate with a majority of votes becomes leader for that term.
Every message carries its sender's term. A server that sees a higher term takes it and becomes a follower, so a returning old leader steps down at the first reply.
If two followers time out almost together, they split the votes and nobody wins. So Raft draws each timer at random from a range, say 150 to 300 ms. Call the width of that range w, the time a RequestVote takes to arrive d, and the number of followers still counting n.
P equals one minus, one minus d over w, all to the n.
Each timer lands at a random point in a window w wide. The election is clean if the second timer fires more than d after the first. For n timers, that chance is one minus d over w, multiplied by itself n times. P is the rest.
With made-up numbers: a five-server cluster loses its leader, so n = 4, with w = 150 ms and d = 5 ms. P = 1 − (1 − 5/150)4 = 0.127. About one election in eight is contested; a simulation of 400,000 elections agrees.
Yellow bars are timers. The first to run out sends blue RequestVotes; pink marks a rival that fired before they landed. Drag the spread toward zero.
Illustrative: timers are 150 ms plus a random part up to w. A follower that grants a vote restarts its timer.
In the Raft paper, with no randomness, repeated split votes made elections take over 10 seconds. With 5 ms of randomness, the median time without a leader fell to 287 ms. The paper's rule: the election timeout is far longer than a round of messages and far shorter than the time between crashes. etcd uses 100 ms heartbeats and a 1,000 ms timeout.
Failure. Symptom: a server cut off for a minute rejoins with term 57 and forces an election. Measure: term jumps in the logs. Cause: alone, it kept raising its term. Fix: Pre-Vote (Ongaro's thesis): ask "would you vote for me?" before raising the term. etcd offers it.
Chapter 3
Check one entry to trust a whole prefix, back up to repair a follower, and commit when a majority holds an entry
Each log entry holds a command and the term in which a leader created it. The leader sends new entries with an AppendEntries message, which doubles as the heartbeat when it carries none. Each message names the entry just before the new ones: its index prevLogIndex and its term prevLogTerm.
A follower accepts only if its own log has that entry with that term. By Raft's Log Matching property, two logs with the same index and term at one entry are identical up to it. If the check fails, the leader steps back one entry and retries. On a match, the follower drops everything after that point and takes the leader's entries.
When is an entry safe? The leader keeps matchIndex, the highest entry it knows each server holds. An entry is committed once a majority holds it; only then does the leader apply it and answer the client. Call matchIndex for server i mi, the majority q, and the commit index c.
c equals the q-th largest of m-one through m-N.
Sort the matchIndex values m-i from high to low. Read the one in place q. At least q servers hold every entry up to that index, so c moves there. Raft adds one condition, the subject of the next chapter: the entry at c must come from the leader's current term.
From the device below: matchIndex is 6, 6, 0, 4, 2 for S1 to S5, and q = 3. Sorted: 6, 6, 4, 2, 0. The third value is 4, so c = 4. Once S3 is repaired to 6, the list is 6, 6, 6, 4, 2, and c = 6.
Top: the leader's log and follower S3's log; numbers are terms. Bottom: matchIndex for every server, with the commit index in green. Press Step to send the next AppendEntries.
Illustrative logs. S3 once followed a term-2 leader that died, so it holds two term-2 entries nobody committed. The leader steps back one entry per try, as in the paper; real systems often skip back a whole term at once.
A follower must store new entries, its term and its vote on disk before it replies, or a restart could make it forget a promise. That disk write often costs more than the network, so etcd recommends SSDs.
Failure. Symptom: writes stall although every server is up. Measure: each follower's matchIndex over time. Cause: three of four followers sit on slow disks, so the third-largest matchIndex crawls. Fix: fast disks; the commit index moves at the speed of the q-th fastest server.
Chapter 4
Use the overlap of two majorities, check the candidate's log, and count only entries of the current term
The promise of consensus: once an entry is committed, every future leader has it. Raft keeps it with three pieces. The first is arithmetic. Any two majorities share a server. How large is the overlap? Call two groups of servers Q1 and Q2, drawn from the same N servers.
The size of Q-one intersect Q-two is at least the size of Q-one plus the size of Q-two, minus N.
Put both groups into N seats. If Q-one and Q-two together have more members than there are seats, some seats must hold a member of both. The surplus, the size of Q-one plus the size of Q-two minus N, is the smallest possible overlap.
N = 5 and two majorities of 3: overlap ≥ 3 + 3 − 5 = 1. A group of 2 and a group of 3: 2 + 3 − 5 = 0, so they can be disjoint. That is why a minority may never decide.
The second piece is the election restriction. A voter refuses a candidate whose log is less up to date than its own. The last entry's term decides; on a tie, the longer log wins. The servers that voted overlap the servers holding each committed entry, so the winner holds every committed entry.
The third piece is subtle. A leader may not mark an entry committed by counting copies if the entry comes from an older term. Step through the paper's Figure 8 to see why. Then switch the rule.
Rows are servers S1 to S5, columns are log slots, numbers are terms. A green outline is an entry the leader has called committed. Pick a rule and an ending, then step.
The scenario and its votes are Figure 8 of Ongaro and Ousterhout (2014). The vote counts in the read-out follow the election restriction, checked by a script.
Under Raft's rule the term-2 entry commits only when S1 commits an entry of its own term 4 after it. Then S5, whose last term is 3, cannot win. Leaders in etcd and others append an empty entry at the start of each term for this reason, so older entries commit quickly.
Failure. Symptom: a write the client saw acknowledged is gone after two leader changes. Measure: replay the terms and votes, and check where an older-term entry was marked committed. Cause: a home-grown Raft counted copies of an older-term entry. Fix: count only entries of the current term.
Chapter 5
Make every read set meet every write set with R + W > N, and see Paxos use the same overlap
Majorities are one kind of quorum: a set of servers big enough that any two sets overlap where they must. Amazon's Dynamo (DeCandia and others, 2007) uses quorums with no leader at all. Each key lives on N replicas. A write waits for W of them to answer, and a read asks R of them and keeps the newest version it sees.
The read finds the latest write if its R replicas meet the write's W replicas. Call the number of replicas per key N, the write quorum W and the read quorum R.
R plus W is greater than N.
By the overlap rule of Chapter 4, a read set of R and a write set of W share at least R plus W minus N replicas. If R plus W is more than N, that is at least one, so every read meets the latest write.
Dynamo's common setting, from the paper: N = 3, R = 2, W = 2. Then 2 + 2 = 4 > 3, overlap at least 1. With R = 1 and W = 1, a random read misses the one written replica 2 times in 3.
Purple replicas hold the new version v2; the rest still hold v1. A teal ring marks the replicas the read asked. Change R and W, and press Read again for a new random read set.
Illustrative. Replica reply times are made up (4, 6, 9, 30, 120, 15, 50 ms); a write waits for the W fastest. The miss chance assumes the read picks R replicas at random.
Latency sits on the same knob: a write waits for the W-th fastest replica. With replies of 4, 6, 9, 30 and 120 ms, W = 3 waits 9 ms. Dynamo also uses a sloppy quorum. If a home replica is down, a stand-in stores the write, and R + W > N no longer promises overlap.
Paxos (Lamport, "Paxos Made Simple", 2001) chooses one value in two phases. In phase 1 a proposer sends prepare(n) with a fresh number n. Each acceptor promises to ignore lower numbers and reports any proposal it already accepted. In phase 2 the proposer asks a majority to accept (n, v), where v is the reported proposal with the highest number, if any. Overlap carries a chosen value to every later proposer.
Failure. Symptom: a user saves a profile and the next page shows the old one. Measure: the R and W the client sends. Cause: R = 1 and W = 1 on N = 3. Fix: R = 2 and W = 2 for reads that must see the last write.
Chapter 6
Name the consistency models, then pick the read path that keeps the promise you need
Writes go through the log, but where does a read go? The answer depends on the promise, or consistency model, the system makes to clients. Four models matter, from strongest to weakest.
A follower applies a committed entry a little after the leader does. This delay is the replication lag. A read served from the follower's local copy during the lag returns the old value, even though the write was already acknowledged. That breaks linearizability.
Client A writes x = 1; the leader acknowledges at 5 ms. Yellow is the follower's lag. Pick a read path, then drag when client B reads.
Illustrative: one round trip between servers takes 2 ms. A read that starts before 5 ms overlaps the write, so either value is allowed.
The worked number: the leader acknowledges at 5 ms. The follower lags 30 ms, so it applies the write at 35 ms. B reads the follower at 12 ms and gets x = 0. The read began 7 ms after the acknowledgement, so a linearizable system must return 1.
There are three read paths. With ReadIndex, the leader notes its commit index, confirms with one heartbeat round that it is still leader, and answers once it has applied up to that index. A follower can do the same by asking the leader for the index first. A lease read skips the heartbeat round but trusts that clocks drift slowly. etcd serves linearizable reads by default and offers "serializable" local reads that may be stale. ZooKeeper serves reads locally; a client calls sync first when it needs the latest value.
Failure. Symptom: a job scheduler runs a job twice, because a worker read "unclaimed" from a lagging replica. Measure: replication lag on the replica that served the read. Cause: a local read used for a check-then-act. Fix: linearizable reads for every check that guards an action.
Chapter 7
Pass each write down a line of servers, read from the end, and trade latency for throughput
A Raft leader sends every entry to every follower. For big values, its outgoing link fills up first. Chain replication (van Renesse and Schneider, 2004) arranges the servers in a line instead. A write enters at the head, each server stores it and passes it on, and the tail replies to the client. Reads go to the tail.
The tail holds only writes that every server before it holds. So a read at the tail sees exactly the committed writes, and the system is linearizable without a vote per write. What limits the write rate? Call one link's bandwidth B, the size of one write s, and the number of servers N. Call the most writes per second X.
X equals B over, N minus one times s.
The leader sends N minus one copies of each write of s bytes. Divide the link bandwidth B by those bytes to get X. In a chain each server sends one copy onward, so the limit is B over s.
With made-up numbers: B = 125 MB/s (1 Gbps), s = 1 MB, N = 5. Raft: X = 125 / (4 × 1) = 31 writes per second. Chain: 125 / 1 = 125 writes per second, four times more.
Blue dots are copies of one write. Watch where they leave from. Pick a shape, then change N and the write size.
Illustrative: a 1 Gbps link per server, propagation only. Latency counts the trips between servers in units of one round trip.
The price is latency. Raft waits about one round trip for a majority of replies. A chain of N servers needs N minus 1 one-way hops before the tail replies: for N = 5, that is 2 round trips. Chain replication also cannot elect anyone. When a server fails, an outside master, itself a Paxos or Raft group, rebuilds the chain. CRAQ (Terrace and Freedman, 2009) lets any server answer reads for objects with no write in flight.
Failure. Symptom: writes crawl at about 31 per second on a Raft cluster storing 1 MB blobs. Measure: the leader's outgoing bandwidth sits at the link limit. Cause: the leader sends every blob four times. Fix: keep only metadata in Raft and the blobs elsewhere, or use a chain for the data.
Chapter 8
Send writes, crash the leader and cut the network on five servers running real Raft rules
This cluster runs the rules of the previous chapters: random election timers, RequestVote with the log check, AppendEntries with the consistency check, and the current-term commit rule. Each new leader appends an empty entry for its term. Watch the logs under the servers: purple entries are stored, green ones are committed on that server.
Blue dots are RequestVote and AppendEntries; teal dots are replies. The yellow arc is each follower's election timer. Send a few requests, then crash the leader or cut the network.
Illustrative timings, slowed down: messages take 40 to 70 ms, heartbeats go every 150 ms, timers run 600 to 1,200 ms. This code passed 400 random runs of crashes and cuts. No term had two leaders, and no committed entry was lost.
Things to try:
The worked number: with five servers and two crashed, the leader needs replies from both live followers, because 1 + 2 = 3 = q. With three crashed, 1 + 1 = 2 < 3, so nothing commits. That is safety before progress: the cluster stops instead of risking two histories.
Failure. Symptom: a client's write timed out, yet the value shows up later. Measure: find the entry's index and term in the leader's log. Cause: the leader stored it, then lost its majority before commit; a later leader with the entry committed it. Fix: retry with an idempotency key, so a duplicate retry applies once.
Chapter 9
Keep small critical data in a consensus store, fence every lock, and pay 3f + 1 if servers can lie
Most systems run a small coordination store and keep the bulk of the data elsewhere. etcd uses Raft and holds the state of a Kubernetes cluster. ZooKeeper uses its own protocol, Zab. They hold leaders, locks, membership and configuration: small, critical, rarely written. etcd caps a request at 1.5 MiB by default. It suggests at most 8 GiB of data.
A common use is a lock with a lease, which frees itself if its holder stops renewing it. The danger: the holder pauses for a long garbage collection, the lease runs out, and a second client takes the lock. Then the first wakes and writes. The cure is a fencing token, a number that grows with each grant, such as ZooKeeper's zxid. The storage rejects any token lower than the highest it has seen.
Yellow is client 1's 10-second lease, pink its pause. Blue arrows are writes with their tokens. Drag the pause past 10 s, then turn token checks on.
Illustrative: client 1 gets token 33 at 0 s and pauses at 1 s. Client 2 gets token 34 at 10.5 s and writes at 11 s.
Changing membership is a second trap. Going from 3 servers to 5 in one step, an old majority of 2 and a new majority of 3 may not overlap: 2 + 3 − 5 = 0. The Raft paper uses joint consensus, where both configurations must agree. Ongaro's thesis changes one server at a time.
Everything so far assumes servers that stop but never lie. A server that sends false messages is Byzantine. PBFT (Castro and Liskov, 1999) tolerates such faults with more servers. Call the number of lying servers to survive f.
N equals three f plus one.
PBFT waits for 2f + 1 servers, because f may never answer. Two such quorums overlap in at least f + 1 servers. At most f of those lie, so at least one honest server is in both. That needs N = 3f + 1.
With f = 1: N = 4, quorum 3, overlap 3 + 3 − 4 = 2, so one honest server is shared. Crash faults need only 3 servers for f = 1. And every server talks to every other, so messages grow with N squared.
Failure. Symptom: two workers both processed the same job during a long GC pause. Measure: lease expiry times against the pause log. Cause: a lease lock with no fencing token. Fix: pass the lock's token with every write, and reject lower tokens at the storage.
Chapter 10
Keep the numbers, the checklist and the code for the next time a cluster loses its leader
Replication needs agreement, and agreement needs overlap. A majority of 2f + 1 servers survives f crashes, and two majorities always share a server. In Raft, random timers elect one leader per term, AppendEntries copies logs, and a current-term entry commits on a majority. Dynamo and Paxos use the same overlap. Reads, chains and locks each need their own care.
| Term | What it is | This lesson's number |
|---|---|---|
| Crash faults | N = 2f + 1, majority q = ⌊N/2⌋ + 1 | f = 2: N = 5, q = 3; N = 4 still survives 1 |
| Contested election | P = 1 − (1 − d/w)n | n 4, w 150 ms, d 5 ms: 0.127 |
| Commit index | c = q-th largest matchIndex, current term | 6, 6, 0, 4, 2: c = 4 |
| Quorum overlap | |Q1 ∩ Q2| ≥ |Q1| + |Q2| − N | 3 + 3 − 5 = 1 |
| Dynamo quorum | R + W > N | (3, 2, 2); R = W = 1 misses 2 in 3 |
| Leader link limit | X = B / ((N − 1) · s) | 1 Gbps, 1 MB, N 5: 31 writes/s; chain 125 |
| Byzantine faults | N = 3f + 1, quorum 2f + 1 | f = 1: N = 4, quorum 3 |
| etcd defaults | heartbeat, election timeout, request, quota | 100 ms, 1,000 ms, 1.5 MiB, 2 GiB |
| Job | Use | Why |
|---|---|---|
| Leader, lock, config, membership | Raft or Paxos store (etcd, ZooKeeper) | Small, critical, linearizable |
| High-volume key-value data | Sharded store, a Raft group per shard, or quorums | One group cannot carry it all |
| Large objects, strong reads | Chain replication with an outside master | No leader fan-out on the data path |
| Always writable, conflicts allowed | Dynamo-style quorums and version vectors | Keeps taking writes during a cut |
| Servers that may lie | PBFT and its descendants | 3f + 1 servers outvote f liars |
python# the two Raft handlers that carry the safety argument, and the commit rule def on_request_vote(s, term, cand, last_idx, last_term): if term > s.term: s.term, s.voted, s.role = term, None, "follower" my_last = s.log[-1].term if s.log else 0 up_to_date = last_term > my_last or (last_term == my_last and last_idx >= len(s.log)) ok = term == s.term and s.voted in (None, cand) and up_to_date if ok: s.voted = cand; s.persist(); s.reset_timer() # vote on disk before replying return s.term, ok def on_append_entries(s, term, leader, prev, prev_term, entries, leader_commit): if term < s.term: return s.term, False s.term, s.role = term, "follower"; s.reset_timer() if prev > len(s.log) or (prev > 0 and s.log[prev - 1].term != prev_term): return s.term, False # leader steps back and retries for k, e in enumerate(entries): i = prev + k # 0-based slot of entry k if i < len(s.log) and s.log[i].term != e.term: del s.log[i:] if i >= len(s.log): s.log.append(e) s.persist() s.commit = max(s.commit, min(leader_commit, prev + len(entries))) return s.term, True def advance_commit(leader, match): # match: matchIndex of every server, leader included q = len(match) // 2 + 1 c = sorted(match, reverse=True)[q - 1] # the q-th largest if c > leader.commit and leader.log[c - 1].term == leader.term: # current term only leader.commit = c
Now press Present or Teach and explain five things from memory. Explain why N = 2f + 1 and how random timers settle an election. Explain how a leader repairs a log, why Figure 8 forbids counting old-term entries, and why R + W > N works. Then go back to the hero, choose four servers and split them two and two.