Distributed SystemsVol. 5 · Part V
0 / 0

Shelves / Distributed Systems

DS·72

Consensus

Getting nodes to agree despite crashes and unreliable networks: the consensus problem and its properties, its equivalence to total-order broadcast and state machine replication, majority quorums and why they work, Paxos (single-decree and Multi-Paxos) step by step, Raft in depth (terms, leader election, log replication, the commit rule, safety, membership changes, snapshots, linearizable reads), Zab and Viewstamped Replication, variants (Flexible Paxos, EPaxos), Byzantine consensus, why consensus is hard, and real implementations in Go, Rust, Java and Elixir.

31 topics · ~21 min read · 31-question quiz
Updated Suggest a correction

Start here: agreeing despite failures

The problem consensus solves

Some decisions must be made once by a group of machines, even if some crash: who is the leader, whether a transaction committed, which value a key holds, which configuration is current. Consensus gets several nodes to agree on one value (and, in practice, on a sequence of values, a replicated log) such that the decision is never undone, and progress continues as long as a majority is alive.

Raft elects a leader; the leader appends client commands to its log and sends them to followers; an entry is committed once a majority has stored it, and then every member applies it in the same order.

Text
1) 3-member Raft cluster (etcd 3.6) after 20 writes:
   127.0.0.21:2379: follower term 2, log index 31
   127.0.0.22:2379: LEADER   term 2, log index 31
   127.0.0.23:2379: follower term 2, log index 31

Every member holds the same log up to index 31. The term numbers leaderships: each election starts a new term, and a message from an older term is ignored, which is how a deposed leader is stopped from doing damage.

Failure, election, majority

Text
2) killed the leader (member 2, term 2): member 3 elected in term 3; writes resumed after 1.21 s
3) killed a second member: 1 of 3 left, write accepted? False (no majority)
   restarted both: write accepted? True; every member's log index: [40, 40, 40]

When the leader died, the followers stopped hearing heartbeats; after an election timeout one of them became a candidate, asked for votes, won a majority and became leader in term 3. Nothing committed was lost, because a candidate can only win if its log is at least as up to date as a majority's, and every committed entry is on a majority. With two of three members dead, no majority existed and writes stopped rather than risk divergence. When they returned, they caught up from the leader's log.

Interactive diagram: Raft: electing a leader and committing a write. It needs JavaScript; the text around it says the same.
Members Majority Failures tolerated
1 1 0
3 2 1
4 3 1
5 3 2
7 4 3

Odd sizes are standard: a fourth member adds cost and latency but no extra tolerance. Most deployments use 3 or 5.

What consensus is used for

You rarely implement consensus; you use a system built on it: etcd for Kubernetes' state, ZooKeeper or KRaft for Kafka's metadata, Consul for service discovery, the Raft groups inside CockroachDB, TiDB and YugabyteDB that replicate each range of data. When you need a leader election, a distributed lock, a configuration store or a unique sequence, reach for one of these (chapter 77) rather than inventing a protocol.

How deep to go in consensus

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain what consensus is for, majorities, leaders and terms
L2 Run and use etcd, ZooKeeper or Consul: sizing, endpoints, transactions, health
L3 Explain Raft's election, log replication and safety; Paxos at a high level; FLP
L4 Diagnose election storms, slow disks, quorum loss and membership mistakes
L5 Design systems on consensus services: what to put in them and what not to
L6 Implement, test (Jepsen, model checking with TLA+) and operate consensus at scale

The consensus problem

Definition

Consensus: a set of processes each propose a value, and all non-faulty processes must decide on one value, satisfying:

Property Meaning Kind
Agreement No two correct processes decide differently Safety
Validity (integrity) The decided value was proposed by some process Safety
Integrity Each process decides at most once Safety
Termination Every correct process eventually decides Liveness

It looks easy until you add failures. With crashes and an asynchronous network, FLP (chapter 65) proves no deterministic algorithm guarantees termination. Practical algorithms (Paxos, Raft) always preserve safety and terminate when the network is "synchronous enough" for a while (partial synchrony), using timeouts.

Why consensus is everywhere

