Chapter 06 / 10 · Distributed Systems

Consensus

The wallet’s replicas choose their own leader, never two at once, and never forget a transfer they acknowledged.

This chapter explains how a group of machines agrees on one answer and keeps it agreed while some of them crash. By the end you should be able to trace a leader election and a log commit in Raft, say what the group can survive given where its machines are, and explain why a deposed leader cannot lose a committed transfer.

In the replication chapter, an engineer promoted a follower by hand during a power failure. Acknowledged transfers were lost, ids were reused, and when power returned there were two leaders. We want the three wallet replicas to make that decision themselves, quickly, and in a way that can never produce two leaders at once or forget a transfer that was acknowledged.

What we are asking the replicas to agree on

Consensus is the problem of getting several machines to decide on one value, such that all of them that decide pick the same value, the value was actually proposed by someone, and they eventually decide as long as enough of them are running and can talk. For the wallet the value is “who leads in this period”, and then, repeatedly, “which transfer is entry number 4,418 in the log”. If every replica agrees on every log entry, they all apply the same transfers in the same order, which is the total-order broadcast from the last chapter.

Two tempting shortcuts fail, and seeing why tells us what the real protocol must do. The first is a fixed coordinator that decides and tells everyone. That is a single point of failure; if it crashes mid-decision, nobody knows what was decided. The second is to let any replica that thinks the leader is dead declare itself leader. During a partition, each side thinks the other is dead, and both declare. We need a rule under which two different leaders cannot both be legitimate.

The rule all practical protocols use is a majority. Out of three replicas, any two form a majority; out of five, any three. Any two majorities of the same group must share at least one member, since two disjoint groups of two would need four replicas out of three. If every decision requires a majority, and each replica takes part in at most one decision of a given kind, two conflicting decisions cannot both happen, because the shared member would have to take part in both.

Where the replicas live decides what they survive

A majority rule turns placement into arithmetic. Our wallet has two replicas in DC-1 and one in DC-2.

Predict first

The three wallet replicas are placed two in DC-1 and one in DC-2. What happens to transfers if (a) one DC-1 machine dies, (b) the link between the data centres is cut, (c) DC-1 loses power entirely?

Show the worked answer

(a) The remaining DC-1 machine and the DC-2 machine are two of three, a majority. Transfers continue, after an election if the dead machine was the leader.

(b) DC-1’s two replicas are still a majority and keep accepting transfers. The DC-2 replica is alone. It cannot win an election, so it cannot accept writes. Clients in DC-2 that can reach DC-1 through another path keep working; those that cannot are refused.

(c) Only the DC-2 replica is left, one of three. It cannot form a majority, so the wallet stops accepting transfers until DC-1 returns. No data is lost, since the DC-1 disks still hold the committed log, but the wallet is unavailable.

So a 2 + 1 layout across two sites survives the loss of a machine, not of a site. With two sites, whichever site holds the majority is a single point of failure. Surviving a site loss needs a third site, even if it only holds a lightweight voting replica.

That answer explains a pattern seen in many production deployments: three sites, one replica each, or five replicas spread 2 + 2 + 1. With one replica per site, losing any site leaves two of three. The cost is latency. A log entry commits when a majority has it, so the leader must wait for at least one replica in another site on every commit. If the nearest other site is 30 ms away, every transfer takes at least 30 ms to commit. The 2 + 1 layout commits in about a millisecond, because the leader and its neighbour in DC-1 form a majority, and pays for that speed with the site-loss behaviour above.

Terms and votes

We will use Raft, which was designed to be understood and is used in etcd, Consul, CockroachDB, TiKV and Kafka’s newer controller. Raft divides time into numbered terms. Each term begins with an election and has at most one leader. Every message carries the sender’s term, and a replica that sees a higher term than its own adopts it and, if it was leader, steps down at once.

A leader sends heartbeats to its followers several times per election timeout. A follower that hears nothing for its election timeout assumes the leader is gone. It increments its term, becomes a candidate, votes for itself and asks the others for votes. Each replica grants at most one vote per term and writes that vote to disk before replying, so that a crash and restart cannot let it vote twice. A candidate that collects a majority becomes leader for that term.

That rule is where the majority argument does its work. Two candidates in the same term would each need a majority, the majorities would share a replica, and that replica can vote only once. So there is at most one leader per term. There can be an old leader from an earlier term that has not yet heard about the new one, and we will deal with it shortly.

