Summary#
Consensus is the problem of getting several machines to agree on a value, or on a sequence of values, even when some of them crash and the network delays or loses messages. Once a value is agreed, it never changes, and every machine that learns it learns the same one. Consensus is how distributed systems elect exactly one leader, keep configuration consistent, grant locks safely, and keep replicas identical. The standard way to use it is a replicated state machine: every server keeps a log of commands, consensus makes all the logs identical, and every server applies the same commands in the same order, so they all reach the same state. Paxos, by Leslie Lamport, was the first practical algorithm: a proposer must win promises from a majority before proposing, and must re-propose any value a majority might already have chosen, so two majorities, which always overlap, can never choose different values. Raft, by Diego Ongaro and John Ousterhout, solves the same problem in a form designed to be understandable. A leader is elected for a term by majority vote, it appends client commands to its log and replicates them to followers, and an entry is committed once a majority has stored it. A cluster of 2f + 1 nodes tolerates f failures, so 3 nodes survive 1 failure and 5 nodes survive 2. The cost is latency, at least one round trip to a majority plus a disk flush per write, and throughput limited by one leader. That is why consensus is used for small, critical metadata, in etcd, ZooKeeper, Consul, Kafka's KRaft controller, Spanner's and DynamoDB's per-partition replication groups, rather than as a general-purpose data path.
Why It Exists#
Suppose you run a database on one server and replicate it to a second for safety. The primary takes writes and streams them to the replica. One day the primary stops responding. Should the replica take over?
- If the primary has crashed, yes. Otherwise the service is down.
- If the primary is alive but cut off from the replica by a network problem, and some clients can still reach it, then promoting the replica creates two primaries, each accepting different writes. That is split brain, and the data diverges.
- If replication was asynchronous, the replica may be missing the last few writes the primary acknowledged. Promoting it silently loses them.
The replica cannot tell these cases apart, as described in Failure Detection and Gossip. With two machines, there is no safe automatic answer. What is needed is a way for a group of machines to make decisions, such as "who is the leader now?" or "what is the next write?", that are:
- Agreed: every machine that decides, decides the same thing.
- Durable: once decided, the decision is never undone, even if machines crash and restart.
- Available despite failures: the group keeps deciding as long as a majority of machines are up and can talk to each other.
- Safe despite timing: wrong guesses about which machines are alive, slow messages and paused processes can delay decisions, but never cause conflicting ones.
That is the consensus problem. It sits at the heart of every system that must stay consistent while machines fail: coordination services, distributed databases, message brokers' metadata, and cluster schedulers. Almost nobody should implement it from scratch, but every system designer needs to know what it guarantees, what it costs, and when it is needed.
How It Works#
What consensus solves#
Formally, in the consensus problem, each of several processes may propose a value, and processes decide on a value, subject to three properties:
- Agreement: no two correct processes decide different values.
- Validity (or integrity): the decided value was proposed by some process. This rules out trivial solutions such as "always decide 0".
- Termination: every correct process eventually decides.
Agreement and validity are safety properties: something bad, two different decisions, never happens. Termination is a liveness property. As described in Distributed Systems Fundamentals, the FLP result (Fischer, Lynch and Paterson, 1985) proves that no deterministic algorithm can guarantee all three in a fully asynchronous network if even one process may crash. Practical algorithms therefore always guarantee safety, and guarantee termination only when the network behaves well enough for long enough, which in real systems is almost all the time.
Deciding one value sounds narrow, but many problems reduce to it:
- Leader election: decide which node is leader for term 7.
- Atomic broadcast (also called total order broadcast): decide the value of log slot 1, then slot 2, then slot 3, and so on. Every node delivers the same messages in the same order. Atomic broadcast and consensus are equivalent: each can be built from the other.
- Linearizable compare-and-set: decide whether "set x to 5 if x is 3" happens before or after a competing request. A linearizable compare-and-set register is enough to solve consensus, and consensus is enough to build one.
- Group membership and configuration: decide the current list of members, or the current configuration version.
- Distributed locks and leases: decide who holds lock L in epoch 12.
- Atomic commit is related but different: in two-phase commit, every participant must agree to commit, so one "no" aborts, whereas consensus only needs a majority. See Distributed Transactions.
What consensus solves, in depth#
Why simpler approaches fail. It is worth seeing why the obvious designs do not work, since they are exactly what systems tend to build by accident.
- A single coordinator decides. Correct and simple, but when the coordinator is down, nothing can be decided. Replacing the coordinator automatically is itself a consensus problem.
- Highest node ID that is alive becomes leader. Each node decides based on its own view of who is alive. During a partition, the two sides see different sets of live nodes, and each elects its own leader.
- Primary with asynchronous replication, plus automatic failover. The replica that is promoted may lack writes the old primary acknowledged, so failover loses data, and without a quorum, a partitioned primary keeps accepting writes, so failover can also cause split brain.
- Two-phase commit for replication. If the coordinator crashes after participants voted yes but before it tells them the outcome, they are stuck holding locks, unable to decide alone. That is the blocking problem of 2PC.
- Vote counting without numbered rounds. If proposers simply ask for votes, two proposers can each collect votes from overlapping groups at different times, and nodes that change their vote can let two values each believe they won.
Consensus algorithms fix all of these with two ideas: majorities, so any two decisions involve at least one common node, and numbered rounds (ballots in Paxos, terms in Raft), so nodes can tell old proposals from new ones and refuse the old.
Not every replicated system needs consensus. It is worth being precise about what does and does not run it:
- A rate limiter that keeps per-user counters in a sharded Redis can lose a few counters when a primary fails over, which only means a user briefly gets a slightly larger allowance. Redis's ordinary asynchronous replication with automatic replica promotion is enough, and the real design question is what to do while a shard is unavailable: fail open, letting traffic through unchecked and risking overload of the backends during the very spike that broke Redis, or fail closed, rejecting requests with 429 or 503 and taking the API offline for those users. A payment system or a platform protecting fragile backends during viral spikes may prefer fail-closed. A service where availability matters more than enforcing limits may fail open, with alerts. No consensus is needed, because nothing breaks if two shards briefly disagree.
- Cassandra's normal reads and writes use quorums of replicas without consensus: each replica accepts writes independently, conflicts are resolved by timestamp, and replicas that miss writes catch up later through hinted handoff, read repair and anti-entropy. That is a quorum system, but not consensus, because replicas can disagree on order. Cassandra's lightweight transactions (
INSERT ... IF NOT EXISTS, conditionalUPDATE) are different: they run a Paxos round among the replicas of the key, at a cost of several round trips, precisely because "only if" requires agreement. - Kafka's partition data uses leader-follower replication with an in-sync replica set, while the decisions about which replica is leader and which replicas are in sync are made by the controller, which in modern Kafka runs Raft (KRaft). This split, where consensus handles the metadata and a cheaper protocol handles the bulk data, is a pattern worth recognising. It is covered in depth below.
Replicated state machine#
Fred Schneider's tutorial "Implementing Fault-Tolerant Services Using the State Machine Approach" (ACM Computing Surveys, 1990) set out the pattern behind almost every use of consensus. Model the service as a deterministic state machine: a state, such as a key-value map, and commands that change it, such as put(k, v). If several servers start in the same state and apply the same commands in the same order, they end in the same state, and they produce the same outputs. So the only thing to agree on is the order of commands: a log.
Each server has three parts:
- A consensus module, which receives commands from clients, agrees with the other servers on where each command goes in the log, and tells the state machine when an entry is committed, meaning safely agreed and durable.
- The log, an append-only list of commands, stored on disk.
- The state machine, which applies committed entries in log order.
A client sends a command to the leader. The leader appends it to its log and replicates it. Once a majority has it on disk, it is committed, and every server applies it, in order. The leader replies to the client with the result. A follower that was down catches up by receiving the entries it missed. A new server joins by copying a snapshot of the state plus the later log. All of this works because the log is the single source of truth, and consensus makes the log identical everywhere.
Replicated state machine, in depth#
Determinism is a hard requirement. If applying the same command on two servers can produce different results, the replicas diverge, silently. Sources of non-determinism that must be removed before a command enters the log:
- Current time: "set expiry to now plus 10 minutes" gives different values on each server. The leader must compute the time once and put the result into the command.
- Random numbers and generated IDs: the leader generates them and logs the values.
- Iteration order over hash maps, which varies between runs in some languages.
- External calls: a command that calls another service would run once per replica. Side effects must happen outside the state machine, triggered after commit, idempotently.
- Floating-point and library differences across server versions, which matter during rolling upgrades.
Snapshots and log compaction. The log cannot grow forever. Periodically, each server writes a snapshot of its state machine as of some log index, and discards the log entries before it. A follower that is far behind, or a new server, receives the snapshot first and then the entries after it. Snapshots must be consistent with a log index, which state machines usually achieve with copy-on-write data structures, or by snapshotting an underlying storage engine such as RocksDB or bbolt at a point in time.
Reads need care too. A read that goes to the leader's state machine without going through the log can be stale, because the server may think it is leader while a new leader has already been elected elsewhere, after a partition. Options, from safest to fastest:
- Log reads: put the read through the log like a write. Always linearizable, but as expensive as a write.
- Read index: the leader records its current commit index, confirms it is still leader by getting a heartbeat response from a majority, waits until its state machine has applied up to that index, then serves the read locally. One round trip, no disk write. This is what etcd does for linearizable reads.
- Leader leases: followers promise not to elect a new leader for a lease period after acknowledging the leader, so the leader can serve reads locally during its lease without any round trip. Fast, but safe only if clock drift stays within assumed bounds and the leader does not pause past its lease. See Time and Ordering.
- Follower reads: serve from a follower, either accepting staleness or using a read index obtained from the leader. Good for scaling reads.
Exactly-once commands. If a client sends a command, the leader commits it, and the reply is lost, the client retries, and the command could be applied twice. The Raft dissertation's solution: each client has a unique ID and numbers its requests, and the state machine remembers the latest sequence number and response per client, returning the stored response for a duplicate instead of applying it again. This is idempotency built into the state machine. See Idempotency.
Paxos intuition#
Leslie Lamport described Paxos in "The Part-Time Parliament", written in 1989 and published in ACM Transactions on Computer Systems in 1998, as the procedures of a parliament on a fictional Greek island whose legislators wandered in and out of the chamber. The allegory confused many readers, so in 2001 he published "Paxos Made Simple", which begins by noting that the algorithm, explained plainly, is simple. It decides a single value, and its design shows why consensus works.
There are three roles. A single machine usually plays all three.
- Proposers propose values.
- Acceptors vote. A value is chosen when a majority of acceptors have accepted it in the same round.
- Learners find out which value was chosen.
Each attempt to choose a value uses a proposal number (ballot), unique across proposers and increasing, for example a counter paired with the proposer's ID. Each acceptor remembers two things on disk: the highest proposal number it has promised, and the proposal (number and value) it has most recently accepted, if any.
Phase 1, prepare and promise.
- A proposer picks a new proposal number n and sends prepare(n) to the acceptors.
- An acceptor that has not promised a number higher than n replies with a promise: it will ignore any proposals numbered below n from now on. In the promise, it includes the highest-numbered proposal it has already accepted, if any.
Phase 2, accept and accepted.
- If the proposer receives promises from a majority, it chooses the value to propose: if any promise reported an accepted proposal, it must use the value of the highest-numbered one. Only if none did may it use its own value. It sends accept(n, value).
- An acceptor accepts the proposal unless it has since promised a higher number, and tells the learners.
- When a majority of acceptors have accepted the same proposal, the value is chosen.
The heart of the algorithm is step 3. Suppose some value v has already been chosen, so a majority M1 accepted it at proposal number m. Any later proposer with a higher number n must collect promises from a majority M2. M1 and M2 overlap in at least one acceptor, so at least one promise reports having accepted v, or a later proposal that, by the same argument, also carried v. The proposer is therefore forced to propose v again. Once chosen, a value can never be replaced.
A worked example of the other case. Suppose Proposer 1's accept message reached only Acceptor 1 before it crashed. Then X was accepted by one acceptor, which is not a majority, so X was not chosen. Proposer 2 prepares with number 2 at Acceptors 2 and 3, neither of which accepted anything, so it is free to propose its own value Y, and Y is chosen. Acceptor 1 still holds an accepted X at number 1, but that does not matter: a later proposer that hears from Acceptor 1 together with Acceptor 2 or 3 will see Y at number 2, which is higher, and adopt Y.
| Scenario | Acceptors holding X at number 1 | Majority at number 2 includes | Proposer 2 must propose | Chosen value |
|---|---|---|---|---|
| X reached A1 and A2 | A1, A2 | A2, A3 | X, reported by A2 | X |
| X reached only A1 | A1 | A2, A3 | Its own value Y | Y |
| X reached only A1 | A1 | A1, A3 | X, reported by A1 | X |
In the third row, X was not yet chosen, but Proposer 2 happens to hear about it and re-proposes it, which is also safe. Paxos never needs to know whether a value was chosen. It only needs to never contradict one that might have been.
Liveness: dueling proposers. Two proposers can block each other forever. P1 prepares with 1, P2 prepares with 2, which invalidates P1's accept, P1 retries with 3, which invalidates P2's accept, and so on. Safety is never at risk, but nothing is chosen. The fix is to elect a distinguished proposer, a leader, so that normally only one node proposes. Leader election itself needs only to work eventually, which a failure detector with timeouts and random back-off provides, so this does not bring back the impossibility.
Paxos, in depth#
Multi-Paxos. Deciding a log, not just one value, means running one Paxos instance per log slot. Running both phases for every slot would cost two round trips per command. Multi-Paxos observes that phase 1 can be done once for all future slots: a stable leader sends a single prepare with its proposal number covering every slot from the current position onwards, and from then on, each command needs only phase 2, one round trip to a majority. When the leader changes, the new leader runs phase 1 again, learns any values accepted in slots it did not know about, and re-proposes them. This makes Multi-Paxos, in steady state, almost identical in cost to Raft: one round trip to a majority, plus disk writes, per command or batch of commands.
From the paper to production. "Paxos Made Live: An Engineering Perspective" (Tushar Chandra, Robert Griesemer and Joshua Redstone, PODC 2007) described building Google's Chubby lock service on Multi-Paxos, and listed everything the papers left out: how to elect and keep a leader (they used master leases so the leader could serve reads locally), how to change the group membership, how to take snapshots, how to handle disk corruption (a replica whose disk lost data must not vote as if it remembered its promises, so it rejoins as a non-voting member until it has caught up), and how to test the system. Their message was that turning a short algorithm into a correct, efficient production system took a large engineering effort, which is part of why Raft, which specifies these pieces, became popular.
Variants worth knowing.
- Fast Paxos (Lamport, 2006) lets clients send values directly to acceptors, saving a message delay when there is no conflict, at the cost of larger quorums, about three quarters of the acceptors, and a slower recovery when proposals collide.
- Flexible Paxos (Heidi Howard, Dahlia Malkhi and Alexander Spiegelman, 2016) showed that the two phases do not both need majorities: what matters is that every phase 1 quorum intersects every phase 2 quorum. With 10 acceptors, you could use phase 2 quorums of 3, making every write faster, if phase 1, which runs only on leader change, uses quorums of 8. This matters for geo-distributed deployments, where the write quorum can be kept within nearby regions.
- EPaxos, Egalitarian Paxos (Iulian Moraru, David Andersen and Michael Kaminsky, SOSP 2013), has no leader: any replica can commit commands, and commands that do not interfere, such as writes to different keys, commit in one round trip to a fast quorum of nearby replicas. Conflicting commands need an extra round and dependency tracking. It reduces latency in wide-area deployments, at the cost of considerable complexity.
- Vertical and reconfigurable Paxos variants handle changing the set of acceptors, which basic Paxos does not address.
Paxos in real systems. Google's Chubby and Spanner use Multi-Paxos, Spanner running one Paxos group per split of the data. Amazon DynamoDB, according to its published descriptions, replicates each partition across three availability zones with a Multi-Paxos group: the leader writes a log record and sends it to its two peers, a write is acknowledged once two of the three have persisted it, strongly consistent reads are served by the leader, and eventually consistent reads can be served by any replica. Apache Cassandra's lightweight transactions use Paxos rounds per key.
Raft#
Diego Ongaro and John Ousterhout published "In Search of an Understandable Consensus Algorithm" at USENIX ATC 2014, and Ongaro's 2014 Stanford dissertation, "Consensus: Bridging Theory and Practice", filled in the rest. Their goal was an algorithm as efficient and safe as Multi-Paxos, but easy to teach and to implement correctly. They split the problem into three parts that can be understood separately: leader election, log replication and safety. In a user study with students at Stanford and Berkeley, participants scored better on a Raft quiz than on an equivalent Paxos quiz. Today Raft runs in etcd, Consul, CockroachDB, TiKV, YugabyteDB, Kafka's KRaft controller, RabbitMQ quorum queues, and many more.
Roles and terms. Each server is in one of three states:
- Follower: passive. It responds to requests from leaders and candidates, and expects regular heartbeats.
- Candidate: a follower that has stopped hearing from a leader and is trying to become one.
- Leader: handles all client requests, appends them to its log and replicates them to the followers.
Time is divided into terms, numbered with consecutive integers. Each term begins with an election, and has at most one leader. A term can end without a leader if the vote splits, in which case a new term starts. Terms act as a logical clock: every message carries the sender's term, a server that sees a higher term immediately adopts it and becomes a follower, and requests with an older term are rejected. That single rule is what makes a deposed leader harmless: the moment it talks to anyone who has seen the newer term, it learns it is no longer leader.
A follower becomes a candidate when its election timeout fires. A candidate whose vote splits starts again in a new term. A candidate returns to follower if it hears from a legitimate leader or sees a higher term. A leader steps down to follower as soon as it sees a higher term.
Leader election.
- A follower that hears nothing from a leader for its election timeout increments its current term, becomes a candidate, votes for itself, and sends RequestVote to every other server.
- Each server grants at most one vote per term, first come first served, and records the vote on disk before replying, so it cannot vote twice after a crash.
- A server refuses its vote if the candidate's log is less up to date than its own: the candidate's last entry must have a higher term, or the same term and an index at least as large. This election restriction guarantees the winner already holds every committed entry.
- A candidate that receives votes from a majority becomes leader, and immediately sends heartbeats (empty AppendEntries messages) to stop new elections.
- If the vote splits and nobody wins, candidates time out and start a new term.
Randomised timeouts make split votes rare. Each server picks its election timeout at random from a range, 150 to 300 ms in the paper, so usually one server times out first, wins, and sends heartbeats before anyone else wakes up. The paper's measurements showed elections typically completing within a few hundred milliseconds. The timing requirement is that broadcast time, about 0.5 to 20 ms, is much less than the election timeout, which is much less than the mean time between server failures, typically months. Production systems use longer timeouts: etcd defaults to a 100 ms heartbeat interval and a 1,000 ms election timeout, and recommends raising both for cross-region clusters.
Log replication. Each log entry contains a command, the term in which the leader received it, and its index, its position in the log. The leader appends a client command to its log, then sends AppendEntries to every follower, containing the new entries plus two consistency fields: prevLogIndex and prevLogTerm, the index and term of the entry immediately before the new ones.
- A follower accepts the entries only if its own log has an entry at prevLogIndex with term prevLogTerm. Otherwise it rejects them.
- On rejection, the leader moves back, decrementing that follower's nextIndex, and retries with earlier entries, until it finds the point where the logs agree.
- At that point, the follower deletes any conflicting entries after the match, and appends the leader's entries. The leader never deletes or overwrites its own entries: logs flow only from leader to followers.
This check gives the Log Matching Property: if two logs contain an entry with the same index and term, then the logs are identical in all entries up to that index. It holds by induction, since each AppendEntries checks the entry before the new ones.
Commitment. The leader tracks, for each follower, the matchIndex, the highest entry known to be replicated there. An entry is committed once it is stored on a majority of servers, and it was created in the leader's current term. Committing an entry also commits all earlier entries. The leader advances its commitIndex, includes it in later AppendEntries, and followers apply entries up to that index to their state machines. The leader replies to the client after applying the entry.
A worked example of log repair. A five-server cluster has a new leader S1 in term 5. Each cell shows the term of the entry at that index.
| Server | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| S1, leader in term 5 | 1 | 1 | 2 | 3 | 3 | 5 | |
| S2 | 1 | 1 | 2 | 3 | 3 | ||
| S3 | 1 | 1 | 2 | ||||
| S4 | 1 | 1 | 2 | 4 | 4 | 4 | 4 |
| S5 | 1 | 1 | 2 | 3 | 3 | 5 |
- S2 is just behind. S1's AppendEntries for index 6 carries prevLogIndex 5 and prevLogTerm 3, which matches S2's log, so S2 appends entry 6.
- S3 is further behind. The check at index 5 fails, since S3 has no entry there. S1 steps back to prevLogIndex 3, which matches, and sends entries 4 to 6.
- S4 was briefly leader in term 4, appended four entries, and replicated none of them before losing contact. The check fails at index 5, where S4 has term 4 but S1 has term 3, and again at index 4. At prevLogIndex 3, term 2, the logs match. S4 deletes its entries 4 to 7, which were never committed, since no majority stored them, and copies S1's entries 4 to 6.
- S5 already matches.
Why is it safe to delete S4's entries, and why must S1 hurry? S4's entries 4 to 7 were only ever stored on S4, never on a majority, so they were never committed and no client was told they succeeded. In the other direction, S1's term 3 entries at indexes 4 and 5 sit on three of the five servers, yet they are not committed either, because they come from an older term: S4, whose last entry has term 4, could still win a later election with votes from S2 and S3, whose last entries have term 3 and term 2, and overwrite them. They become committed only when S1's own term 5 entry at index 6 reaches a majority, which happens as soon as S2 or S3 accepts it. From then on, no server lacking index 6 can win an election. This is exactly the subtle case explained next.
Stepping back one index at a time can take many round trips for a follower that is far behind. A common optimisation, described in the paper, is for the follower's rejection to include the term of the conflicting entry and the first index it holds for that term, so the leader can skip a whole term at once. Many implementations also send a snapshot if the follower needs entries the leader has already compacted away.
Raft, in depth#
Why "current term" matters in the commit rule: the Figure 8 scenario. The commit rule's second condition, that the leader only counts replicas for entries from its own term, is the most subtle part of Raft, illustrated in Figure 8 of the paper. Consider five servers:
- In term 2, S1 is leader. It appends entry 2 (term 2) and replicates it to S2 only, then crashes.
- In term 3, S5 is elected with votes from S3, S4 and itself (their logs are no less up to date). It appends a different entry at index 2, with term 3, and crashes before replicating it.
- In term 4, S1 restarts and is elected again. It continues replicating its old entry 2 (term 2), and now S1, S2 and S3 hold it: a majority.
- Is that entry committed? If S1 crashes now, S5 can win term 5 with votes from S2, S3 and S4, because S5's last entry has term 3, higher than term 2. S5 would then overwrite index 2 everywhere with its own term 3 entry. An entry stored on a majority would have been lost.
So an entry from an earlier term is not safe just because a majority stores it. Raft's rule avoids the trap: S1 in term 4 does not consider the term 2 entry committed by counting replicas. Instead, it appends a new entry in term 4, and once that entry reaches a majority, it and everything before it, including the term 2 entry, are committed. S5 can no longer win, because a majority now holds an entry from term 4, newer than S5's last entry. In practice, every new leader immediately appends a no-op entry in its own term, so that earlier entries get committed promptly, and so that read-index reads can be served safely, since the leader then knows the full commit index.
The five safety properties. The Raft paper proves that the algorithm maintains these at all times:
- Election Safety: at most one leader per term. Each server votes once per term, and two majorities overlap.
- Leader Append-Only: a leader never overwrites or deletes entries in its own log.
- Log Matching: if two logs have an entry with the same index and term, they are identical up to that index.
- Leader Completeness: if an entry is committed in some term, it is present in the logs of all leaders of later terms. This follows from the election restriction: the entry is on a majority, the winner got votes from a majority, the two overlap, and the overlapping voter would refuse any candidate whose log lacks it.
- State Machine Safety: if a server has applied an entry at a given index, no other server ever applies a different entry at that index.
The Raft authors also published a formal specification in TLA+, and Ongaro's dissertation includes a proof of safety. Several research groups later verified the protocol and implementations of it mechanically, for example the Verdi project at the University of Washington, which produced a verified Raft implementation in Coq (Wilcox and colleagues, PLDI 2015; Woos and colleagues, CPP 2016).
What must be on disk. A Raft server must persist, and fsync, three things before responding to any request: its currentTerm, its votedFor in that term, and its log entries. If it forgot its term or vote after a crash, it could vote twice in one term, allowing two leaders. If it acknowledged an entry without persisting it, a majority could "hold" an entry that vanishes on restart. The commit index and state machine can be rebuilt from the log and the latest snapshot. Running Raft on disks with write caches that lie about fsync, or on a filesystem mounted without durable writes, silently breaks these guarantees.
The core of the protocol fits in a page. Here is the follower side of AppendEntries:
on AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries, leaderCommit):
if term < currentTerm:
reply (currentTerm, success = false) # stale leader
if term > currentTerm:
currentTerm = term; votedFor = null; persist
state = FOLLOWER; resetElectionTimer(); leader = leaderId
if log has no entry at prevLogIndex
or log[prevLogIndex].term != prevLogTerm:
reply (currentTerm, success = false,
conflictTerm, firstIndexOfConflictTerm) # lets leader skip back
for each (i, e) in entries starting at prevLogIndex + 1:
if log[i] exists and log[i].term != e.term:
truncate log from i onwards # remove conflicting suffix
if log[i] does not exist:
append e
persist log (fsync)
if leaderCommit > commitIndex:
commitIndex = min(leaderCommit, index of last new entry)
apply entries up to commitIndex to the state machine
reply (currentTerm, success = true)Note the truncation is only of entries that conflict. A follower must not truncate entries that match just because a delayed, older AppendEntries arrived with fewer entries, or it could drop entries it had already acknowledged.
Membership changes. Adding or removing servers is dangerous: if servers switch from the old configuration to the new one at different moments, there could be a time when a majority of the old configuration and a majority of the new one are disjoint, and each elects a leader. Raft offers two solutions:
- Joint consensus, from the original paper: the leader first commits a special entry for the combined configuration, C old,new, during which every decision needs separate majorities of both the old and new configurations, and then commits the new configuration alone. At no point can the two sides decide independently.
- Single-server changes, from Ongaro's dissertation: add or remove one server at a time. Any majority of the old and new configurations then overlap automatically, so no joint phase is needed. A bug in the original single-server description, found and fixed by Ongaro in 2015, showed that a leader must commit an entry in its current term before applying a configuration change, another case of the same subtlety as Figure 8.
New servers usually join first as non-voting learners (etcd's learner feature), receiving the log without counting towards the quorum until they have caught up, so that adding a blank server does not stall commits while it copies gigabytes of data.
Pre-vote and CheckQuorum. A server that is partitioned away keeps timing out, incrementing its term each time. When it reconnects, its high term forces the healthy leader to step down, causing a needless election. Pre-vote, described in the dissertation, fixes this: before incrementing its term, a would-be candidate asks the others whether they would vote for it, and they say no if they have heard from a leader recently. Only with a majority of pre-votes does it start a real election. CheckQuorum is the counterpart on the leader side: a leader that has not heard from a majority within an election timeout steps down, so a leader isolated in a minority stops accepting requests that it could never commit. etcd supports both and recommends enabling them. Cloudflare's November 2020 post-mortem, "A Byzantine failure in the real world", describes how a partially failed network switch left some etcd members able to reach only part of the cluster, causing repeated leader elections that stalled the services built on it, which is the kind of partial partition these features are designed to contain.
Snapshots and InstallSnapshot. When a follower needs entries the leader has already discarded after a snapshot, the leader sends InstallSnapshot with the snapshot data, in chunks, plus the index and term of the last entry it covers. The follower replaces its state with the snapshot, keeps any log entries after it, and continues normal replication. For large state machines this transfer can take minutes, so implementations throttle it and keep the leader serving traffic meanwhile.
Quorum and fault tolerance (2f + 1)#
A quorum is the minimum number of servers that must take part in a decision. Consensus algorithms use majority quorums: more than half of the voting members. The reason is the overlap property: any two majorities of the same set share at least one member, and that member carries knowledge from one decision to the next, whether a promise in Paxos or a vote and log entry in Raft.
To tolerate f crashed or unreachable servers, a cluster needs 2f + 1 voting members, so that the remaining f + 1 still form a majority.
| Voting members | Majority | Failures tolerated | Typical use |
|---|---|---|---|
| 1 | 1 | 0 | Development only |
| 2 | 2 | 0 | Never: worse than 1, since either failure stops it |
| 3 | 2 | 1 | Most production clusters, one member per availability zone |
| 4 | 3 | 1 | Rarely useful: same tolerance as 3, slower |
| 5 | 3 | 2 | Critical clusters; survives one zone loss plus one more failure, or maintenance plus a failure |
| 7 | 4 | 3 | Rare; slower writes, used when very high durability is required |
Even sizes do not help. Four servers need three for a majority, so they tolerate one failure, the same as three servers, while every write must reach one more server. Worse, a partition that splits four servers two and two leaves neither side with a majority, and the cluster stops. That is why consensus clusters almost always have an odd number of voters.
Placement matters as much as size. Three servers in one rack fail together when the rack switch fails. The usual deployment puts one voter in each of three availability zones, so losing a whole zone still leaves a majority. Two zones are a trap: whichever zone holds two of the three voters is a single point of failure, since losing it loses the majority. For region-level fault tolerance, voters must span at least three regions, for example 2 + 2 + 1 across three regions for a five-node cluster, accepting cross-region commit latency.
Commit latency is set by the fastest majority. The leader needs acknowledgements from enough followers to form a majority with itself, and it does not wait for the rest. In a five-node cluster, it needs the two fastest followers. A slow or distant follower does not slow writes down, as long as enough others are fast. This is also why a leader's location matters: a leader in a region far from the others pays the longest round trip on every write. Systems such as CockroachDB move leadership, or "leaseholders", closer to where writes come from.
Non-voting members scale reads without slowing writes.
- ZooKeeper observers receive all committed updates and serve reads, but do not vote, so adding them does not enlarge the quorum. They are often placed in remote data centres to serve local reads.
- etcd learners are non-voting members used to bring a new member up to date before promoting it to a voter.
- Witnesses, in some systems, vote and store log metadata but not the full state, providing quorum participation cheaply, for example a third, small member in a third zone.
- Raft read replicas in systems such as CockroachDB's non-voting replicas and TiKV's learners serve stale or follower reads near users.
Byzantine failures need more. All of the above assumes servers fail by crashing or going silent. If servers can lie, sending different messages to different peers, tolerating f of them needs 3f + 1 servers and quorums of 2f + 1, as in PBFT. That case is covered in a Deep Dive below.
Flexible quorums. As noted under Paxos, the requirement is really that a leader election quorum intersects every replication quorum. With N servers, a replication quorum of size Q2 and an election quorum of size Q1 are safe whenever Q1 + Q2 > N. Most systems still use majorities for both, because they balance write cost against the ability to elect a leader during failures.
Performance cost#
What one write costs. In Raft or Multi-Paxos, a committed write needs:
- The client's request to reach the leader.
- The leader to append the entry to its log, and flush it to disk.
- One round trip to the followers, each of which appends and flushes the entry before replying.
- The leader to apply the entry and reply to the client.
The leader's flush and the followers' flushes can overlap, since the leader sends to followers while writing its own disk, so the critical path is roughly one network round trip plus one disk flush.
Worked numbers.
| Deployment | Network round trip | fsync | Typical commit latency |
|---|---|---|---|
| Single data centre, NVMe SSD | 0.1 to 0.5 ms | 0.05 to 0.5 ms | About 1 to 2 ms |
| Three zones in one cloud region, SSD volumes | 0.5 to 2 ms | 0.5 to 2 ms | About 2 to 10 ms |
| Three regions on one continent | 10 to 40 ms | 1 ms | About 15 to 50 ms |
| Regions across continents | 70 to 150 ms | 1 ms | About 80 to 200 ms |
| Rotating hard disks or network disks under load | Any | 5 to 50 ms | Disk-bound, often tens of ms |
Disk latency is the most common performance problem in practice. etcd's documentation advises that its write-ahead-log fsync, measured as the 99th percentile of wal_fsync_duration_seconds, should be below about 10 ms, and recommends dedicated SSDs. A busy neighbour on a shared disk can push fsync latency past the heartbeat interval, triggering elections even though nothing has crashed.
Throughput comes from batching and pipelining. One write per round trip would cap a 5 ms cluster at 200 writes per second. Real implementations:
- Batch: collect all client requests that arrive while a flush is in progress, and write and replicate them together. One fsync and one round trip then commit hundreds of entries.
- Pipeline: send the next AppendEntries before the previous one is acknowledged, keeping the link busy.
- Write to disk and network in parallel on the leader.
With these, a well-provisioned etcd cluster sustains tens of thousands of small writes per second, according to etcd's own benchmark documentation, and ZooKeeper is similar. These numbers are for small values. Large values cost bandwidth to every follower and disk space in the log.
The single-leader ceiling. Every write in a consensus group passes through one leader, which must send it to every follower. That leader's CPU, network and disk set an upper bound on the group's throughput, and the group's entire state must fit on each member. etcd, for example, has a default storage quota of 2 GB, and its documentation suggests a maximum of about 8 GB. That is why coordination services hold metadata, not bulk data.
Scaling out: many consensus groups. Systems that need consensus for large amounts of data split the data into many small ranges, each with its own consensus group, so that leaders and load spread over all machines:
- CockroachDB splits its key space into ranges, 512 MiB by default in recent versions, each replicated by its own Raft group, typically of three replicas. A cluster with 10 TB of data has tens of thousands of Raft groups. To keep this manageable, CockroachDB coalesces heartbeats between pairs of nodes, rather than per group, and lets idle ranges go quiet.
- TiKV, the storage layer of TiDB, does the same with regions, about 96 MiB by default historically and larger in recent versions, using what it calls Multi-Raft, with a placement driver that balances region leaders across stores.
- YugabyteDB replicates each tablet with Raft.
- Spanner runs a Paxos group per split, with a long-lived leader, and uses two-phase commit across groups for transactions that touch several splits.
Each group is still limited by its own leader, but the system as a whole scales with the number of machines. The cost is that transactions spanning several groups need a separate protocol, such as two-phase commit on top of consensus. See Distributed Transactions and Partitioning and Sharding.
A worked sizing example. A configuration service must store 50,000 keys of 2 KB each, about 100 MB, with 500 writes per second and 20,000 reads per second, across three zones of one region.
- Size: 100 MB fits easily within etcd's quota. Keep revision history compacted, so the database does not grow with every write.
- Writes: 500 per second at about 5 ms commit latency is well within one Raft group's capacity with batching.
- Reads: 20,000 linearizable reads per second would all go through the leader's read-index path. Serving most of them from followers with serializable, possibly slightly stale reads, or from client-side caches kept current by watches, spreads the load. In Kubernetes, the API server's watch cache plays exactly this role in front of etcd.
- Members: three voters, one per zone, tolerate the loss of one zone. A fourth zone does not exist in most regions, so five voters would put two in some zones, which tolerates two node failures but still not two zones.
Systems using it#
etcd and Kubernetes. etcd is a strongly consistent key-value store built on Raft, created at CoreOS, now a CNCF project. Its Raft library, etcd/raft, is also used by CockroachDB and many other systems, and its key-value layer adds MVCC revisions, watches (clients subscribe to changes after a revision), leases (keys deleted when a lease's time-to-live expires without renewal) and transactions with compare-and-swap. Kubernetes stores its entire cluster state in etcd: every pod, service and config object. The API server is the only component that talks to etcd, and controllers and the scheduler watch the API server. Kubernetes' leader election for its controller manager and scheduler uses Lease objects stored through the API server, so etcd's consistency guarantees ensure that only one instance holds each lease. See ZooKeeper and etcd.
ZooKeeper and ZAB. Apache ZooKeeper, created at Yahoo, provides a hierarchical namespace of small data nodes called znodes, with watches, ephemeral znodes deleted when the session that created them ends, and sequential znodes whose names get an increasing counter. It replicates its state with ZAB, ZooKeeper Atomic Broadcast (Flavio Junqueira, Benjamin Reed and Marco Serafini, "Zab: High-performance broadcast for primary-backup systems", DSN 2011). ZAB is not Paxos, but it is closely related, and very similar in structure to Raft:
- A leader is elected, and each leadership period is an epoch.
- Every transaction gets a zxid, a 64-bit number whose high 32 bits are the epoch and low 32 bits a counter within the epoch, so zxids order all transactions, and every transaction from a new epoch sorts after every transaction from an old one.
- On election, the new leader first synchronises followers so that they all have its history, discarding uncommitted transactions from older epochs, and only then starts broadcasting new transactions.
- In broadcast, the leader proposes a transaction, followers log it and acknowledge, and once a quorum has acknowledged, the leader sends a commit. Transactions from one leader are delivered in the order it proposed them.
ZooKeeper guarantees linearizable writes, and FIFO client order for each session, but reads are served by whichever server the client is connected to and can be slightly stale. A client that needs the latest value calls sync before reading.
Leader election with ZooKeeper. ZooKeeper's documented recipe for electing a leader among application processes, not among ZooKeeper's own servers, uses ephemeral sequential znodes:
- Each candidate creates an ephemeral sequential znode under
/election, for example/election/n_0000000007. - It lists the children. The one with the lowest sequence number is the leader.
- Every other candidate sets a watch on the znode immediately before its own, not on the leader's, to avoid a "herd effect" where every candidate wakes up when the leader goes away.
- When a candidate's predecessor znode is deleted, because that process crashed and its session expired, or because it gave up, the candidate checks again whether it now has the lowest number.
The leader learns it may have lost leadership only when its session expires or disconnects, so it must stop acting promptly, and anything it writes elsewhere should carry a fencing token. See Leader Election and Coordination and Distributed Locks.
Consul. Consul servers, three or five per data centre, run Raft for the service catalog, key-value store and session state, while all agents use gossip for membership and failure detection. Consul offers configurable read consistency modes: default, where the leader serves reads using its leadership lease, consistent, which confirms leadership with a quorum first, and stale, which any server can answer.
Spanner. Google's Spanner (Corbett and colleagues, OSDI 2012) shards data into splits, each replicated by a Paxos group whose replicas are spread across zones or regions. The Paxos leader holds a time-based leader lease, 10 seconds by default in the paper, and acts as the lock manager and transaction participant for its split. Writes commit through Paxos, and transactions across splits use two-phase commit, where each participant is itself a Paxos group, so a participant never becomes unavailable because a single machine failed. TrueTime commit wait then gives externally consistent timestamps. See Time and Ordering.
Amazon DynamoDB. As described in Amazon's 2022 USENIX ATC paper on DynamoDB, each table is split into partitions, and each partition is replicated across three availability zones. The replicas form a Multi-Paxos group: one replica is elected leader, it alone serves writes and strongly consistent reads, it writes a log record and sends it to the peers, and it acknowledges a write after a quorum of replicas, two of three, has persisted it. Eventually consistent reads can go to any replica. Leaders keep their role through leases, and a replica that suspects the leader has failed proposes a new election. Global Tables, DynamoDB's multi-region feature, do not extend this consensus across regions: each region's replicas accept writes, and changes are replicated asynchronously between regions, with last-writer-wins conflict resolution. Consensus within a region gives strong consistency there, while cross-region replication favours latency and availability. See Multi-Region Data.
Apache Kafka. Kafka uses consensus for its metadata and a lighter protocol for its data.
- Data: each partition has a leader replica and followers, typically with a replication factor of 3. Followers fetch from the leader. The in-sync replica set (ISR) is the leader plus the followers that are caught up within
replica.lag.time.max.ms. Withacks=all, a producer's write is acknowledged once every member of the ISR has it, andmin.insync.replicas=2makes the partition refuse writes if fewer than two replicas are in sync, so an acknowledged write always survives the loss of one broker. This is not majority-quorum consensus: the ISR can shrink to just the leader, and correctness depends on the controller managing ISR membership and leadership. - Metadata: which broker leads each partition, the ISR of each partition, topics and configuration are decided by the controller. Kafka originally relied on ZooKeeper for this. Since KRaft (KIP-500), production-ready in Kafka 3.3 and the only mode in Kafka 4.0, a quorum of controller nodes runs a Raft-based protocol over an internal metadata log, and brokers replicate that log to learn the latest metadata.
- Consumers record their progress as offsets in an internal, replicated topic. Committing offsets only after processing a message gives at-least-once processing, and consumer groups rebalance partitions when members join or leave. See Delivery Semantics.
The ISR design lets Kafka tolerate f failures with only f + 1 replicas, instead of the 2f + 1 a majority quorum needs, so three replicas with min.insync.replicas=2 survive one broker loss without blocking and keep storage and network costs low. The price is that the data path cannot decide leadership on its own: it relies on the controller, which does run consensus, to choose a new leader only from the ISR.
More systems.
- CockroachDB, TiKV and YugabyteDB use Raft per range, region or tablet, as described above.
- MongoDB replica sets use an election protocol, protocol version 1, that borrows Raft's terms and voting rules, with an operation log replicated by followers pulling from the primary. Writes with
w: "majority"are acknowledged once a majority has them, which makes them durable across failovers. - Google Chubby (Mike Burrows, "The Chubby lock service for loosely-coupled distributed systems", OSDI 2006) is a lock service of five replicas running Paxos. It inspired ZooKeeper, and its paper's lessons about coarse-grained locks, sequencers and client caching are still relevant.
- Apache Cassandra lightweight transactions use Paxos per partition key, and the project is building Accord (CEP-15), a leaderless protocol, for general multi-key transactions.
- RabbitMQ quorum queues and NATS JetStream replicate messages with Raft.
- HashiCorp Vault and Nomad use Raft for their integrated storage and state.
When you need it#
The question to ask is not "is this data important?" but "would two parts of the system acting on different answers cause harm that cannot be repaired afterwards?". If yes, the decision needs consensus, either directly or through a system built on it. If divergence can be merged, tolerated or corrected later, something cheaper will do.
Decisions that need consensus:
- Exactly one leader or owner: which node is primary for a database shard, which scheduler instance assigns jobs, which worker owns a partition of a stream. Two owners mean duplicated or conflicting work.
- Mutual exclusion that protects correctness: a lock guarding a payment or a unique resource, where two holders corrupt data. Combine it with fencing tokens.
- Uniqueness constraints: a username or a seat can be claimed only once. A conditional write with compare-and-set on a strongly consistent store is consensus in disguise.
- Cluster metadata and configuration: partition maps, schema versions, feature flags whose rollout order matters, and membership lists that decide who stores what.
- Linearizable data: when every read must see the latest committed write, such as a bank account balance or inventory that must never be oversold.
- Totally ordered logs: event logs and replication streams where every consumer must see the same order.
Decisions that usually do not:
- Caches: a stale value expires or is invalidated. Losing a write costs a cache miss.
- Counters and metrics that tolerate small errors: view counts, rate-limit counters, analytics. Use per-node counters merged later, or CRDT counters. See Collaborative Editing and CRDTs.
- Mergeable user data: shopping carts, collaborative documents, likes, where concurrent changes can be merged automatically.
- Membership for routing: gossip is enough to decide where to send requests, because a brief disagreement only causes a retry.
- Idempotent, retryable work: if two workers occasionally process the same message and the effect is idempotent, a best-effort lease is enough.
The usual architecture: consensus for the control plane, cheaper replication for the data plane. Most large systems use consensus sparingly, for the small, critical facts, and use those facts to make cheaper protocols safe:
- Kafka: the KRaft controller decides partition leaders and ISRs; partition data uses ISR replication.
- HDFS high availability: ZooKeeper elects the active NameNode, and a quorum journal manager holds the edit log; DataNodes store the blocks.
- Kubernetes: etcd stores the desired state; containers and their data live elsewhere.
- A sharded primary-replica database: a coordination service decides which replica is primary for each shard, with an epoch number; the data replicates asynchronously or semi-synchronously, and storage rejects writes from an old epoch.
Do I run it, or does my database? In most designs, you never call a consensus API. You pick a database or service that runs it internally, such as Spanner, CockroachDB, DynamoDB with strongly consistent reads and conditional writes, etcd or ZooKeeper, and use its compare-and-set, transactions, leases or leader-election primitives. In an interview, saying "this goes in etcd, which uses Raft, so the lease is safe across failover" is usually the right level. Implementing Raft yourself is justified only if you are building such a system.
When to Use It#
- Leader election and failover for any component that must have exactly one active instance at a time.
- Coordination metadata: configuration, service registries that must be consistent, partition assignments, schemas.
- Distributed locks and leases where correctness depends on mutual exclusion, always combined with fencing.
- Strongly consistent, replicated storage: when a system must survive machine or zone failures without losing acknowledged writes or serving stale reads.
- Ordered replicated logs for state machine replication, such as a metadata log or a transaction log.
- Building a database or a coordination service yourself, using a proven library.
When NOT to Use It#
- High-volume data paths where order does not matter: logs, metrics, clickstreams. A consensus round per event wastes latency and throughput.
- Data that can be merged: use CRDTs, version vectors or last-writer-wins where acceptable.
- Caches and soft state: stale data is tolerable and can be rebuilt.
- Across continents on every request, unless the product truly needs global linearizability and can accept 100 ms or more per write. Prefer regional consensus with asynchronous cross-region replication, or place leaders near their users.
- As a message queue or bulk store: etcd and ZooKeeper are designed for megabytes to a few gigabytes of small values, not for gigabytes of payloads or thousands of writes per second per key.
- Two-node setups: there is no majority to be had. Add a third voter, even a small witness, or use an external coordinator.
- When you would write your own: use etcd, ZooKeeper, Consul, or a library such as etcd/raft, hashicorp/raft or Apache Ratis instead.
How to Implement It#
- Decide what needs agreement. List the facts that must never diverge, such as the leader of each shard or the current configuration, and keep the consensus-backed state to those.
- Use an existing system first. For coordination, run etcd, ZooKeeper or Consul, or use the primitives of your strongly consistent database. Only embed a Raft library if you are building a replicated service yourself.
- Size and place the cluster: three voters across three zones for most uses, five when you need to survive a failure during maintenance, never an even number. Add learners or observers for read scaling.
- Give it fast, dedicated disks: SSDs with low fsync latency, separate from noisy workloads. Monitor fsync and commit latency.
- Tune timeouts to the network: heartbeat interval around the round-trip time times a small factor, election timeout about ten times the heartbeat. Raise both for cross-region clusters. Enable pre-vote and CheckQuorum.
- Choose read semantics deliberately: linearizable reads through read index for correctness-sensitive paths, follower or serializable reads for scale.
- Make commands deterministic and idempotent: compute time and IDs before logging, and deduplicate client retries with client IDs and sequence numbers.
- Plan snapshots, compaction and membership changes: automatic snapshots, history compaction, one-at-a-time membership changes, and learners for new members.
- Fence everything outside the consensus group: a leader acting on external systems must pass its term or lease revision as a fencing token, which those systems check.
- Test with fault injection: kill leaders, pause processes, partition the network asymmetrically, slow disks, and check with a linearizability checker such as Jepsen's Knossos or Porcupine that no acknowledged write was lost.
Here is leader election with a lease and a fencing token, using etcd's concurrency API from TypeScript-style pseudocode. The same pattern applies with ZooKeeper's recipe or Consul sessions.
// Campaign for leadership; act only while the lease is alive; fence all writes
async function runAsLeader(etcd: Etcd, name: string, work: (token: bigint) => Promise<void>) {
const lease = await etcd.lease.grant({ ttlSeconds: 10 }); // kept alive in background
const election = etcd.election("/elections/scheduler");
// Blocks until this process holds the lowest-revision key under the prefix
const leadership = await election.campaign(name, lease);
const fencingToken = leadership.revision; // increases with every new leader
const lost = new AbortController();
lease.onExpired(() => lost.abort()); // keep-alives failed: stop now
try {
while (!lost.signal.aborted) {
// Downstream storage rejects any write carrying a token lower than one it has seen
await work(fencingToken);
}
} finally {
await leadership.resign().catch(() => {}); // best effort; the lease expires anyway
}
}The fencing token comes from etcd's global revision counter, so a newer leader always has a higher token. If this process pauses longer than the lease, the next leader's token is higher, and storage that checks tokens rejects the old leader's late writes.
| Technology | Fits when |
|---|---|
| etcd | Kubernetes and cloud-native control planes; small, strongly consistent key-value data with watches and leases |
| Apache ZooKeeper | JVM ecosystems, Hadoop, HBase, older Kafka; hierarchical namespace, ephemeral and sequential znodes, recipes via Apache Curator |
| Consul | Service discovery plus key-value and sessions, with gossip-based health across many machines |
| etcd/raft (Go) | Embedding Raft in your own Go system; used by etcd, CockroachDB and others; you supply storage and transport |
| hashicorp/raft (Go) | Simpler embedded Raft with built-in transport and snapshot support; used by Consul, Nomad and Vault |
| Apache Ratis (Java) | Embedding Raft in JVM systems; used by Apache Ozone |
| openraft, tikv/raft-rs (Rust) | Embedding Raft in Rust systems; raft-rs is a port of etcd/raft used by TiKV |
| Spanner, CockroachDB, TiDB, YugabyteDB | Strongly consistent SQL that runs consensus per range for you |
| DynamoDB strongly consistent reads and conditional writes | Managed key-value storage with per-partition Multi-Paxos, without operating a cluster |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Raft or Multi-Paxos with a stable leader | Linearizable; survives f of 2f + 1 failures; well understood | Every write through one leader; majority round trip and fsync per batch | Metadata, coordination, strongly consistent storage |
| Leaderless Paxos variants (EPaxos and similar) | No leader bottleneck; one round trip for non-conflicting commands from any replica | Complex; conflict handling costs extra rounds | Geo-distributed systems with low-conflict workloads |
| Primary-backup with asynchronous replication | Fast writes; simple | Failover can lose acknowledged writes; split brain without external fencing | Data where a small loss on failover is acceptable |
| Quorum replication without consensus (Dynamo style) | Highly available; any replica accepts writes; tunable consistency | No total order; conflicts resolved by timestamp or merge | Large, write-heavy data that tolerates eventual consistency |
| ISR-style replication with a consensus controller | Tolerates f failures with f + 1 replicas; high throughput | Relies on the controller for safety; ISR can shrink to one | Logs and streams, as in Kafka |
| Three voters | Fast commits; one failure tolerated | Maintenance plus one failure stops writes | Most clusters, one per zone |
| Five voters | Two failures tolerated | Slightly slower writes; more machines | Critical control planes, rolling upgrades with safety margin |
| Byzantine fault-tolerant consensus | Tolerates lying nodes | 3f + 1 nodes; many more messages | Blockchains, mutually distrusting parties |
Common Pitfalls#
- Running two or four voters, gaining nothing in fault tolerance and, with two, losing availability on any failure.
- Putting all voters in one zone or rack, so one failure removes the majority.
- Slow or shared disks, where fsync latency spikes cause missed heartbeats, constant elections and stalls.
- Reading from the leader without a read index or lease, so a deposed leader serves stale data during a partition.
- Non-deterministic commands, such as using local time or random values inside the state machine, causing replicas to diverge silently.
- Treating "the lease says I am leader" as permission to act on external systems without fencing tokens.
- Storing large values or high-churn data in etcd or ZooKeeper, filling the quota, slowing snapshots, and destabilising the cluster.
- Changing membership several servers at a time, or adding an empty voter directly, which stalls commits or risks two majorities.
- Timeouts copied from a LAN to a WAN, causing election storms across regions.
- Assuming consensus makes the whole system consistent, when only the state inside the group is linearizable, and clients, caches and side effects outside it are not.
Real-World Examples#
- Kubernetes stores all cluster state in etcd, a Raft cluster of typically three or five members, and uses leases on top of it to elect active controller managers and schedulers.
- Apache Kafka replaced ZooKeeper with KRaft, a Raft-based controller quorum, removing ZooKeeper entirely in Kafka 4.0, while partition data stays on ISR replication.
- Google Spanner replicates each split with Paxos across zones and regions, and uses two-phase commit across Paxos groups with TrueTime timestamps.
- Amazon DynamoDB replicates each partition across three availability zones with Multi-Paxos, acknowledging writes after two of three replicas persist them.
- CockroachDB and TiDB run tens of thousands of Raft groups per cluster, one per range or region, with heartbeat coalescing and load-based leader placement.
- Google Chubby, described in 2006, was a five-replica Paxos lock service used for leader election and naming in systems such as Bigtable and GFS.
- HashiCorp Consul, Vault and Nomad use hashicorp/raft for their servers, typically three or five per cluster.
- Apache ZooKeeper has served as the coordination layer for HBase, Hadoop high availability, Solr and many other systems, with ZAB as its replication protocol.
In the Interview#
Deep Dive: Why Raft is safe, step by stepShow
The claim. Once an entry is committed, every future leader has it, and no server ever applies a different entry at that index. The argument chains together the rules introduced above.
Step 1: at most one leader per term. A candidate needs votes from a majority in a term. Each server votes at most once per term and persists that vote before replying. Two different candidates in the same term would need two disjoint majorities, which cannot exist. So a term has at most one leader.
Step 2: a leader's log only grows. By construction, a leader appends entries and never rewrites its own log. All repair flows from leader to followers.
Step 3: matching entries imply matching prefixes. A leader creates at most one entry per index in a term, and entries never change their index. A follower accepts new entries only if the entry before them matches the leader's by index and term. By induction over the log, if two servers have an entry with the same index and term, everything before it is identical too.
Step 4: committed entries survive leader changes. Suppose an entry E from term T is committed: the leader of term T stored it on a majority M1. Consider the first later term U whose leader L lacks E. L won with votes from a majority M2. M1 and M2 share some server V. V stored E before voting for L, since V had accepted E in term T, before U began, and V would have rejected any AppendEntries from term T after seeing term U. V voted for L, so L's log was at least as up to date as V's:
- If L's last term equals V's last term, L's log is at least as long, so by Step 3 it contains V's prefix, which includes E. Contradiction.
- If L's last term is higher than V's, the leader that created L's last entry, from a term between T and U, had E, since U was the first term whose leader lacked it. By Step 3, L's log contains that leader's prefix up to that entry, which includes E. Contradiction.
So every later leader has E. This is the Leader Completeness property.
Step 5: why the current-term rule is needed. Step 4 assumed "committed" means "stored on a majority by the leader of the entry's own term". In the Figure 8 scenario, an entry from term 2 sits on a majority during term 4, but a server with a term 3 entry can still win, because the voters compare last terms, and 3 beats 2. Counting only current-term entries closes the gap: once an entry of term 4 is on a majority, any winning candidate must have a last term of at least 4, and by Step 3 that candidate also has everything before it.
Step 6: state machines agree. A server applies an entry only once it is committed, in index order. By Step 4, every later leader has the same committed entries, and by Step 3 followers' logs match the leader's up to the commit index. So no two servers apply different entries at the same index.
Where liveness enters. None of these steps mentions timeouts, clocks or message delays. Timing only decides whether elections succeed. With random election timeouts much longer than message delays, one candidate usually wins quickly. With bad timing, elections can repeat indefinitely, but never produce two leaders in a term. This is exactly the division the FLP result forces: safety under all conditions, progress under reasonable ones.
Bugs that break it in practice. Implementations have violated these guarantees through:
- Not persisting
votedForbefore replying, allowing double votes after a crash. - Acknowledging AppendEntries before the entries reached stable storage.
- Truncating matching entries when an old, reordered AppendEntries arrives.
- Serving reads from a leader that had been deposed without knowing it.
- Applying configuration changes before they were committed.
Jepsen analyses by Kyle Kingsbury have found consistency bugs of these kinds in several databases and coordination systems built on consensus protocols, which is a strong argument for using mature implementations and testing them under faults.
Deep Dive: Byzantine fault toleranceShow
When servers can lie. Crash-fault-tolerant protocols such as Raft and Paxos assume a server either follows the protocol or stops. A Byzantine server, named after Lamport, Shostak and Pease's paper "The Byzantine Generals Problem" (ACM TOPLAS, 1982), may do anything: send conflicting votes to different peers, forge messages it relays, or claim to have stored data it threw away. This models bugs, corrupted hardware, and, most importantly, malicious participants in systems where no single party controls all the machines.
Why 3f + 1. With f faulty servers, a node can wait for only n minus f replies, since the faulty ones might stay silent. Among those replies, up to f might be from liars. For any two such quorums of size n minus f to overlap in at least one honest server, they must overlap in at least f + 1 servers, giving 2(n - f) - n ≥ f + 1, so n ≥ 3f + 1. Four servers tolerate one Byzantine failure, seven tolerate two.
PBFT. "Practical Byzantine Fault Tolerance" (Miguel Castro and Barbara Liskov, OSDI 1999) was the first Byzantine protocol fast enough for real services. A primary assigns a sequence number to each request, and the replicas run three phases: pre-prepare, where the primary proposes the order; prepare, where each replica broadcasts that it saw the proposal, and waits for 2f matching prepares; and commit, where each replica broadcasts that it is prepared, and executes after 2f + 1 matching commits. A view change replaces a faulty primary. Messages are authenticated, and clients accept a result once f + 1 replicas return the same answer. The cost is that every replica talks to every other replica in the prepare and commit phases, O(n squared) messages per decision, which limits PBFT to tens of replicas.
HotStuff and Tendermint. Later protocols reduced this communication. HotStuff (Maofan Yin, Dahlia Malkhi, Michael Reiter, Guy Golan Gueta and Ittai Abraham, PODC 2019) routes votes through the leader, which aggregates them into a single quorum certificate, giving linear message complexity per phase and a simple, pipelined leader rotation. It was the basis of the consensus protocol designed for Facebook's Libra (later Diem) project. Tendermint, by Jae Kwon and later formalised by Ethan Buchman and colleagues, is a round-based BFT protocol with propose, prevote and precommit steps, used by the Cosmos ecosystem of blockchains.
Proof-of-work is different. Bitcoin's consensus (Satoshi Nakamoto, 2008) works with an open, unknown set of participants, by making each block expensive to produce and following the longest valid chain. Agreement is probabilistic: a block becomes harder to reverse as more blocks are built on it. It tolerates adversaries with less than half the hashing power, but finality takes many minutes, compared with milliseconds to seconds for BFT protocols among known participants.
When to use BFT. Inside one organisation, where all machines are operated by the same team, crash fault tolerance plus checksums and careful engineering is almost always the right choice, since BFT costs at least a third more replicas and much more communication. BFT protocols fit when participants are mutually distrusting: permissioned blockchains, consortium ledgers, and some critical systems that must tolerate arbitrary hardware faults.
Deep Dive: Operating a consensus clusterShow
What to monitor.
- Leader changes: a healthy cluster changes leader rarely, on deployments or real failures. Repeated changes, visible in etcd as
etcd_server_leader_changes_seen_total, signal slow disks, network trouble or overloaded members. - Disk sync latency: etcd's
etcd_disk_wal_fsync_duration_secondsandetcd_disk_backend_commit_duration_seconds. The 99th percentile of WAL fsync should stay below about 10 ms. - Proposal health: pending, failed and committed proposals. A growing pending count means the leader cannot reach a quorum fast enough.
- Apply lag: the gap between committed and applied indexes. A large gap means the state machine is slower than replication, and reads wait.
- Peer round-trip time and network errors between members.
- Database size relative to the quota, and the frequency and duration of snapshots and compaction.
Common failure stories.
- The noisy neighbour. A backup job on the same disk pushes fsync latency to 500 ms. The leader misses heartbeats, followers start elections, and the new leader suffers the same disk. Writes stall although every process is up. Fix: dedicated disks, I/O priority, and alerting on fsync latency.
- The quota alarm. A controller writes a large object on every reconciliation loop, and history is not compacted. The database hits its 2 GB quota, etcd raises a NOSPACE alarm and refuses writes, and Kubernetes can no longer change anything. Fix: compaction and defragmentation, limits on object size and write rates, and monitoring of database size.
- The slow follower in a three-node cluster. One follower lags, so every commit depends on the other follower. When that one restarts for maintenance, the cluster has no quorum until the lagging follower catches up. Fix: monitor follower lag, and confirm all members are healthy before maintenance.
- Losing a majority. Two of three members are lost permanently, for example to a zone outage combined with an operator mistake. The survivor cannot elect itself, by design. Recovery means restoring a snapshot onto a new single-member cluster, for example with
etcdctl snapshot restoreand starting a new cluster from it, which can lose writes committed after the snapshot. Practise this before you need it, and take regular snapshots.
Upgrades and changes. Upgrade one member at a time, waiting for it to rejoin and catch up before the next. Replace members by adding the new one as a learner, promoting it, then removing the old one, so the voter count never drops below the majority needed. Move leadership away from a member before restarting it, using leadership transfer, so the cluster does not wait for an election timeout.
Client behaviour matters. Clients should spread across members, retry with back-off on leader changes, and use watches instead of polling. Thousands of clients each polling with linearizable reads can overload a leader that would handle the same information easily as watch events.
Deep Dive: Consensus at scale and across regionsShow
Many groups, one cluster. As described above, systems such as CockroachDB, TiKV and Spanner split data into ranges, each with its own consensus group. This raises new problems:
- Heartbeat overhead: 100,000 groups each sending heartbeats every few hundred milliseconds would be millions of messages per second. CockroachDB coalesces heartbeats per pair of nodes and lets idle ranges stop heartbeating ("quiescing").
- Placement and balancing: a placement driver or allocator moves replicas and leaders to balance load and disk use, and to respect constraints such as "one replica per zone".
- Range splits and merges: hot or large ranges split, each half forming its own group, and small, cold ranges merge.
- Cross-group transactions: a transaction touching several ranges needs two-phase commit on top of consensus, with the transaction record itself stored in a consensus group, so coordinator failure does not block participants forever.
Geo-distribution choices. For a group spanning regions, the round trip between the leader and the nearest majority sets write latency. Common options:
- Three regions, one replica each: survives a region loss, with writes paying the round trip to the nearest other region, perhaps 20 to 70 ms.
- Leader placement near writers: move each range's leader, or leaseholder, to the region where its writes come from, so that the round trip is only to the closest other region.
- Regional data: pin data to a home region, with all replicas in that region's zones, so writes stay fast, and the data survives a zone but not a region loss. CockroachDB's regional tables and Spanner's regional configurations offer this.
- Follower reads with bounded staleness: serve reads from a local replica at a timestamp slightly in the past, avoiding cross-region round trips for reads that can accept a few seconds of staleness.
- Flexible quorums and witnesses: keep the replication quorum within nearby regions, accepting larger election quorums.
A worked example. A five-replica group spans us-east (two replicas), us-west (two) and eu-west (one). The leader is in us-east. A write needs three replicas: the leader, its local peer at under 1 ms, and the nearest remote replica, us-west, at about 70 ms round trip. Commit latency is about 70 ms plus fsync. If us-east fails, a new leader in us-west needs us-west's two replicas plus eu-west, at about 140 ms round trip, so writes slow down but continue. Moving one us-west replica to us-central, about 40 ms from us-east, would cut normal commit latency to about 40 ms. Small placement changes have a direct effect on every write.
Leaderless alternatives. EPaxos and its successors, and protocols such as Accord, let any replica commit non-conflicting commands in one round trip to a nearby fast quorum. They avoid sending every write to a distant leader, but they complicate recovery and add cost when commands conflict. They are an active research and engineering area, and the choice between them and leader-based groups with smart placement depends on how often writes from different regions touch the same keys.
Key Takeaways#
- Consensus lets a group of machines agree on values, or on a log of commands, so that decisions are never contradicted or undone, even with crashes, lost messages and wrong failure guesses.
- The replicated state machine pattern turns consensus into fault-tolerant services: agree on the order of deterministic commands, and every replica reaches the same state.
- Paxos guarantees safety by requiring promises from a majority and re-proposing any value a majority might have accepted. Multi-Paxos with a stable leader needs one round trip per command.
- Raft elects a leader per term with randomised timeouts and an up-to-date-log restriction, replicates entries with a consistency check, and commits an entry once a majority stores it in the leader's current term.
- A cluster of 2f + 1 voters tolerates f failures. Use three or five voters, spread across three zones, and never an even number.
- Each write costs a majority round trip plus a disk flush and passes through one leader, so consensus is for small, critical metadata, or is sharded into many groups.
- etcd, ZooKeeper with ZAB, Consul, Spanner, DynamoDB, CockroachDB, TiKV and Kafka's KRaft controller all run consensus. Most designs use it through these systems rather than implementing it.
- Use consensus when divergent decisions would cause irreparable harm, such as two leaders, two lock holders or oversold inventory, and combine it with fencing tokens for anything outside the group.