Sina Vafadar

Consistency and Consensus

Nov 26, 2026 · 30 min

Designing Data-Intensive Applications · Chapter 9 · Recall lab

Chapter 8 ended with a list of everything that can go wrong: packets lost, reordered, duplicated or arbitrarily delayed, clocks that are approximate at best, nodes that pause or crash at any time. This chapter is about building fault-tolerant systems anyway. The best way to do that, as with transactions, is to find general-purpose abstractions with useful guarantees, implement them once, and let applications rely on them. The most important of these is consensus: getting all the nodes to agree on something, despite all those faults.

The vocabulary § Consistency Guarantees

Eventually is not a time

Most replicated databases provide at least eventual consistency: if you stop writing and wait some unspecified length of time, all read requests eventually return the same value. A better name is convergence. It is a very weak guarantee: it says nothing about when, and until then a read could return anything or nothing. It is hard for application developers, because it behaves so differently from a variable in a single-threaded program, and its bugs only show up under faults or high concurrency.

This chapter explores stronger models. They cost something, in performance or in fault tolerance, and they are easier to use correctly. Distributed consistency models and the transaction isolation levels of chapter 7 overlap, but they are mostly independent: isolation is about avoiding race conditions between concurrently executing transactions, while distributed consistency is about coordinating the state of replicas in the face of delays and faults.

The strongest common model § Linearizability

As if there were only one copy

Wouldn’t it be simpler if the database could give the illusion that there is only one replica? Then every client would see the same data, and replication lag would not exist. That is linearizability, also called atomic consistency, strong consistency, immediate consistency or external consistency. As soon as one client successfully completes a write, every client reading from the database must be able to see the value just written. It is a recency guarantee.

The book’s opening example is a sports website. The referee records the final score; Alice, on her phone, reloads and sees it, and exclaims. Bob, next to her, hits reload, and his request goes to a replica that is lagging, so he sees the game still in progress. Bob’s request started after Alice’s had finished, so he should have seen at least what she saw. That is the whole idea, and it can be stated precisely about a single object, a register, such as one key in a key-value store:

  • Each operation takes some time, from the moment the client sends it to the moment the response arrives. A read that overlaps a write may return either the old value or the new one.
  • But once any read has returned the new value, every read that starts afterwards must return it too. There has to be some single instant, inside each operation’s interval, at which it took effect, and those instants must line up into an order a single copy could have produced.

That last sentence is mechanical enough to check. The histories below are written by hand; whether each one is linearizable, and where the instants fall, is decided by a checker that searches every order. 2 of the 4 pass.

Four histories and the linearizability checker, figures 9-2 to 9-4

Client AClient BClient CRegister xwrite 1read → 0read → 1read → 10x = 111
A read that overlaps a write may return either value

While A’s write is in progress, B’s first read is concurrent with it and gets the old value; C’s read, also concurrent, gets the new one. Both are allowed. Once some read has returned 1, though, every read that starts after it must return 1 too.

Linearizable. The checker found an instant inside every bar, marked where each line meets the register, in this order: B read → 0, A write 1, C read → 1, B read → 1.

Linearizability

A recency guarantee on reads and writes of one register, an individual object. It does not group operations into transactions, so it does not prevent write skew without extra measures such as materializing conflicts.

Serializability

An isolation property of transactions that may touch many objects: they behave as if they had run in some serial order, which may differ from the order they actually ran in. A database that provides both is strictly serializable, which two-phase locking and actual serial execution usually are. Serializable snapshot isolation is not linearizable, by design: its reads come from a snapshot that leaves out more recent writes.

Locks and leader election

A single-leader system must make sure there is only one leader, not a split brain. One way is a lock that every node tries to acquire: whichever succeeds is leader. That lock must be linearizable, so that all nodes agree who owns it. Apache ZooKeeper and etcd are used for exactly this, with consensus underneath.

Uniqueness constraints

A username, an email address, a file path, a bank balance that must never go negative, two people in the same seat on a flight: each is like acquiring a lock on a name, or an atomic compare-and-set. Enforcing them as they are written needs linearizability. Constraints like foreign keys can be enforced without it.

Cross-channel timing

A user uploads a photo; the web server writes it to storage and then puts a message on a queue asking a resizer to make a thumbnail. If the queue is faster than the storage’s replication, the resizer fetches an old version of the image (figure 9-5). Two communication channels, and only linearizable storage makes them agree.

