Course contents

08. Distributed Systems Lesson 6 of 10

Distributed Consensus

Why getting machines to agree is hard, how majority quorums tolerate failures, safety versus liveness, and what the FLP result really says.

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

Summary

  • Consensus makes every node decide the same proposed value despite racing messages, delays and crashes.
  • A node cannot distinguish a crashed peer from a slow one; timeouts are guesses.
  • Waiting for every replica turns one failure into an outage; waiting for a majority tolerates f failures with 2f + 1 nodes.
  • Any two majorities overlap, so every new majority contains a node that knows each earlier decision.
  • Consensus never sacrifices safety; it sacrifices liveness on the minority side of a partition and, per FLP, under bad timing.
  • In practice a stable leader orders decisions and each decision costs one majority round trip.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Consensus is the problem of getting a group of nodes to agree on a single value (or, repeated, on a sequence of values such as a log of commands) even though messages can be delayed, reordered or lost and nodes can crash. A correct protocol guarantees:

  • Agreement: no two nodes decide different values.
  • Validity: the decided value was proposed by someone (a protocol that always decides 0 is useless).
  • Termination: every non-faulty node eventually decides.

The first two are safety properties, the third is a liveness property. Repeated consensus over a log is called state machine replication: if every replica applies the same commands in the same order, every replica ends in the same state.

Why it exists

Replicating data is easy while nothing goes wrong. The trouble starts when two clients write at once, when a node crashes in the middle of an update, or when the network splits the cluster. Without a protocol, replicas apply writes in whatever order they arrive and diverge; a naive failover can produce two primaries that both accept writes (split brain). Consensus is the building block that makes "one leader", "one committed order of writes" and "one owner of this lock" well-defined in a system where any part can fail.

How it works

Nodes cannot tell slow from dead. In an asynchronous network there is no bound on message delay. A node waiting for a reply cannot know whether the peer crashed, is paused, or whether the message or its reply is stuck. Any timeout is a guess, and a protocol must stay correct when the guess is wrong.

Quorums. Instead of waiting for every node (which stops progress when one is down), a decision needs acknowledgements from a majority, ⌊n/2⌋ + 1 nodes. With n = 2f + 1 nodes, the cluster keeps deciding with f nodes down: 3 nodes tolerate 1 failure, 5 tolerate 2, 7 tolerate 3. Even sizes add no tolerance: 4 nodes need 3 acknowledgements and still tolerate only 1 failure.

Overlap is the key. Any two majorities of the same group share at least one node. A value committed by one majority is therefore known to at least one member of every later majority. Protocols use that: before a new leader proposes anything it collects state from a majority and must respect what was already accepted (Paxos's prepare phase, Raft's rule that only a candidate with an up-to-date log can win).

Rounds. Proposals carry a monotonically increasing number: a ballot in Paxos, a term in Raft, an epoch in ZAB. A node that has seen round 6 rejects messages from round 5. That stops an old leader, after a pause or a partition, from overriding a newer one.

Leaders. Two nodes proposing at the same time can keep pre-empting each other with ever-higher rounds. Practical protocols (Multi-Paxos, Raft, ZAB) elect a single stable leader that sequences all proposals; elections only happen when the leader seems to have failed, and randomised timeouts make repeated collisions unlikely.

Safety, liveness and FLP. Fischer, Lynch and Paterson proved in 1985 that in a fully asynchronous system where even one process may crash, no deterministic algorithm can guarantee consensus terminates. Real protocols therefore guarantee safety unconditionally and liveness only under partial synchrony: once messages are delivered within some (unknown) bound for long enough, they decide. During a partition, the majority side keeps working and the minority side stops; nobody ever decides two different things.

When to use it

  • Choosing a single leader, primary or owner (database failover, scheduler leader, shard ownership).
  • Storing small, critical metadata that everything else depends on: cluster membership, configuration, which node owns which partition.
  • Distributed locks and leases where correctness matters, combined with fencing tokens.
  • Replicating a database's write log when confirmed writes must survive any minority of failures (CockroachDB, TiKV, Spanner, etcd).

When not to

  • For bulk data paths with very high write rates where losing the most recent writes on failover is acceptable: asynchronous replication is cheaper.
  • When conflicts can be merged after the fact (shopping carts, counters, collaborative editing): leaderless replication with CRDTs or version vectors stays available during partitions.
  • Inside a single machine, or when one database's transactions already give you the guarantee.
  • Do not implement a consensus protocol yourself for production use; use a proven implementation or service.