If two followers time out at the same moment, they can split the vote and neither wins. Raft makes this unlikely by randomising each follower’s timeout within a range, so one usually starts its campaign first and wins before the other wakes up. The Raft paper uses 150 to 300 ms on a local network. etcd defaults to a 100 ms heartbeat and a 1,000 ms election timeout, and recommends raising both when replicas are far apart, since a timeout must comfortably exceed the round trip between them. Shorter timeouts mean faster failover and more spurious elections when a garbage-collection pause or a slow link is mistaken for a death.

The log, and when an entry counts

Once elected, the leader accepts transfers. For each one it appends an entry to its log and sends it to the followers. An entry is committed once a majority of replicas have stored it. Only then does the leader apply it to the balances and reply “Sent” to the caller.

leader12345follower12345follower12345committed — on a majority (2 of 3)the slow follower is behind, not wrong — it will catch up from the leader
Fig 6 · The leader and one follower hold entries 1–5; the slow follower has 1–3. Entries 1–5 are committed because two of three replicas hold them

Followers check that their log matches the leader’s before accepting anything. Each append message includes the index and term of the entry just before the new ones. If the follower has no entry at that index with that term, it refuses, and the leader retries one entry further back until the two logs agree. The follower then discards anything after that point and takes the leader’s entries. This is how a follower that had extra, uncommitted entries from an old leader gets repaired.

One more rule protects committed entries across elections. A replica votes for a candidate only if the candidate’s log is at least as up to date as its own: its last entry has a higher term, or the same term and an index at least as large. A committed entry is on a majority. A winning candidate collected votes from a majority. Those majorities overlap, so at least one voter holds the committed entry, and that voter would refuse a candidate lacking it. A new leader therefore always has every committed entry, and since leaders never delete their own entries, committed transfers are never lost.

The leader that did not know it was deposed

Here is the failure the manual failover handled badly, walked through with Raft. The wallet replicas are A and B in DC-1 and C in DC-2. A leads in term 4.

A’s network link to B and C fails, but A can still reach some of the API servers in its own rack. A still believes it leads term 4. B and C stop receiving heartbeats. B’s election timeout fires first; it becomes a candidate for term 5, C votes for it, and B leads term 5 with two of three.

Meanwhile, an API server sends Asha’s transfer to A. A appends it as entry 120 in term 4 and sends it to B and C. Nothing arrives. Entry 120 is on one replica out of three, so it never commits. A never applies it and never replies “Sent”. The API server times out, and, because the request carries Asha’s idempotency key, safely retries. Its retry reaches B, which commits the transfer as entry 120 in term 5 and replies.

Predict first

When A’s network recovers, its log has entry 120 from term 4 (Asha’s transfer, never committed). B’s log has entry 120 from term 5 (the same transfer, committed, from the retry). What happens to A’s entry, and is anything lost or duplicated?

Show the worked answer

A receives a message from B carrying term 5, adopts term 5 and steps down to follower. B sends entries with the consistency check; A finds that its entry 120 has term 4 where B expects term 5, discards it, and takes B’s entry 120.

Nothing acknowledged is lost, because A’s entry was never acknowledged. Nothing is duplicated, because the retry carried the same idempotency key, and the transfer was applied once, through B. The uncommitted entry was always provisional, and Raft is allowed to throw provisional entries away.

Writes are safe in this scenario because they must commit through a majority. Reads are not automatically safe. If A answers balance reads from its own state while partitioned, it returns balances that miss everything B has committed since. Asha could see ₹2,000 on the home screen after her transfer committed. To serve a linearizable read, a leader must first confirm it is still the leader. One way, called a read index, is to record the current commit index, exchange a heartbeat with a majority, and answer once its state has applied up to that index; that costs a round trip per read or batch of reads. The other is a leader lease: after a successful heartbeat round, the leader assumes nobody else can be elected for slightly less than an election timeout, and serves reads locally until then. Lease reads are faster and rely on clocks running at roughly the same rate, which the next chapter takes seriously.

Replacing a replica without creating two majorities

Machines are replaced routinely: a disk fails, a host is retired, the team moves a replica to a new site to survive a site loss. Each change alters the group, and a careless change breaks the majority argument that everything else rests on.