Many problems are equivalent to consensus (solving one solves the others):

  • Leader election: agree on who leads in a given term.
  • Atomic commit across nodes: agree to commit or abort (chapter 73; 2PC is a blocking special case).
  • Total-order (atomic) broadcast: all nodes deliver the same messages in the same order. A sequence of consensus instances, one per log slot, yields a totally ordered log.
  • Linearizable compare-and-set registers, distributed locks, uniqueness constraints.
  • Membership: agree on which nodes are in the cluster.

State machine replication

The central application: replicated state machines (Lamport 1978, Schneider 1990). If several replicas start in the same state and apply the same deterministic commands in the same order, they end in the same state. Consensus provides the order (a replicated log); each replica applies log entries to its state machine (a key-value store, a lock table, cluster metadata).

client server 1 (leader) consensus logx←3 y←1 y←9 state machinex=3 y=9 server 2 consensus logx←3 y←1 y←9 state machinex=3 y=9 server 3 consensus logx←3 y←1 y←9 state machinex=3 y=9
Replicated state machine. Clients send commands to the leader; the consensus module replicates them into an identical log on every server; each server applies committed entries in order to its deterministic state machine, so all state machines hold the same state.

That's how etcd, ZooKeeper, Consul, Kafka's KRaft metadata, CockroachDB/TiKV ranges, Spanner splits and RabbitMQ quorum queues work.

Quorums

Majority quorums

With N = 2f + 1 nodes, a majority is f + 1. Any two majorities intersect in at least one node. That intersection is the core of every consensus safety argument: if a value was accepted by a majority, any later majority contains at least one node that knows about it, so a new leader can't "forget" it.

Cluster size N Majority Failures tolerated f
1 1 0
2 2 0 (worse than 1: two points of failure)
3 2 1
4 3 1 (no better than 3, and more chatty)
5 3 2
7 4 3

That's why consensus clusters have odd sizes, usually 3 or 5. More nodes increase fault tolerance but slow writes (a larger quorum must respond) and don't increase write throughput, since all writes go through one leader.

Flexible Paxos (Howard, Malkhi and Spiegelman, 2016) showed that only leader-election quorums and replication quorums must intersect, not all quorums pairwise. So you can use smaller replication quorums (faster writes) with larger election quorums.

Paxos

Single-decree Paxos

Leslie Lamport's Paxos (written 1989, published 1998 as "The Part-Time Parliament"; "Paxos Made Simple", 2001) decides one value. Roles (one process can play several):

  • Proposers propose values.
  • Acceptors vote; a majority of acceptors decides.
  • Learners learn the decided value.

Each proposal has a unique, increasing proposal number (ballot) n, e.g. (counter, nodeId).

Phase 1: prepare / promise

  1. A proposer picks n and sends Prepare(n) to acceptors.
  2. An acceptor that hasn't promised a higher number replies Promise(n, accepted): it promises to ignore proposals numbered < n, and includes the highest-numbered proposal it has already accepted, if any.

Phase 2: accept / accepted

  1. With promises from a majority, the proposer sends Accept(n, v) where v is the value of the highest-numbered accepted proposal reported, or its own value if none was reported. This rule is the heart of Paxos: once a value might have been chosen, every later proposer is forced to re-propose it.
  2. An acceptor accepts unless it has promised a higher number, and tells learners.
  3. A value is chosen once a majority has accepted the same (n, v).
proposerA1A2A3 ① Prepare(5) ② Promise(5, none)slow ③ Accept(5, X) ④ Accepted(5, X) majority accepted → X chosen
Single-decree Paxos message flow with three acceptors. Phase 1 gathers promises from a majority; Phase 2 asks them to accept a value, which is chosen when a majority accepts. If any acceptor reported an earlier accepted value, the proposer must use that value instead of its own.

Why it's safe, and why it can livelock

Safety sketch: suppose value v was chosen with ballot n (a majority accepted it). Any proposer with a higher ballot n′ must get promises from a majority, which intersects the majority that accepted (n, v). At least one promise reports v (or a value from a later ballot that, by induction, is also v), so the proposer must propose v. No different value can ever be chosen.

