Sub topic 13
Consensus: how strong consistency is implemented
This chapter assumes you know what linearizability means, how quorums overlap, and what a replicated log is at a basic level. You should also be comfortable reading short Python snippets.
The problem consensus solves
Quorum reads and writes (R + W > N) do not make a system linearizable on their own. Two clients can write concurrently, replicas can apply those writes in different orders, and a read can see a half-propagated write. To behave like a single copy, all replicas must agree on one order of operations.
Consensus is the problem of getting a set of nodes to agree on a single value, even when some nodes crash and messages are delayed or lost. A consensus protocol must satisfy three properties:
- Agreement: no two nodes decide different values.
- Validity: the decided value was proposed by some node.
- Termination: every non-crashed node eventually decides.
Agreement and validity are safety properties. Termination is a liveness property. The FLP result shows that no deterministic protocol can guarantee termination in a fully asynchronous network if even one node may crash. Practical protocols such as Paxos and Raft keep safety always and give up guaranteed liveness. They make progress only when the network is stable enough, which in practice means timeouts and leader election.
From consensus to a replicated state machine
A single consensus decision picks one value. A database needs an ordered sequence of operations. The standard construction is the replicated state machine:
- Every replica starts from the same initial state.
- Operations are deterministic: the same operation applied to the same state gives the same result.
- Consensus is run once per log slot to decide which operation occupies slot 1, slot 2, and so on.
- Every replica applies the decided log entries in slot order.
Because all replicas apply the same operations in the same order, they pass through the same states. A client sees one total order of operations, which is the raw material for linearizability.
Leader-based protocols
Running a full consensus round per operation is expensive. Raft and Multi-Paxos reduce the cost by electing a leader. The leader orders client requests and replicates them to followers. Only when a majority of nodes (a quorum of size floor(N/2) + 1) have stored an entry does the leader mark it committed.
Leadership is divided into terms (Raft) or ballots (Paxos). Each term has at most one leader. A node grants its vote to a candidate only if it has not already voted in that term and the candidate's log is at least as up to date as its own. Two majorities always overlap in at least one node, so a newly elected leader is guaranteed to hear from a node that holds every committed entry. This is the same overlap idea as R + W > N, applied to elections and log replication.
def majority(n):
"""Smallest number of nodes that forms a majority of n."""
return n // 2 + 1
def tolerated_failures(n):
"""How many crashed nodes a cluster can survive and still commit."""
return n - majority(n)
for n in (3, 5, 7):
print(n, majority(n), tolerated_failures(n))
# 3 2 1
# 5 3 2
# 7 4 3Note that an even cluster size buys nothing. Four nodes need a majority of three and tolerate one failure, the same as three nodes.
Where the linearizability guarantee can break
Committing writes through a majority is not enough. Reads need care too, and several failure modes are common.
Stale leaders
After a network partition, an old leader may not know it has been replaced. If it answers a read from its local state, it can return a value older than one committed by the new leader. That read violates linearizability. There are three standard fixes:
| Approach | How it works | Cost |
|---|---|---|
| Log reads | Put the read through the log like a write | One consensus round per read |
| Read index | Leader confirms it is still leader by contacting a majority, then serves the read | One round of heartbeats, no log append |
| Leader leases | Leader serves reads locally while its time-limited lease is valid | Depends on bounded clock drift |
Leases are fastest but rely on clocks. If a clock jumps or a process pauses (for example during garbage collection) past the lease expiry, two nodes can believe they are leader and a stale read becomes possible.
Retries and duplicate execution
A client that times out cannot tell whether its write was committed. If it retries, the operation may run twice. Systems handle this by attaching a client ID and sequence number to each request, so the state machine can detect and skip duplicates. Without this, a retried increment counts twice.
Unknown outcomes
A timeout is not a failure. The write may be committed, uncommitted, or committed later after a leader change. When you test or build on such a system, treat a timed-out operation as possibly applied at any later time.
The cost of consensus
Consensus buys strong consistency at a price that PACELC makes explicit.
- Latency: each write needs at least one round trip from the leader to a majority. In a multi-region cluster that round trip crosses the wide area.
- Availability: a minority partition cannot commit writes. This is the CP side of CAP.
- Throughput: a single leader orders everything, so it becomes a bottleneck. Large systems split data into shards, each with its own consensus group.
- Membership changes: adding or removing nodes must itself go through consensus. Changing membership unsafely can create two disjoint majorities, so protocols use joint configurations or one-node-at-a-time changes.
What consensus systems are used for
Most applications do not implement consensus themselves. They use a system that does, such as etcd, ZooKeeper, or Consul. These store small, critical data: configuration, leader election, locks, and cluster membership. Distributed databases such as Spanner and CockroachDB run a consensus group per data range and combine it with transactions to offer strict serializability, covered in the next chapter.
Common mistakes
- Believing that "uses Raft" means every read is linearizable. Reads served by followers or by an unconfirmed leader can be stale.
- Using an even number of nodes and expecting more fault tolerance.
- Treating a timeout as a failed write and retrying without deduplication.
- Spreading a consensus group across distant regions without budgeting for the added write latency.
- Assuming consensus removes the need for application-level idempotency.
Exercise
A five-node Raft cluster is split by a partition into a group of two nodes (containing the old leader) and a group of three. A client talking to the old leader issues a read, and the old leader answers from its local state without contacting anyone. Can this violate linearizability, and what should the old leader have done?
Show answer
Yes. The group of three can elect a new leader, because three is a majority of five, and commit new writes. The old leader in the group of two cannot reach a majority, but it may still believe it is leader, so its local read can return a value that predates those writes. That is a stale read. It should have used a read index (confirm leadership with a majority before answering, which would fail here), put the read through the log, or served it under a valid leader lease. The client should then get an error or a timeout instead of stale data.
Exercise
Why does a seven-node cluster tolerate three failures while an eight-node cluster still tolerates only three?
Show answer
A majority of seven is four, so seven nodes tolerate 7 - 4 = 3 failures. A majority of eight is five, so eight nodes tolerate 8 - 5 = 3 failures. The extra node adds replication cost and does not add fault tolerance.