The chapter as an experiment § Implementing Linearizable Systems

Five situations, six ways to replicate, thirty runs

The simplest linearizable system would have a single copy of the data, and that is not fault tolerant. So which replication methods from chapter 5 can be made linearizable? The book’s answers are short: single-leader potentially, consensus yes, multi-leader no, leaderless probably not. Instead of taking them on trust, here is the experiment.

Each row is a situation from the chapter, played by a few clients against three nodes. Each column replicates the register a different way, in a small simulator that records every message and every operation’s interval. Every history then goes through the same checker as the four above. Click any cell for the run that produced it.

Every cell is a run: click one to see what happened

Single leader, read any replica asynchronous followers serve reads Single leader, read the leader potentially linearizable Multi-leader every node takes writes Leaderless quorum Dynamo style, n = 3, w = 2, r = 2 Quorum + synchronous read repair the reader writes back before returning Consensus etcd; ZooKeeper with sync()
Read after a write figure 9-1
Reads during a write figure 9-6
Claim a username uniqueness
Network partition figure 9-7
Leader fails over leader crash

linearizable the checker found an order stale read no order works: an anomaly unavailable nothing wrong, but no answer

How the column works A client sends each write to all three nodes and waits for two acknowledgements, and sends each read to all three and takes the newest of the first two replies. Because w + r > n, a read always meets the last completed write. But while a write is still in flight, variable delays let a later read go backwards (figure 9-6). There is no atomic compare-and-set: it is a read, then a write.

Reads during a write under Leaderless quorumA writer sets x to 1 over slow links to nodes 2 and 3. Reader A reads while the write is in flight; reader B starts after A has finished.

WriterReader AReader BNode 1Node 2Node 3write 1read → 1read → 0write 1read100read001

Not linearizable Reader B reads 0, though Reader A had already read 1 and finished before Reader B started. Once any operation has seen the new value, every operation that starts later must see it too.

Read down the columns and the book’s verdicts appear. Reading from asynchronous followers gets 4 of the 5 wrong (read after a write, reads during a write, network partition, leader fails over), and multi-leader gets 5 wrong. Reading from the leader fixes everything except failover, where an acknowledged write dies with the old leader. The leaderless quorum surprises most people: even with strict quorums it gets 2 wrong (reads during a write, claim a username), because a read during a slow write can see the new value while a later read misses it. Synchronous read repair fixes that, at a performance cost, and leaves only the compare-and-set race, which needs consensus. Consensus gets none wrong.

Every column that stays correct during the partition does it by not answering the client on the wrong side. That is not a flaw in the simulator; it is the next section.

What linearizability costs § The Cost of Linearizability

During a partition, consistent or available

Picture two datacenters and a network interruption between them (figure 9-7). With a multi-leader database, each side keeps accepting writes and queues them for later: still available, not linearizable. With single-leader, clients connected to the follower datacenter cannot reach the leader. They can read from the follower, which is not linearizable, or they wait, which means being unavailable. Either way something gives, and that trade-off is the CAP theorem.

What CAP says

If your application requires linearizability and some replicas are disconnected from the others by a network problem, those replicas cannot process requests while disconnected: they wait, or return an error. If it does not require linearizability, each replica can process requests independently, even disconnected, and stay available. Partitions are a kind of fault that will happen whether you like it or not, so the honest phrasing is either consistent or available when partitioned, rather than “pick two out of three.”

Why the book is lukewarm about it

CAP was useful in starting a discussion and encouraged engineers to explore a wider design space. As a theorem it is narrow: it considers one consistency model, linearizability, and one kind of fault, partitions, and says nothing about network delays, dead nodes or other trade-offs. Its terms are used inconsistently, and it has been superseded by more precise results. It is best avoided as a design tool.

Linearizability is rarer than you might think, and not only because of partitions. Even the RAM on a modern multi-core CPU is not linearizable: each core has its own cache and store buffer, and a write from one thread is not immediately visible to another unless a memory barrier is used. The reason is performance, not fault tolerance. The same holds in distributed databases: Attiya and Welch proved that the response time of linearizable reads and writes is at least proportional to the uncertainty of delays in the network, which on most networks is high. The consensus column above is correct and also slowest, for this reason. A faster algorithm for linearizability does not exist; weaker models can be much faster.