Trade-offs

Choice You gain You pay
Majority quorum (consensus) Survives f of 2f + 1 failures with no lost confirmed writes and no split brain One round trip to a majority per decision; the minority side of a partition is unavailable
Wait for all replicas Every copy always has every confirmed write Any single failure stops writes
Asynchronous replication Lowest write latency; writes continue with replicas down Confirmed writes can be lost on failover; failover needs an external decision
Larger cluster (5 or 7) Tolerates more failures Slower commits (larger majority, often across more zones) and more replication traffic
Cross-region cluster Survives a region outage Every write pays a cross-region round trip

Alternatives

  • Primary–backup with an external arbiter: a single primary with async or semi-sync replicas, and failover decided by a consensus-backed service (for example a Kubernetes lease or an etcd key). The data path avoids consensus; only the leadership decision uses it.
  • Leaderless quorums (Dynamo-style, with R + W > N): reads and writes contact overlapping quorums, but without consensus concurrent writes can conflict and need resolution.
  • CRDTs: data types whose concurrent updates always merge deterministically; no agreement needed, but only for operations that commute.
  • Byzantine fault-tolerant protocols (PBFT and successors): tolerate nodes that lie, at the cost of 3f + 1 nodes and more messages. Rarely needed inside one organisation.

Failure modes

  • Losing a majority: with 3 of 5 nodes down (or unreachable) the cluster cannot commit anything. Spread nodes across failure domains so one zone outage cannot take a majority.
  • Slow disks or networks: every commit waits for the median-fastest majority; one slow node is masked, two slow nodes in a five-node cluster slow everything.
  • Election storms: timeouts set too close to normal latency make followers start elections during GC pauses or load spikes, and every election pauses writes.
  • Unsafe membership changes: adding or removing several nodes at once can create two disjoint majorities (old and new configuration). Protocols change membership one node at a time or with joint consensus.
  • Stale reads from an old leader: a leader cut off from the majority may not know it was replaced; reads served from it without checking (ReadIndex, leases) can be stale.

In production