Liveness problem (duelling proposers): proposer P1 prepares 5; P2 prepares 6 (invalidating 5 before P1's accept); P1 retries with 7, invalidating 6; and so on forever. The fix is to elect a distinguished proposer (leader) and use randomised backoff, which is where FLP bites: leader election itself needs timeouts.

Multi-Paxos

Real systems need a sequence of decisions (a log). Multi-Paxos runs one Paxos instance per log slot, but with a stable leader it runs Phase 1 once for all future slots, and then each new entry needs only Phase 2 (one round trip to a majority). That's essentially what Raft formalises.

Paxos-family systems: Google Chubby and Spanner (Multi-Paxos per split), Megastore, Cassandra lightweight transactions (single-decree Paxos per partition operation), Azure storage, Neo4j (historically), and ZooKeeper's Zab and Viewstamped Replication (Oki and Liskov, 1988, which predates Paxos) are closely related designs.

"Paxos Made Live" (Google, 2007) catalogues how hard the gap is between the paper and production: disk corruption, master leases, group membership, snapshots, testing.

Raft

Design goal

Raft (Ongaro and Ousterhout, "In Search of an Understandable Consensus Algorithm", 2014) provides the same guarantees as Multi-Paxos but is decomposed for understandability:

  1. Leader election
  2. Log replication
  3. Safety
  4. Plus membership changes and log compaction

Each server is a follower, candidate or leader. Time is divided into terms (monotonically increasing integers), each starting with an election; at most one leader per term.

follower candidate leader timeout majority votes split vote: timeout, new term sees leader / higher term leader sees higher term → steps down
Raft server states. Followers become candidates when their election timeout fires without hearing from a leader; a candidate that wins votes from a majority becomes leader; any server that sees a higher term reverts to follower.

Leader election

  • The leader sends periodic heartbeats (empty AppendEntries).
  • A follower that hears nothing for its election timeout (randomised, e.g. 150–300 ms, or 1 s in etcd's defaults) increments its term, becomes a candidate, votes for itself, and sends RequestVote(term, lastLogIndex, lastLogTerm) to all.
  • A server grants at most one vote per term, first come first served, and only if the candidate's log is at least as up-to-date as its own (compare last log term, then last index). That's the election restriction, which guarantees the winner has all committed entries.
  • A candidate with votes from a majority becomes leader and starts heartbeating.
  • Randomised timeouts make split votes rare and resolve them quickly.
  • Any message with a higher term makes the receiver update its term and become a follower. Stale leaders step down as soon as they hear from the newer term.

Practical improvements:

  • Pre-vote (a candidate first checks it could win before incrementing its term), so a node rejoining after a partition doesn't disrupt a healthy leader.
  • Check-quorum (a leader steps down if it hasn't heard from a majority recently).
  • Leadership transfer for planned maintenance.

Log replication

  1. The leader appends the client's command to its log as entry (term, index, command).
  2. It sends AppendEntries(term, prevLogIndex, prevLogTerm, entries[], leaderCommit) to followers.
  3. A follower rejects if it doesn't have an entry at prevLogIndex with prevLogTerm (the consistency check). The leader then backs up nextIndex for that follower and retries, eventually overwriting the follower's divergent suffix.
  4. Once an entry is stored on a majority, the leader marks it committed, applies it to its state machine, and responds to the client. Followers learn the commit index from subsequent messages and apply too.

Log Matching Property: if two logs contain an entry with the same index and term, the logs are identical up to that index. It follows from the consistency check by induction.

index 1234567 leader 1 1 2 3 4 4 4 a 1 1 2 3 4 4 b 1 1 2 ← missing, filled in c 1 1 2 3 3 3 ← overwritten indexes 1–4 are on a majority (leader, a, c) ← | → term-4 entries still replicating
Raft logs after failures. Entries are labelled with their term. The leader for term 4 forces follower logs to match its own: follower b is missing entries and is filled in; follower c has uncommitted divergent entries from term 3 that get overwritten. Indexes 1–4 are on a majority; they count as committed once a term-4 entry after them reaches a majority too.

The commit rule and safety

Raft's subtle safety rule: a leader only commits entries from its own current term by counting replicas. Entries from previous terms are committed indirectly, when a current-term entry after them is committed.

Why? Figure 8 of the Raft paper shows a scenario in which an entry from an old term, replicated to a majority by a later leader, can still be overwritten by another leader that doesn't have it, because a server with a log that's "more up to date" by term can win an election without that entry. Counting replicas only for current-term entries prevents committing such an entry prematurely.

Safety properties Raft guarantees:

  • Election Safety: at most one leader per term.
  • Leader Append-Only: a leader never overwrites or deletes its own entries.
  • Log Matching: same index and term implies identical prefixes.
  • Leader Completeness: a committed entry is present in the logs of all future leaders.
  • State Machine Safety: no two servers apply different commands at the same index.

Persistence

To survive crashes (the crash-recovery model), each server persists currentTerm, votedFor and the log to stable storage (fsync) before responding to RPCs. Skipping fsync for speed reintroduces split-vote and lost-commit bugs: a restarted node could vote twice in the same term.

Membership changes

Changing the cluster (3 → 5 nodes, or replacing a node) is dangerous: during the switch, old and new configurations might form two disjoint majorities and elect two leaders. Raft offers:

  • Joint consensus: an intermediate configuration C_old,new that requires majorities of both old and new configurations; then switch to C_new.
  • Single-server changes: add or remove one server at a time, which guarantees old and new majorities overlap. That's what most implementations use (etcd, hashicorp/raft), usually with learners / non-voting members that catch up before being promoted to voters.

Log compaction and snapshots

Logs can't grow forever. Each server periodically snapshots its state machine at index i, and discards log entries up to i. A follower that's far behind receives the snapshot via InstallSnapshot.

Linearizable reads in Raft

Reading directly from the leader's state machine isn't linearizable: a deposed leader that doesn't know it's been replaced (partitioned) could serve stale data. Options:

Method How Cost
Log read Append the read as a log entry; answer when it commits A full replication round + disk write
ReadIndex Record the commit index; confirm leadership with a heartbeat round to a majority; wait until applied ≥ that index; answer One network round, no disk write (etcd's default)
Lease read Leader assumes it's still leader for a lease period after a successful heartbeat round (lease < election timeout) No extra round; relies on bounded clock drift
Follower read Follower asks the leader for the ReadIndex, waits until applied, answers locally Offloads reads from leader

Raft in practice

Implementations: etcd/raft (Go, used by etcd, Kubernetes via etcd, CockroachDB's fork, TiKV's raft-rs port), hashicorp/raft (Go; Consul, Nomad, Vault integrated storage), raft-rs (Rust, TiKV), openraft (Rust, async), Apache Ratis (Java; Apache Ozone, IoTDB), JRaft / SOFAJRaft (Java), Ra (Erlang; RabbitMQ quorum queues and streams' Khepri metadata store), NuRaft (C++, ClickHouse Keeper), Kafka KRaft, Redpanda (C++, Raft per partition), MongoDB (Raft-inspired replication protocol), Dragonboat (Go, multi-group).

Multi-Raft: large databases split data into thousands of ranges, each its own Raft group (CockroachDB ranges, TiKV regions, YugabyteDB tablets). Heartbeats are coalesced and leadership is spread across nodes for load balance.

// Go: hashicorp/raft, you implement a deterministic FSM; Raft feeds it committed log entries in order
type kvFSM struct {
    mu   sync.Mutex
    data map[string]string
}

func (f *kvFSM) Apply(l *raft.Log) interface{} {          // called on every node, same order
    var cmd struct{ Op, Key, Value string }
    if err := json.Unmarshal(l.Data, &cmd); err != nil { return err }
    f.mu.Lock(); defer f.mu.Unlock()
    switch cmd.Op {
    case "set": f.data[cmd.Key] = cmd.Value
    case "del": delete(f.data, cmd.Key)
    }
    return nil
}
func (f *kvFSM) Snapshot() (raft.FSMSnapshot, error) { /* copy map */ return snapshotOf(f), nil }
func (f *kvFSM) Restore(rc io.ReadCloser) error      { /* replace map */ return restoreInto(f, rc) }

// Leader-only write: returns once committed on a majority and applied locally
future := r.Apply(mustJSON(cmd{"set", "x", "3"}), 500*time.Millisecond)
if err := future.Error(); errors.Is(err, raft.ErrNotLeader) { /* redirect to r.Leader() */ }
TLA+
\* TLA+ fragment: the safety property model checkers verify for Raft-like specs
ElectionSafety == \A i, j \in Server :
                    (state[i] = Leader /\ state[j] = Leader /\ currentTerm[i] = currentTerm[j]) => i = j

Byzantine consensus

When nodes may lie (malicious or arbitrarily faulty), you need Byzantine fault tolerance (BFT):

  • Requires N ≥ 3f + 1 nodes to tolerate f Byzantine nodes, and quorums of 2f + 1, so any two quorums overlap in at least f + 1 nodes, at least one of which is honest.
  • PBFT (Castro and Liskov, 1999): three phases (pre-prepare, prepare, commit), O(n²) messages.
  • Tendermint/CometBFT, HotStuff (linear communication, the basis of several blockchain protocols), Narwhal/Bullshark-style DAG protocols.
  • Proof-of-work / proof-of-stake blockchains reach probabilistic agreement in open, permissionless settings.

Datacentre systems rarely use BFT: the threat model is crashes and bugs, not malicious nodes, and BFT is much costlier. Checksums, authenticated channels and careful operations handle corruption.

Why consensus is hard

The roadmap asks this explicitly. The reasons, collected:

  1. Impossibility results (FLP, two generals): you can't have guaranteed termination with crashes in an asynchronous system; algorithms are designed around this, with timeouts that are only heuristics.
  2. Uncertain failure detection: a slow node and a dead node look identical, so you will sometimes elect a new leader while the old one is alive, which is why terms, epochs and fencing exist.
  3. Subtle interleavings: the bug in Raft's Figure 8 scenario is an example; such races are rare in tests and appear only under specific crash and timing sequences. Formal specs (TLA+) and model checking are standard practice for this reason.
  4. Persistence and disks: fsync semantics, partial writes, disk corruption and lying disks break assumptions ("Paxos Made Live", "Protocol-Aware Recovery for Consensus-Based Storage").
  5. Membership changes, snapshots and compaction add states the core algorithm doesn't cover.
  6. Performance: every write needs a majority round trip and an fsync; batching, pipelining and multi-group designs are needed for throughput, each adding complexity.
  7. Operations: losing a majority stops the cluster; recovering requires careful manual steps (e.g. etcd's --force-new-cluster), and mistakes cause split brain or data loss.

Don't implement consensus yourself for production. Use etcd, ZooKeeper, Consul, a consensus-based database, or a battle-tested library, and understand its guarantees and failure modes.

Lab: a Raft cluster under load and failure

Throwaway etcd 3.6 clusters on one 2-core machine, each member on its own loopback address with its own data directory on the same disk; Python clients over etcd's HTTP gateway. Because all members share one machine and disk, absolute numbers are lower bounds; the comparisons are what matter.

Experiment 1: what each member and each fsync costs

500 sequential puts to the leader:

Text
1 member:                       median 1.10 ms, p99 3.36 ms
3 members:                      median 1.76 ms, p99 4.64 ms
5 members:                      median 2.26 ms, p99 5.03 ms
3 members, --unsafe-no-fsync:   median 1.15 ms, p99 2.75 ms

A Raft write costs the leader's fsync plus a round to a majority, who each fsync too. Going from 1 to 3 to 5 members added latency (more messages and, on one disk, more fsyncs competing). Turning off fsync removed most of the gap, which shows where the time goes: disk sync latency is the critical path of consensus. That's why etcd's docs insist on SSDs with low fsync latency (etcd_disk_wal_fsync_duration_seconds p99 under 10 ms) and why a slow disk on one member causes leader elections. Never run --unsafe-no-fsync for real data: a power loss can then lose committed entries.

Experiment 2: throughput from batching

Writes per second for 3 seconds, 3 members:

Text
 1 concurrent client:  520 writes/s
16 concurrent clients: 1,687 writes/s

One client waits for each write before sending the next, so it gets at most 1 / latency. With 16 clients in flight, the leader batched many proposals into each append and fsync, tripling throughput (and the Python clients, not etcd, were likely the limit here). Consensus systems are latency-bound per operation and batch-friendly in aggregate.

Experiment 3: correctness needs compare-and-swap

8 clients each increment a counter 100 times:

Text
read then put:                     counter = 173
compare-and-swap on mod_revision:  counter = 800, 2905 retries

Consensus makes each operation linearizable; it doesn't make your read-modify-write sequence atomic. Reading then writing lost 627 of 800 increments. etcd transactions compare a key's mod_revision and write only if nothing changed in between; the losers retried (2,905 times under this contention) and every increment counted. Use the same pattern for leader leases, configuration updates and any check-then-act on a consensus store.

Experiment 4: election timeouts

The leader was killed with SIGKILL five times; a client wrote with 200 ms timeouts until a write succeeded:

Text
default timeouts (heartbeat 100 ms, election 1,000 ms): writes resumed after 1.01, 1.21, 1.61, 1.21, 1.81 s
heartbeat 50 ms, election 300 ms:                        writes resumed after 0.61, 0.41, 0.41, 0.40, 0.40 s

Failover time is roughly the election timeout plus a randomised delay plus one voting round. Shorter timeouts recover faster, but if they approach real network or disk hiccups (a GC pause, a slow fsync), followers start elections against a healthy leader, and each election is itself a short outage. etcd's guidance: heartbeat about the round-trip time between members, election timeout at least 10× that; across regions, seconds.

Try it yourself

  1. Put members on three machines (or containers with tc netem delay of 10 ms) and repeat experiment 1.
  2. Run experiment 3 with etcd's concurrency package (a mutex) instead of CAS and compare throughput.
  3. Watch etcdctl endpoint status while running stress-ng --hdd on one member's disk. Do elections happen?
  4. Read the Raft paper's Figure 2 and trace experiment 4's election through RequestVote messages with --log-level debug.

Revision sheet: consensus

Key ideas

  • Consensus: agreement, validity, integrity (safety) and termination (liveness); state machine replication through a replicated log.
  • FLP (1985): no deterministic algorithm guarantees consensus in a fully asynchronous system with even one crash; real systems use timeouts (partial synchrony) and keep safety always, liveness when the network behaves.
  • Quorums: majorities intersect; N = 2f + 1 tolerates f crashes.
  • Paxos: proposers, acceptors, learners; prepare/promise and accept/accepted with ballot numbers; Multi-Paxos with a stable leader.
  • Raft: leader election with randomised timeouts and terms; log replication with consistency checks; commit on majority in current term; election restriction; membership changes (joint consensus or single-server changes); snapshots; ReadIndex and lease reads.
  • Others: Zab (ZooKeeper), Viewstamped Replication, EPaxos and flexible quorums.
  • Byzantine: PBFT and descendants need 3f + 1 nodes; used in blockchains and some aerospace systems.
  • Practice: use etcd, ZooKeeper, Consul or an embedded Raft library; keep consensus state small; fsync latency and network RTT bound performance.

Numbers to remember

  • 3 members tolerate 1 failure, 5 tolerate 2; BFT needs 3f + 1.
  • etcd defaults: heartbeat 100 ms, election 1,000 ms; recommended keyspace under 8 GB (default quota 2 GB).
  • Lab: puts 1.10 ms (1 member), 1.76 ms (3), 2.26 ms (5), 1.15 ms without fsync; batching took 520 to 1,687 writes/s; read-then-put lost 627 of 800 increments; tuned timeouts cut failover from 1–1.8 s to 0.4–0.6 s.

Pitfalls

  • Even-sized clusters; clusters stretched over high-latency links without tuning.
  • Slow or shared disks under consensus members.
  • Storing large or high-churn data in etcd/ZooKeeper.
  • Read-modify-write without compare-and-swap.
  • Changing membership of a cluster that has lost quorum (needs disaster recovery, not an add).

Glossary

  • Replicated state machine: identical deterministic machines applying the same log.
  • Term / ballot / epoch: monotonically increasing leadership number.
  • Commit index: highest log entry known to be committed.
  • Election timeout: silence after which a follower campaigns.
  • Joint consensus: Raft's two-phase configuration change.
  • Lease read: leader serves reads without a round, relying on bounded clock drift.