What order really means § Ordering Guarantees

Cause comes before effect

Ordering keeps coming up: a single leader decides the order of writes in its log, serializability makes transactions behave as if in some sequential order, and timestamps were chapter 8’s attempt at ordering writes. Underneath all of them is causality. A question comes before its answer, a row must be created before it is updated, and a consistent snapshot must include everything that happened before what it includes. A system that respects this is causally consistent.

Causal order is partial

Linearizability gives a total order: there is one copy and every operation is atomic, so any two can be compared. Causality gives only a partial order: two events are ordered if one happened before the other, and concurrent if neither knew about the other. Like a version history in Git that branches and merges, not a single timeline.

Linearizability implies causality

Any linearizable system preserves causality correctly, which is what makes it easy to understand. But it costs performance and availability. The good news: causal consistency is the strongest model that does not slow down due to network delays and stays available during network failures, and many systems that seem to need linearizability really only need causality.

To keep track of causality, a database needs to know which version of the data each operation read, as with the version vectors of chapter 5. Doing that for every key is expensive, so a common shortcut is to number operations with sequence numbers or timestamps that are consistent with causality: if A happened before B, A gets the smaller number. A single leader can simply count. Without one, there are tempting ways to generate numbers. Here are two the book rejects and the one it recommends, on the same events, checked against all 17 causal pairs among them. Node B’s clock is 4 units behind.

Three ways to number the same events, figure 9-8

Node A (busy)Node B (quiet)carries 71235746
Each node counts on its own: odd numbers on node A, even on node B

Unique without any coordination, and fast. But a busy node’s counter races ahead of a quiet one’s, so the numbers say nothing about which event happened first.

3 of the 17 causal pairs come out backwards. For example, node B’s receive, numbered 4, happened after node A’s send, numbered 7, yet its number is not larger.

Lamport timestamps versus version vectors

Version vectors can tell whether two operations are concurrent or one depends on the other. Lamport timestamps cannot; they always produce a total order, but from that order alone you cannot tell which pairs were really concurrent. What they buy is compactness: one counter and a node ID.

Timestamp ordering is not sufficient

Suppose two users try to register the same username at once. With Lamport timestamps you could pick the one with the lower timestamp, after the fact, once you have seen every claim. A node receiving a claim cannot decide on the spot: it would have to ask every other node whether they have a lower one, and one unreachable node would stall it. You need to know when the order is finalized. That is total order broadcast.

Making the order final § Total Order Broadcast

Everyone hears everything, in the same order

Total order broadcast, or atomic broadcast, is a protocol for exchanging messages between nodes with two safety properties: reliable delivery (no message is lost: if it is delivered to one node, it is delivered to all) and totally ordered delivery (every node delivers messages in the same order). The order is fixed when messages are delivered, and a node may not insert a message earlier in the order once later ones have been delivered. That makes it stronger than timestamps.

Two claims for one username

User 1Node ANode BUser 2claimclaimuser 1’s claimuser 2’s claimyoursyours1212
Each node decides on its own: first claim it hears wins

Each node checks its own copy, finds the name free, and says yes. The other node’s claim arrives later and loses, but by then both users have been told the name is theirs.

Node A says the name belongs to user 1, node B says user 2: they disagree.

What it is good for

If every message is a write to the database, and every replica processes the same writes in the same order, the replicas stay consistent with each other: state machine replication. It is also a way of creating a log, and it is what ZooKeeper and etcd implement. A linearizable compare-and-set can be built on it: append your claim to the log, read the log, and if the first claim for the name is yours, commit. For linearizable reads, append a message and read when it comes back, or use the equivalent of etcd’s quorum reads or ZooKeeper’s sync().

Equivalent to consensus

It works the other way too: given a linearizable increment-and-get register, attach the next number to every message and deliver them in that order. But a linearizable register with an atomic increment-and-get, it turns out, is as hard as consensus. Linearizable compare-and-set, total order broadcast and consensus are all equivalent: solve one and you can turn it into a solution for the others.

Agreement across a transaction § Atomic Commit and Two-Phase Commit

All nodes commit, or all abort