Run three nodes for most clusters and five when you need to survive two failures or one zone plus maintenance. Put them in different zones within a region unless you need regional fault tolerance and can afford the latency. Monitor leader changes, proposal commit latency (which includes the disk sync on a majority) and follower lag. etcd and ZooKeeper are sized for metadata (etcd's default storage quota is 2 GiB), not for application data. Remember that the client side matters too: a client that retries a write after a timeout may apply it twice unless requests are idempotent or deduplicated.

Common misconceptions

  • "Consensus means all nodes agree before anything is committed." A majority is enough; the rest catch up later.
  • "FLP says consensus is impossible." It says termination cannot be guaranteed in a fully asynchronous model. Safety can be, and practical systems terminate whenever the network is reasonably timely.
  • "Four nodes are safer than three." They tolerate the same single failure and add one more machine that can fail.
  • "A partition makes both sides keep working, then they reconcile." That is what leaderless or async systems do. A consensus system stops the minority side instead.
  • "Consensus makes my application exactly-once." It orders the commands it receives; duplicate client retries are still duplicates unless the application deduplicates them.

Interview angle

When a design needs a single leader, unique ownership or a strongly consistent store, say that you would rely on a consensus-backed component (etcd, ZooKeeper, a Raft-replicated database) rather than invent one. Explain the majority arithmetic (2f + 1), what happens during a partition (the minority side is unavailable), and the cost (a majority round trip per write, so keep the cluster in one region unless you need regional survival). Mentioning safety versus liveness and the role of timeouts (FLP) shows you understand why these systems behave as they do.

Model assumptions

Most of this lesson is a scripted illustration: the packets are placed by hand to show who sends what to whom and in which order, and node state appears as annotations. The simulator has no voting or ballot model. Two steps are simulated with real writes (40 per second) through the engine's synchronous replication: in "Wait for all" the primary answers a write only after every replica has applied it, so a crashed replica fails every write; in "Majority" it answers after one of its two peers has applied it (itself plus one peer is 2 of 3), so writes keep succeeding with one node down and fail once a second node crashes. The leader is fixed in both; there is no election. Latencies are illustrative (5 ms between app and node, 10 ms between nodes, about 1 ms of processing; a few links in the duel are faster or slower to make the race visible); real intra-region round trips are usually well under a millisecond plus a disk sync. The duel uses Paxos-style prepare and accept phases to show pre-emption; Raft avoids most duels with randomised election timeouts.

The lesson as textEvery step of the simulation, written out.
  1. 1. Three copies, two writers, one value?

    Three nodes keep a copy of the same value x. App A sets x = 1 on Node 1 while App B sets x = 2 on Node 3, at the same moment. Each node applies its own write and forwards it to the others, and every node applies writes in the order they arrive.

    Watch the packets race. Node 1 ends with x = 2, Node 2 with x = 2, Node 3 with x = 1. Nobody crashed and no message was lost, yet the copies disagree for good.

    Consensus is the problem of making every node decide the same value, a value someone actually proposed, even though messages race, are delayed, and nodes crash. This step is a scripted illustration.

    Scene: App A writes x = 1 to Node 1 and App B writes x = 2 to Node 3 at the same time. Both nodes forward their write. Node 2 receives x = 1 first and x = 2 second; Node 1 ends with x = 2 and Node 3 with x = 1, so the copies disagree.

    Key idea: Applying writes in arrival order is not enough: different nodes see different orders. Agreement needs a protocol.

  2. 2. A silent node: crashed, or just slow?

    Node 1 asks both peers a question and waits 100 ms for answers. Node 2 answers in about 20 ms. Node 3 is alive and answers too, but its reply is held up (a busy link, a long garbage-collection pause) and arrives after 151 ms, too late.

    From Node 1’s point of view a crashed node, a slow node and a lost message look exactly the same: silence. In an asynchronous network there is no upper bound on delay, so no timeout can tell them apart. Pick a short timeout and you declare live nodes dead; pick a long one and you wait forever for dead ones.

    This uncertainty is what makes consensus hard, not the arithmetic.

    Scene: Node 1 sends a request to Node 2 and Node 3. Node 2 replies within about 20 ms. Node 3 replies too, but its reply arrives after 151 ms, well after Node 1’s 100 ms timeout.

    Key idea: A node cannot tell a crashed peer from a slow one. Timeouts are guesses.

  3. 3. Wait for every copy: safe, until one node dies

    A simple way to keep copies identical: Node 1 takes every write, sends it to both peers, and confirms it to the app only after all of them have stored it (synchronous replication). This step runs in the simulator: App A sends 40 writes per second and every one succeeds.

    Two seconds in, Node 3 crashes. Node 1 can no longer get an acknowledgement from every node, so from then on every write fails, although two of the three nodes are healthy. Waiting for everyone means any single failure stops all progress.

    Scene: Simulated: App A sends 40 writes per second to Node 1, which replicates each one synchronously to Node 2 and Node 3. All writes succeed until Node 3 crashes after two seconds; from then on every write fails.

    Key idea: Waiting for all replicas turns any one failure into an outage.

  4. 4. Wait for a majority instead

    Node 3 is still down. Now Node 1 confirms a write as soon as a majority has stored it: 2 of 3, itself included, so one peer acknowledgement is enough. It sends every write to both peers; Node 2’s acknowledgement arrives, that makes two, and the write is committed and confirmed to the app. Node 3 never answers and nobody waits for it. This step runs in the simulator again: the same 40 writes per second now all succeed, with Node 3 still down.

    Three seconds in, Node 2 crashes too. Now only Node 1 is left: 1 of 3 is not a majority, and every write fails. A majority of *n* nodes is ⌊n/2⌋ + 1. With 2f + 1 nodes the system keeps working with up to f of them down: 3 nodes survive 1 failure, 5 survive 2, and no more.

    Scene: Simulated: Node 3 is down. App A keeps sending 40 writes per second to Node 1, which replicates each one to Node 2 and Node 3 and commits as soon as Node 2 acknowledges (two of three). Every write succeeds. After three seconds Node 2 crashes as well; with only one of three nodes left, every write fails.

    Key idea: Majority quorums let 2f + 1 nodes keep deciding while f of them are down, and stop once more are.

  5. 5. Why majorities: any two of them overlap

    The cluster grows to five nodes and Nodes 2 and 3 are back. A write W reaches only Nodes 1, 2 and 3 (Nodes 4 and 5 were cut off for a moment). Three of five is a majority, so W is committed.

    Later Node 5 wants to know what was decided and asks a majority of its own: Nodes 3 and 4, plus itself. Node 3 was in both majorities and reports W. That is the whole trick: two majorities of the same group always share at least one node, so a later decision can always find out about an earlier one.

    Four nodes would tolerate only one failure (a majority of 4 is 3), the same as three nodes, which is why clusters have an odd size. This step is a scripted illustration.

    Scene: Five nodes. Node 1 replicates write W to Nodes 2 and 3, which acknowledge: three of five, committed. Later Node 5 queries Nodes 3 and 4; Node 3, which belongs to both majorities, reports W.

    Key idea: Any two majorities share a node, so knowledge of every committed decision survives into the next majority.

  6. 6. A partition: only the majority side moves

    The network splits the cluster: Nodes 1 and 2 on one side, Nodes 3, 4 and 5 on the other. Both apps try to write.

    Node 1 gets Node 2’s acknowledgement, but 2 of 5 is not a majority, so it cannot commit. App A waits and finally times out. On the other side Node 3 collects acknowledgements from Nodes 4 and 5: 3 of 5, committed, and App B gets its answer.

    This is safety: nothing bad ever happens, the two sides never commit conflicting values. The minority side gives up liveness (the promise that something good eventually happens) until the partition heals. A consensus protocol always trades liveness for safety, never the reverse. This step is a scripted illustration.

    Scene: A partition separates Nodes 1 and 2 from Nodes 3, 4 and 5. Node 1 gets one acknowledgement, two of five, and cannot commit; App A times out. Node 3 gets acknowledgements from Nodes 4 and 5, three of five, commits and answers App B.

    Key idea: Safety: never decide two different things. Liveness: eventually decide something. Under a partition, only the majority side stays live.

  7. 7. Duelling leaders and the FLP result

    The partition heals. Node 1 and Node 4 both try to lead at once. Each uses a round number: a node that has promised round 6 refuses anything from round 5 (Paxos calls these ballots, Raft calls them terms).

    Node 1 gathers promises for round 5, but before its *accept* reaches Node 3, Node 4’s round 6 got there first: refused. Node 1 retries with round 7, which in turn pre-empts Node 4’s round 6. Here the duel ends in round 7, when Node 3 and Node 2 accept and value A is chosen, but only because the timing happened to work out. No conflicting value was ever chosen: safety held throughout.

    The FLP result (Fischer, Lynch and Paterson, 1985) says this is unavoidable: in an asynchronous system where even one node may crash, no deterministic protocol can guarantee it always terminates. Real systems keep safety unconditionally and get liveness from timing: randomised timeouts and a stable leader make progress whenever the network behaves for long enough. This step is a scripted illustration.

    Scene: Node 1 and Node 4 compete with rising round numbers. Node 3 refuses Node 1’s round-5 accept because it promised round 6, then refuses Node 4’s round-6 accept because it promised round 7. Node 1’s round 7 finally collects a majority and value A is chosen.

    Key idea: Safety can be guaranteed always; termination only when the network is timely enough (FLP). Practical protocols use randomised timeouts and a stable leader.

  8. 8. One leader, one majority round trip per decision

    Production systems avoid duels by electing a stable leader that orders all decisions; elections happen only when it fails. Every write then costs one round trip from the leader to a majority: here Node 1 commits as soon as two of its four followers acknowledge, before the slower two answer.

    That is where consensus lives in practice: etcd and ZooKeeper (configuration, leader election, locks for systems such as Kubernetes), the metadata quorum in Kafka (KRaft), and the replication groups inside CockroachDB, TiKV and Spanner. Raft, Multi-Paxos and ZAB are the protocols behind them. Each decision costs a majority round trip and goes through one leader, so teams use consensus for small, critical state, not for bulk data. This step is a scripted illustration.

    Scene: Node 1 is the leader. A write from App A goes to all four followers; after Nodes 2 and 3 acknowledge, Node 1 commits and answers before the acknowledgements from Nodes 4 and 5 arrive.

    Key idea: Consensus = a leader plus one majority round trip per decision. Use it for the small state everything else depends on.

  9. 9. What to remember about consensus

    Nodes cannot tell slow from dead, and messages race, so agreeing on one value needs a protocol. Majority quorums give 2f + 1 nodes tolerance of f failures, because any two majorities overlap.

    Consensus protocols never give up safety. They give up liveness when they must: on the minority side of a partition, and (FLP) whenever timing is bad enough. Next, the Raft lesson shows a complete protocol built on exactly these ideas.

    Scene: Five consensus nodes with Node 1 as leader, and the two apps that write to them.

    Key idea: Majorities overlap, safety is absolute, progress depends on timing.