Suppose the wallet grows from three replicas, A, B and C, to five by adding D and E, and the new configuration reaches the replicas at slightly different moments. For a short time, A and B may still believe the group is {A, B, C}, where two votes make a majority, while C, D and E already believe it is {A, B, C, D, E}, where three do. A and B can elect a leader with two votes under the old rule while C, D and E elect another with three under the new one. Two leaders in the same term, each with a valid majority in the configuration it believes in.

Raft offers two ways out. The original paper uses joint consensus: during the transition, every decision needs a majority of the old configuration and a majority of the new one at the same time. Only once that joint configuration has itself been committed does the group move to the new configuration alone. The simpler approach, used by many implementations, changes membership one replica at a time. Adding or removing a single replica means any majority of the old group and any majority of the new group must overlap, so there is no moment at which two disjoint majorities exist. Growing from three to five takes two steps.

A new replica also starts with an empty log. If it joined as a voting member immediately, a three-replica group would become four, with a majority of three. The new replica cannot acknowledge anything until it has caught up, so every commit would need all three of the old replicas. The slowest of them would set commit latency, and a single failure would stop writes. Implementations therefore add new replicas as non-voting learners first. The learner copies a snapshot of the state plus the recent log, and is promoted to a voter once it has caught up.

Snapshots matter for a second reason. A log that is never trimmed grows forever, and a replica that restarts would have to replay years of transfers. Each replica periodically writes a snapshot of its balances at some log index and discards the entries before it. A follower that has fallen behind past the trimmed point is sent the snapshot instead of the entries. This is routine, and it is also a common source of bugs, because sending a large snapshot competes with normal replication for the same network and disk.

What consensus guarantees, and what it cannot

Raft’s safety, meaning no two leaders in a term and no lost committed entries, never depends on timing. Messages can be delayed arbitrarily and the protocol still never decides two different things. Its liveness, meaning that it eventually makes progress, does depend on timing: elections need timeouts, and a network that delays messages badly enough can cause election after election with no leader lasting long enough to commit anything.

This is not a weakness of Raft in particular. A 1985 result by Fischer, Lynch and Paterson shows that in a fully asynchronous system, where messages can take any time to arrive, no deterministic protocol can guarantee that it always decides if even one process may crash. Practical protocols keep safety unconditional and accept that progress requires the network to behave reasonably for long enough. In production this appears as a flapping link that makes a replica start elections repeatedly, bumping the term and disrupting a healthy leader. etcd’s pre-vote option addresses this: a replica first asks whether it would win before it increments its term.

ChoiceWhat it improvesWhat the design must also handle
3 votersSurvives 1 failure; commit needs 1 followerA second failure stops writes
5 votersSurvives 2 failuresCommit needs 2 followers; more traffic per entry
4 votersNothing over 3Majority is 3, so it still survives only 1 failure
One voter per siteSurvives losing a siteEvery commit waits for a cross-site round trip
Majority in one siteCommit at local-network speedThat site is a single point of failure for writes
Batching entriesThroughput: many transfers per round tripA little added latency per entry

Throughput deserves a word, since “every write needs a majority round trip” sounds slow. The leader does not wait for one entry to commit before sending the next. It pipelines entries and batches many transfers into each append message and each disk flush. A Raft group in one data centre can commit tens of thousands of small entries per second; the limit is usually the disk’s flush rate and the network, not the protocol’s rules.

When not to run consensus yourself

There are two common ways to apply consensus to the wallet. One is to put every transfer through a Raft log, as CockroachDB, TiKV and Spanner do with a consensus group per range of keys. The other is to keep an ordinary database with a primary and a synchronous standby, and use a separate consensus service only to decide which machine is primary. Tools such as Patroni do this for Postgres with etcd. The first gives consensus guarantees on every write. The second keeps the familiar database and uses consensus only for the rare leadership decision, which is simpler to operate and leaves more of the safety to fencing the old primary correctly.

Writing your own consensus implementation is rarely the right choice for an application team. The protocol fits on a page, and the implementation details (persisting votes before replying, snapshotting long logs, changing membership safely, the rule that a leader only counts replicas for entries from its own term) have each caused bugs in mature systems. Revisit this only if no existing library or service fits your constraints.

That second approach, a small consensus service deciding who is primary, raises its own question. The service grants leadership to a wallet server. What stops that server from acting on a grant that has expired while it was paused? The next chapter, Membership, failure detection and coordination, deals with leases and fencing tokens.