Consensus problems are everywhere: leader election, so that all nodes agree who the leader is, and atomic commit, so that a transaction spanning several nodes or partitions either commits on all of them or aborts on all of them. On a single node, atomicity is one disk write: the commit record. Across nodes, sending each its own commit is not enough: one may detect a constraint violation, a request may be lost, a node may crash, and a committed transaction cannot be taken back. The classic answer is two-phase commit (2PC), not to be confused with two-phase locking.

Two-phase commit, figures 9-9 and 9-10

CoordinatorDatabase 1Database 2prepareyesyescommitcommitdecides commitcommitscommits
Phase 1, prepare: both promise. Phase 2: commit

A participant that votes yes promises it can commit under all circumstances, crash or not, and gives up the right to abort. The coordinator writes its decision to its own log, the commit point, and then tells everyone.

Outcome: database 1 commits at 5.3, database 2 commits at 5.6. Both end the same way.

There are two points of no return in that protocol: a participant that votes yes promises it will definitely be able to commit later, and once the coordinator decides, that decision is irrevocable. Those promises are what make 2PC atomic, and they are also why it is a blocking protocol: if the coordinator crashes at the wrong moment, a participant can do nothing but wait.

Distributed transactions in practice

Two kinds are often confused. Database-internal ones, between the nodes of one database such as VoltDB or MySQL Cluster’s NDB, can use any protocol and often work quite well. Heterogeneous ones span different technologies, such as two databases from different vendors or a database and a message broker, with the XA standard. They enable exactly-once message processing: acknowledge a message and commit its side effects atomically. They also carry a performance penalty: MySQL’s are reported to be over ten times slower than single-node ones.

In doubt, holding locks

A participant in doubt keeps its row locks, possibly exclusive ones, and nothing else can touch those rows until the coordinator comes back. If the coordinator’s log is lost, orphaned in-doubt transactions need an administrator to decide by hand. XA implementations have an escape hatch called a heuristic decision, which lets a participant decide on its own, and which is a euphemism for probably breaking atomicity. The coordinator is a single point of failure, often run on one machine with no replication.

The general problem § Fault-Tolerant Consensus

Agree on one value, despite crashes

Informally, consensus means getting several nodes to agree on something. Formally, one or more nodes propose values, and the algorithm decides on one of them, with four properties. Uniform agreement: no two nodes decide differently. Integrity: no node decides twice. Validity: a node that decides value v decided a v that some node proposed. Termination: every node that does not crash eventually decides. The first three are safety; the last is liveness, and it is what rules out a coordinator that everyone waits for.

The FLP result (Fischer, Lynch and Paterson) proves that no algorithm can always reach consensus if there is a risk that a node may crash. But it is proved in the asynchronous model, where an algorithm may not use any clocks or timeouts. With timeouts to suspect crashed nodes, even if the suspicion is sometimes wrong, consensus becomes solvable, and real systems routinely reach it.

The best-known fault-tolerant consensus algorithms are Viewstamped Replication, Paxos, Raft and Zab. Most of them actually decide on a sequence of values, which makes them total order broadcast algorithms. They all use a leader, but the leader is not fixed: each election gets a new epoch number (a ballot number in Paxos, a view number in Viewstamped Replication, a term number in Raft), and within each epoch the leader is unique. Before a leader decides anything, it must collect votes from a quorum, and any node may refuse a proposal from an older epoch than one it has seen.

Two rounds of voting, and why they overlap

N1, epoch 1N2N3N4N5propose (epoch 1)yesdecided, 5 of 5
The leader of epoch 1 proposes a value

N1 is leader for epoch 1, and no other node has heard of a later epoch. It needs votes from a majority before the value counts as decided.

Votes: N1, N2, N3, N4 and N5. 5 of 5, and a majority is 3: decided.

So there are two rounds of voting, one to choose a leader and one on the leader’s proposals, and the quorums of the two must overlap. That overlap is what lets a node in the second quorum know whether a newer leader exists. How much a cluster can lose follows from the quorum size:

How many nodes a consensus cluster can lose

N1N2N3××
3 of 5 up: still a majority

5 nodes need 3 for a majority, so the cluster tolerates 2 failures. With 2 down, the 3 that remain can still elect a leader and commit.

What consensus costs

