Consistency and Consensus
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.
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.
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
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.
B reads 1 and finishes. Then C starts a read and gets 0, though A’s write is still going on, so each read on its own would be fine. Together they are not: there would have to be a moment when x became 1 and then another when it became 0 again, and nobody wrote 0.
Not linearizable. No order of instants inside the bars works. Take away C’s read → 0, drawn in red, and one does.
B and C both try cas(x, 1 → something). Only one of them can find x still at 1, and the one that loses must report failure. D’s read afterwards tells you which order the register chose.
Linearizable. The checker found an instant inside every bar, marked where each line meets the register, in this order: A write 1, B cas 1→3: ok, C cas 1→4: fail, D read → 3.
B and C both run cas(x, 0 → something) and both are told it worked. A single register cannot do that: whichever ran second would have found x already changed. This is the situation a uniqueness constraint has to rule out.
Not linearizable. No order of instants inside the bars works. Take away B’s cas 0→1: ok, drawn in red, and one does.
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.
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 Writes go to the leader, node 1, which acknowledges at once and passes the change to the followers asynchronously. Reads go to whichever replica is nearest the client. Fast and highly available, and a follower can be behind, so a read can return a value that an acknowledged write has already replaced.
Read after a write under Single leader, read any replicaThe referee records the final score on node 1. Alice reads it from her nearby replica and shouts it across the room. Bob, hearing her, refreshes his page.
Not linearizable Bob reads “playing”, though Alice had already read “final” and finished before Bob started. Once any operation has seen the new value, every operation that starts later must see it too.
How the column works The same asynchronous replication, but every read also goes to the leader, so there is only one copy to ask. That can be linearizable. It stops being so when the leader acknowledges a write, crashes before passing it on, and a follower takes over without it; or when a node wrongly believes it is still the leader. A client that cannot reach the leader gets no answer at all.
Read after a write under Single leader, read the leaderThe referee records the final score on node 1. Alice reads it from her nearby replica and shouts it across the room. Bob, hearing her, refreshes his page.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: Referee write “final”; Alice read → “final”; Bob read → “final”. The dots mark those instants.
How the column works Each node accepts writes from its own clients and replicates them to the others asynchronously, with conflicts settled later by last write wins. A compare-and-set is checked against the local copy only. Excellent for availability and write latency, and never linearizable: two nodes can accept conflicting writes at the same time.
Read after a write under Multi-leaderThe referee records the final score on node 1. Alice reads it from her nearby replica and shouts it across the room. Bob, hearing her, refreshes his page.
Not linearizable Bob reads “playing”, though Alice had already read “final” and finished before Bob started. Once any operation has seen the new value, every operation that starts later must see it too.
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.
Read after a write under Leaderless quorumThe referee records the final score on node 1. Alice reads it from her nearby replica and shouts it across the room. Bob, hearing her, refreshes his page.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: Referee write “final”; Alice read → “final”; Bob read → “final”. The dots mark those instants.
How the column works The same quorums, plus one rule: if any reply in the reader’s quorum is stale, the reader writes the newest value back to a quorum before returning it. Once a read has returned a value, a majority holds it, so no later read can miss it. Reads and writes become linearizable, at the cost of an extra round trip. Compare-and-set still cannot be built this way; that needs consensus.
Read after a write under Quorum + synchronous read repairThe referee records the final score on node 1. Alice reads it from her nearby replica and shouts it across the room. Bob, hearing her, refreshes his page.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: Referee write “final”; Alice read → “final”; Bob read → “final”. The dots mark those instants.
How the column works Every operation, reads included, is appended to a replicated log by the leader and applied only once a majority of nodes has acknowledged it, in log order, so all nodes apply the same operations in the same order. Linearizable, compare-and-set included. The price is a round trip to a majority on every operation, and the minority side of a partition cannot answer at all.
Read after a write under ConsensusThe referee records the final score on node 1. Alice reads it from her nearby replica and shouts it across the room. Bob, hearing her, refreshes his page.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: Referee write “final”; Alice read → “final”; Bob read → “final”. The dots mark those instants.
How the column works Writes go to the leader, node 1, which acknowledges at once and passes the change to the followers asynchronously. Reads go to whichever replica is nearest the client. Fast and highly available, and a follower can be behind, so a read can return a value that an acknowledged write has already replaced.
Reads during a write under Single leader, read any replicaA 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.
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.
How the column works The same asynchronous replication, but every read also goes to the leader, so there is only one copy to ask. That can be linearizable. It stops being so when the leader acknowledges a write, crashes before passing it on, and a follower takes over without it; or when a node wrongly believes it is still the leader. A client that cannot reach the leader gets no answer at all.
Reads during a write under Single leader, read the leaderA 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.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: Writer write 1; Reader A read → 1; Reader B read → 1. The dots mark those instants.
How the column works Each node accepts writes from its own clients and replicates them to the others asynchronously, with conflicts settled later by last write wins. A compare-and-set is checked against the local copy only. Excellent for availability and write latency, and never linearizable: two nodes can accept conflicting writes at the same time.
Reads during a write under Multi-leaderA 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.
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.
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.
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.
How the column works The same quorums, plus one rule: if any reply in the reader’s quorum is stale, the reader writes the newest value back to a quorum before returning it. Once a read has returned a value, a majority holds it, so no later read can miss it. Reads and writes become linearizable, at the cost of an extra round trip. Compare-and-set still cannot be built this way; that needs consensus.
Reads during a write under Quorum + synchronous read repairA 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.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: Writer write 1; Reader A read → 1; Reader B read → 1. The dots mark those instants.
How the column works Every operation, reads included, is appended to a replicated log by the leader and applied only once a majority of nodes has acknowledged it, in log order, so all nodes apply the same operations in the same order. Linearizable, compare-and-set included. The price is a round trip to a majority on every operation, and the minority side of a partition cannot answer at all.
Reads during a write under ConsensusA 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.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: Writer write 1; Reader A read → 1; Reader B read → 1. The dots mark those instants.
How the column works Writes go to the leader, node 1, which acknowledges at once and passes the change to the followers asynchronously. Reads go to whichever replica is nearest the client. Fast and highly available, and a follower can be behind, so a read can return a value that an acknowledged write has already replaced.
Claim a username under Single leader, read any replicaTwo users register the same username at almost the same moment, each with compare-and-set from free to their own name, through different nodes.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: User 1 cas “free”→“user 1”: ok; User 2 cas “free”→“user 2”: fail. The dots mark those instants.
How the column works The same asynchronous replication, but every read also goes to the leader, so there is only one copy to ask. That can be linearizable. It stops being so when the leader acknowledges a write, crashes before passing it on, and a follower takes over without it; or when a node wrongly believes it is still the leader. A client that cannot reach the leader gets no answer at all.
Claim a username under Single leader, read the leaderTwo users register the same username at almost the same moment, each with compare-and-set from free to their own name, through different nodes.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: User 1 cas “free”→“user 1”: ok; User 2 cas “free”→“user 2”: fail. The dots mark those instants.
How the column works Each node accepts writes from its own clients and replicates them to the others asynchronously, with conflicts settled later by last write wins. A compare-and-set is checked against the local copy only. Excellent for availability and write latency, and never linearizable: two nodes can accept conflicting writes at the same time.
Claim a username under Multi-leaderTwo users register the same username at almost the same moment, each with compare-and-set from free to their own name, through different nodes.
Not linearizable Both compare-and-sets found “free” and both report success, so User 1 and User 2 each believe they own the name. A single register would have let exactly one win.
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.
Claim a username under Leaderless quorumTwo users register the same username at almost the same moment, each with compare-and-set from free to their own name, through different nodes.
Not linearizable Both compare-and-sets found “free” and both report success, so User 1 and User 2 each believe they own the name. A single register would have let exactly one win.
How the column works The same quorums, plus one rule: if any reply in the reader’s quorum is stale, the reader writes the newest value back to a quorum before returning it. Once a read has returned a value, a majority holds it, so no later read can miss it. Reads and writes become linearizable, at the cost of an extra round trip. Compare-and-set still cannot be built this way; that needs consensus.
Claim a username under Quorum + synchronous read repairTwo users register the same username at almost the same moment, each with compare-and-set from free to their own name, through different nodes.
Not linearizable Both compare-and-sets found “free” and both report success, so User 1 and User 2 each believe they own the name. A single register would have let exactly one win.
How the column works Every operation, reads included, is appended to a replicated log by the leader and applied only once a majority of nodes has acknowledged it, in log order, so all nodes apply the same operations in the same order. Linearizable, compare-and-set included. The price is a round trip to a majority on every operation, and the minority side of a partition cannot answer at all.
Claim a username under ConsensusTwo users register the same username at almost the same moment, each with compare-and-set from free to their own name, through different nodes.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: User 1 cas “free”→“user 1”: ok; User 2 cas “free”→“user 2”: fail. The dots mark those instants.
How the column works Writes go to the leader, node 1, which acknowledges at once and passes the change to the followers asynchronously. Reads go to whichever replica is nearest the client. Fast and highly available, and a follower can be behind, so a read can return a value that an acknowledged write has already replaced.
Network partition under Single leader, read any replicaNode 3 and its client are cut off from the other two nodes. A write happens on the other side; then the client reads.
Not linearizable Client reads 0, though Writer had already written 1 and finished before Client started. Once any operation has seen the new value, every operation that starts later must see it too.
How the column works The same asynchronous replication, but every read also goes to the leader, so there is only one copy to ask. That can be linearizable. It stops being so when the leader acknowledges a write, crashes before passing it on, and a follower takes over without it; or when a node wrongly believes it is still the leader. A client that cannot reach the leader gets no answer at all.
Network partition under Single leader, read the leaderNode 3 and its client are cut off from the other two nodes. A write happens on the other side; then the client reads.
Unavailable Nothing wrong is returned, but Client gets no answer at all. The partition cuts it off from a node that could answer it consistently. Consistent, and not available.
How the column works Each node accepts writes from its own clients and replicates them to the others asynchronously, with conflicts settled later by last write wins. A compare-and-set is checked against the local copy only. Excellent for availability and write latency, and never linearizable: two nodes can accept conflicting writes at the same time.
Network partition under Multi-leaderNode 3 and its client are cut off from the other two nodes. A write happens on the other side; then the client reads.
Not linearizable Client reads 0, though Writer had already written 1 and finished before Client started. Once any operation has seen the new value, every operation that starts later must see it too.
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.
Network partition under Leaderless quorumNode 3 and its client are cut off from the other two nodes. A write happens on the other side; then the client reads.
Unavailable Nothing wrong is returned, but Client gets no answer at all. The partition cuts it off from a node that could answer it consistently. Consistent, and not available.
How the column works The same quorums, plus one rule: if any reply in the reader’s quorum is stale, the reader writes the newest value back to a quorum before returning it. Once a read has returned a value, a majority holds it, so no later read can miss it. Reads and writes become linearizable, at the cost of an extra round trip. Compare-and-set still cannot be built this way; that needs consensus.
Network partition under Quorum + synchronous read repairNode 3 and its client are cut off from the other two nodes. A write happens on the other side; then the client reads.
Unavailable Nothing wrong is returned, but Client gets no answer at all. The partition cuts it off from a node that could answer it consistently. Consistent, and not available.
How the column works Every operation, reads included, is appended to a replicated log by the leader and applied only once a majority of nodes has acknowledged it, in log order, so all nodes apply the same operations in the same order. Linearizable, compare-and-set included. The price is a round trip to a majority on every operation, and the minority side of a partition cannot answer at all.
Network partition under ConsensusNode 3 and its client are cut off from the other two nodes. A write happens on the other side; then the client reads.
Unavailable Nothing wrong is returned, but Client gets no answer at all. The partition cuts it off from a node that could answer it consistently. Consistent, and not available.
How the column works Writes go to the leader, node 1, which acknowledges at once and passes the change to the followers asynchronously. Reads go to whichever replica is nearest the client. Fast and highly available, and a follower can be behind, so a read can return a value that an acknowledged write has already replaced.
Leader fails over under Single leader, read any replicaNode 1 acknowledges a write and then crashes. After a timeout, node 2 takes over as leader, and a client reads.
Not linearizable Writer’s write of 1 was acknowledged, and the node that took it crashed before passing it on. No surviving node has it, so Reader reads 0: an acknowledged write is gone.
How the column works The same asynchronous replication, but every read also goes to the leader, so there is only one copy to ask. That can be linearizable. It stops being so when the leader acknowledges a write, crashes before passing it on, and a follower takes over without it; or when a node wrongly believes it is still the leader. A client that cannot reach the leader gets no answer at all.
Leader fails over under Single leader, read the leaderNode 1 acknowledges a write and then crashes. After a timeout, node 2 takes over as leader, and a client reads.
Not linearizable Writer’s write of 1 was acknowledged, and the node that took it crashed before passing it on. No surviving node has it, so Reader reads 0: an acknowledged write is gone.
How the column works Each node accepts writes from its own clients and replicates them to the others asynchronously, with conflicts settled later by last write wins. A compare-and-set is checked against the local copy only. Excellent for availability and write latency, and never linearizable: two nodes can accept conflicting writes at the same time.
Leader fails over under Multi-leaderNode 1 acknowledges a write and then crashes. After a timeout, node 2 takes over as leader, and a client reads.
Not linearizable Writer’s write of 1 was acknowledged, and the node that took it crashed before passing it on. No surviving node has it, so Reader reads 0: an acknowledged write is gone.
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.
Leader fails over under Leaderless quorumNode 1 acknowledges a write and then crashes. After a timeout, node 2 takes over as leader, and a client reads.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: Writer write 1; Reader read → 1. The dots mark those instants.
How the column works The same quorums, plus one rule: if any reply in the reader’s quorum is stale, the reader writes the newest value back to a quorum before returning it. Once a read has returned a value, a majority holds it, so no later read can miss it. Reads and writes become linearizable, at the cost of an extra round trip. Compare-and-set still cannot be built this way; that needs consensus.
Leader fails over under Quorum + synchronous read repairNode 1 acknowledges a write and then crashes. After a timeout, node 2 takes over as leader, and a client reads.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: Writer write 1; Reader read → 1. The dots mark those instants.
How the column works Every operation, reads included, is appended to a replicated log by the leader and applied only once a majority of nodes has acknowledged it, in log order, so all nodes apply the same operations in the same order. Linearizable, compare-and-set included. The price is a round trip to a majority on every operation, and the minority side of a partition cannot answer at all.
Leader fails over under ConsensusNode 1 acknowledges a write and then crashes. After a timeout, node 2 takes over as leader, and a client reads.
Linearizable Every operation can be placed at one instant inside its own bar, in this order: Writer write 1; Reader read → 1. The dots mark those instants.
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.
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.
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
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.
Physical timestamps with enough resolution are unique enough, and they would order events correctly if clocks were perfectly in sync. They are not, as chapter 8 showed, so a message can arrive before it was sent.
3 of the 17 causal pairs come out backwards. For example, node B’s receive, numbered t 1.6, happened after node A’s send, numbered t 3.6, yet its number is not larger.
A node increments its counter for every event. When it receives a message carrying a larger counter, it jumps to that value first. Ties are broken by node ID. Every causal dependency gets a larger timestamp, with no clocks and nothing shared.
All 17 causal pairs come out in order.
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.
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
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.
Each node appends the claim to a log that delivers every message to every node in the same order. Each node then reads the log, and the first claim for the name wins, wherever it was made.
Node A says the name belongs to user 1, node B says user 1: they agree.
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.
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
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.
A conflict, a constraint violation or a full disk: any participant may still vote no in phase 1. One no is enough for the coordinator to abort the transaction everywhere.
Outcome: database 1 aborts at 5.3, database 2 aborts at 5.6. Both end the same way.
Database 2 voted yes, so it may not abort on its own: database 1 may already have committed. It may not commit on its own either: the decision might have been abort. It is stuck in doubt, still holding its row locks, until the coordinator recovers and reads its decision back from its log.
Outcome: database 1 commits at 5.3, database 2 commits at 12.5. Still atomic, but database 2 spent 10.2 time units in doubt, and anything that wanted its locked rows waited with it.
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.
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 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.
While N1 was paused, N2 called an election for epoch 2 and won the votes of a majority. N1 does not know. When it proposes, every node that voted in epoch 2 refuses. A quorum for any decision must overlap the quorum that elected the new leader, so at least one node in it has heard of epoch 2.
Votes: N1 and N5. 2 of 5, and a majority is 3: not decided, and N1 learns it is no longer the leader.
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
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.
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
| problem | what has to be agreed |
|---|---|
| Linearizable compare-and-set | whether to set the value, given whether it currently equals the expected one |
| Atomic transaction commit | whether to commit or abort a distributed transaction |
| Total order broadcast | the order in which to deliver messages |
| Locks and leases | which of several clients racing for a lock gets it |
| Membership and coordination | which nodes are alive and which are dead, given a failure detector |
| Uniqueness constraint | which 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.
Did it stick?
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
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.