The voting is a kind of synchronous replication, and many databases are configured for asynchronous replication precisely to avoid that cost. A strict majority must be up: tolerating one failure takes three nodes, two takes five. Most algorithms assume a fixed set of voters, and dynamic membership extensions are much less well understood.

And what timeouts cost it

Consensus relies on timeouts to detect failed nodes. In an environment with highly variable network delays, especially geographically distributed ones, nodes often falsely believe the leader has failed. That is not unsafe, but frequent elections leave the system spending more time choosing a leader than doing useful work. Raft has been shown to have unpleasant edge cases when one network link is consistently unreliable, bouncing leadership between two nodes.

Consensus as a service § Membership and Coordination Services

A small store with strong guarantees

Projects like ZooKeeper and etcd are often described as distributed key-value stores, but you would not use them as a general database. They hold small amounts of data that fit in memory, replicated to all nodes with a fault-tolerant total order broadcast algorithm. Applications rarely use them directly; they come in through HBase, Hadoop YARN, OpenStack Nova and Kafka, among others.

What ZooKeeper offers

Linearizable atomic operations, so a lock can be acquired with compare-and-set, usually as a lease that expires if the client fails. Total ordering of operations, with a monotonically increasing transaction ID that serves as a fencing token. Failure detection through heartbeats on long-lived sessions, with ephemeral nodes that disappear when a session times out. Change notifications, so a client learns that another joined or failed without polling.

What applications use it for

Allocating work: choosing a leader among several instances of a process, and assigning partitions to nodes as they join and leave. Service discovery: finding the IP address to reach a service, though that does not strictly need consensus. Membership services: deciding which nodes are currently alive. A fixed three or five ZooKeeper nodes can coordinate thousands of application nodes, outsourcing the consensus work.

Problems that turn out to be equivalent to consensus

problemwhat has to be agreed
Linearizable compare-and-setwhether to set the value, given whether it currently equals the expected one
Atomic transaction commitwhether to commit or abort a distributed transaction
Total order broadcastthe order in which to deliver messages
Locks and leaseswhich of several clients racing for a lock gets it
Membership and coordinationwhich nodes are alive and which are dead, given a failure detector
Uniqueness constraintwhich of several conflicting writes to allow and which to fail

All of them are easy on a single node, or with a single leader making every decision. The difficulty is what happens when that leader fails: wait for it, fix it by hand, or use a consensus algorithm to choose a new one automatically.

Recall check 12 questions

Did it stick?

One attempt per question; the explanation appears either way.

1. What does linearizability promise?

2. How is linearizability different from serializability?

3. In figure 9-1, why is Bob’s result a violation?

4. In the grid, which situations does a leaderless quorum with w + r > n get wrong?

5. What does the CAP theorem actually say, in the form the book recommends?

6. Why do many systems choose not to be linearizable even without partitions?

7. What is the relationship between causal consistency and linearizability?

8. Why do odd/even counters per node fail to order events causally?

9. Why are Lamport timestamps not enough to enforce a unique username?

10. Which properties define total order broadcast?

11. In two-phase commit, why is a participant that voted yes stuck if the coordinator crashes?

12. How do consensus algorithms like Raft and Paxos avoid split brain?

Answered 0 of 12 · 0 correct

Vocabulary Click to flip

The terms this chapter installs


Chapter 9 in one breath. Linearizability makes a replicated database behave like a single copy of the data with atomic operations: once a read has seen a new value, every later read sees it too. It is appealing because it is easy to understand, and it is slow, especially with large network delays, and unavailable on the wrong side of a partition. Of the 5 situations in the grid, only consensus gets through all of them correctly, and it pays in round trips. Causality is a weaker, partial order that preserves cause and effect without the cost, and Lamport timestamps give a total order consistent with it. But some things, such as a unique username, need to know when the order is final, and that takes total order broadcast, which is equivalent to consensus. So are linearizable compare-and-set, atomic commit, locks and leases, membership, and uniqueness constraints.

Two-phase commit is atomic and blocks when its coordinator fails. Fault-tolerant consensus algorithms such as Raft and Paxos decide by majority vote, with epochs to keep stale leaders out, and tolerate the failure of a minority of nodes. Not every system needs it: leaderless and multi-leader databases usually do without, accepting conflicts and divergence instead. When you do need it, a coordination service such as ZooKeeper or etcd is the usual way to get it, rather than writing your own.

← all lab notes