Store one number on three machines, so that losing a machine doesn’t lose the number. Two clients change it at the same moment, one replica is slow, and a third client reads. What should that read return?
Most of a distributed systems course is spent answering this question under different assumptions. This post is a compressed version of my notes from one such course. It walks through the ideas in the order in which each one fixes a problem left by the previous one.
The same ideas keep showing up in Cassandra, etcd, Kafka, Spanner and almost every other system that stores data on more than one machine.
Why put data on several machines at all?
There are two reasons, and they lead to two different techniques.
The first is that machines die. A disk fails or a rack loses power, and data stored in one place is gone. The fix is replication: keep several copies and hope they don’t all fail together.
The second is that the data stops fitting on one machine. The fix is sharding: split the keys into groups and give each group to a different set of servers.
Real systems stack these. Each shard is a small replicated group, and a router in front knows which shard owns which key. On top of that sit transactions, for when one change has to touch keys in several shards.
Most of the hard questions are about a single replicated value, so that’s where I’ll start.
What if any replica can answer on its own?
The simplest design gives you the best availability. A client writes to whichever replica it can reach, that replica answers “ok” immediately, and it tells the others later. As long as one replica is alive, the system accepts reads and writes.
“Tells the others later” needs a mechanism. Having every node talk to every other node costs N² connections. Gossip is cheaper: every node periodically picks a random peer and sends it what it knows.
Push gossip with eight nodes, in the ideal case where every message reaches a node that hasn’t heard yet.
Notice that the number of informed nodes doubles each round. That is why a cluster of N nodes needs on the order of log N rounds, a result that goes back to the epidemic algorithms paper from Xerox PARC in 1987. With perfect doubling a thousand nodes would take ten rounds. With random peers some messages land on nodes that already know, so the real number is somewhat higher, and it still grows with the logarithm.
The price is in what a client can observe. You write a value, read from another replica a millisecond later, and get the old one. If the replica that took your write dies before it gossips, the write is lost even though you were told “ok”. This guarantee is called eventual consistency: the replicas agree at some point, and nothing is promised before that.
How do you read your own write without waiting for every replica?
Waiting for all N replicas on every write would fix stale reads, but then one dead replica blocks all writes and the slowest replica sets your latency.
A quorum is the middle ground. Send a write to W replicas and a read to R replicas, and choose the numbers so that W + R > N.
N = 5 with W = R = 3. Any three replicas you write to and any three you read from have at least one in common.
Because the two sets overlap, every read reaches at least one replica that saw the latest finished write. Attach a version number to each value, take the highest one among the answers, and you get the newest value.
The usual choice is a majority for both. With 3 replicas that is 2, with 5 it is 3. A cluster of N replicas keeps working while fewer than half of them are down. You can also skew it: W = 4 and R = 2 on five replicas makes reads cheaper and writes more fragile.
Why can a quorum read still go back in time?
Overlap is enough for writes that have finished. A write that is still in progress breaks it.
Say a writer sends the value 1. It reaches replica R3 quickly and is delayed on the way to R1 and R2. Meanwhile another client reads twice.
The same client reads 1 and then 0, while the write of 1 is still in flight.
The first read happens to include R3 and returns 1. The second read asks the two replicas that don’t have the write yet and returns 0. From the client’s side the value went backwards. No ordering of these three operations explains what it saw, so the register is not linearizable, which is the property of behaving like a single copy.
The fix comes from the ABD algorithm, named after Attiya, Bar-Noy and Dolev and published in “Sharing Memory Robustly in Message-Passing Systems”. A read becomes two steps. First it asks a quorum and picks the value with the highest version. Then it writes that value back to a quorum, and only after that returns it.
With the write-back, the first read pushes the value 1 to a majority before it answers. The second read overlaps with that majority and can no longer see only old copies. In effect the reader finishes the writer’s job for it.
One more detail is needed when there are several writers. Each writer first asks a quorum for the highest version, adds one, and appends its own id to break ties. Versions are then pairs like (7, node-B), compared by number first and id second. Clocks are deliberately not used for this, because the clocks of two machines never agree closely enough.
ABD gives you a linearizable read and write over an unreliable network, and it works as long as a majority of replicas is up. It’s a good first algorithm to learn, because it’s small and it shows what quorums alone leave unsolved.
What breaks when an operation depends on the current value?
Plain reads and writes are rarely all you need. Locks, counters and unique usernames need an operation like compare-and-swap: set the value to y only if it is currently x.
ABD can’t do this. Each replica decides on its own, and replicas can receive the same operations in different orders. Take three clients that all send a CAS from x at once:
| Replica | Order of arrival | Result |
|---|---|---|
| R1 | CAS(x, y2), CAS(x, y3), CAS(x, y1) | y2 |
| R2 | CAS(x, y3), CAS(x, y1), CAS(x, y2) | y3 |
| R3 | CAS(x, y1), CAS(x, y2), CAS(x, y3) | y1 |
Every replica applied the first CAS it saw and rejected the other two. All three are healthy, no message was lost, and they now hold three different values.
The problem is the order. If all replicas processed the same operations in the same sequence, any deterministic operation would produce the same result everywhere.
One agreed order turns three conflicting requests into one winner and two clean failures.
That is the replicated state machine approach, described by Fred Schneider in a 1990 tutorial. Put every operation into a single log, make sure every replica has the same log, and let each replica apply it in order. The piece that builds the log is called total order broadcast. ZooKeeper, etcd and Kafka’s controller all work this way.
How do machines agree on one thing?
Agreeing on the next entry of the log is the consensus problem: several machines each propose a value, and all of them must end up with the same one, which has to be one of the proposed values.
Consensus and total order broadcast turn out to be the same problem. A log is a sequence of consensus decisions, one per slot. In the other direction, the first proposal in an ordered log is a decision.
There is a famous limit here. The FLP result by Fischer, Lynch and Paterson shows that no deterministic algorithm can guarantee a decision if the network has no bound on message delay and even one machine may crash. The reason is that a crashed machine and a very slow one look identical from outside.
Every practical algorithm gives something up:
| What you give up | What you get |
|---|---|
| Guaranteed termination | Paxos, Raft: never a wrong answer, but can stall while the network misbehaves |
| Determinism | Randomized algorithms such as Ben-Or |
| Unbounded delays | Timeout-based algorithms for networks with a known delay limit |
Almost all production systems take the first row. They are always safe, and they make progress whenever the network is calm for long enough.
Paxos in two phases
Paxos, from Leslie Lamport’s Paxos Made Simple, decides a single value. A proposer talks to a set of acceptors, and a majority of acceptors has to agree.
A run without failures. Every proposal carries a unique number, here 5.
In phase one the proposer picks a number higher than any it has used and asks the acceptors to promise that they will ignore anything with a lower number. Each acceptor that agrees also reports the last value it accepted, if there is one.
In phase two the proposer sends a value to be accepted. There is one rule that carries the whole algorithm: if any acceptor reported an earlier accepted value, the proposer must send that value and drop its own. If nobody reported anything, it is free to send what it wanted.
This rule is why a decided value can never change. Once a majority has accepted a value, any later proposer will hear about it from at least one acceptor in its own majority, and will propose it again.
The weak spot is progress. Two proposers can keep outbidding each other with higher numbers, each one invalidating the other’s phase two. That loop is the stall FLP says must exist somewhere.
One leader, one log
Running both phases for every log entry is wasteful, and competing proposers get in each other’s way. Multi-Paxos fixes both with a leader.
One node sends a single prepare that covers all future log slots. After that, each new command costs one round trip from the leader to a majority. The proposal number becomes the leader’s term of office. When the leader stops responding, another node starts a higher term and takes over.
The leader only makes things faster, and correctness doesn’t depend on there being exactly one. If two nodes both believe they lead, both still go through the acceptors, and the promise rule lets only one of them succeed.
Raft is the same design with the open details written down: how the leader is elected, how a lagging follower catches up, how the cluster changes membership. That is why most new systems implement Raft.
How do you split data across machines?
Replication copies the same data. Sharding spreads different data, and the first thing it needs is a rule for which server owns which key.
The obvious rule, hash(key) mod N, has a bad property. Changing N from 10 to 11 moves almost every key to a different server.
Consistent hashing, introduced by Karger and co-authors in 1997, avoids that. Hash both the keys and the servers into the same range and bend the range into a ring. A key belongs to the first server found clockwise from its position.
Adding or removing a server changes ownership of one arc and leaves the rest of the ring alone.
Each server usually gets many positions on the ring instead of one. These virtual nodes even out the load, and when a server dies its keys spread over many neighbours instead of landing on a single one.
What Dynamo built on the ring
Amazon’s Dynamo paper from 2007 is the best known design that picks availability over consistency, and Cassandra and Riak grew out of it. It combines the ring with the first two ideas of this post and adds three repair mechanisms.
Each key is stored on the next N servers along the ring, with quorum reads and writes. The paper’s common setting is N = 3, R = 2, W = 2. If one of those servers is down, the write goes to the next healthy server instead, with a note to hand the data back later. This keeps writes available and gives up the overlap guarantee.
That means two clients can update the same key through different servers without seeing each other. Dynamo detects this with vector clocks: each version carries a counter per server that coordinated a write. If one version’s counters are all at least as high as another’s, it is newer. If neither dominates, the writes were concurrent, and Dynamo returns both versions for the application to merge.
In practice conflicts were rare. The paper reports that over 24 hours of shopping cart traffic, 99.94% of requests saw exactly one version.
Two background jobs pull replicas back together. Read repair fixes stale replicas noticed during a read. Merkle trees let two replicas compare a whole key range by exchanging a few hashes and descending only into the parts that differ.
How do you change several keys at once?
Everything so far was about one key. Moving money between two accounts changes two keys, and they may live in different shards. Either both changes happen or neither does.
Two-phase commit
A shard can’t decide alone, because another shard might refuse. Two-phase commit adds a coordinator that asks first and decides second.
Two-phase commit across two shards.
In the prepare phase each shard locks the rows involved and writes the pending change to its log. Answering “prepared” is a promise that it can commit no matter what happens next, including its own restart. If every shard is prepared, the coordinator records the decision and sends commit. If any shard refuses, it sends abort.
The known weakness is the window after “prepared”. A shard that has promised can’t release its locks until it hears the decision, so a coordinator that dies at the wrong moment leaves rows locked. This is why real systems store the coordinator’s decision in a replicated log, which brings consensus back in. Spanner runs two-phase commit between groups that each use Paxos internally.
Versions instead of locks
Two-phase commit makes writes atomic. Reads still have a problem: a reader can visit shard A before the commit and shard B after it, and see half a transaction. Making reads take locks would fix that, but reads usually outnumber writes many times over, and they would block each other.
Multi-version concurrency control takes a different route. A write never overwrites a row. It adds a new version stamped with a commit timestamp. A reader picks a timestamp when it starts and sees, for every key, the latest version at or before that timestamp. Readers and writers never wait for each other.
Across shards this only works if everyone draws timestamps from the same increasing sequence. Wall clocks aren’t safe for that, so the timestamps come from a small service, often called a timestamp oracle, whose counter is kept in a consensus log. To avoid a consensus round per transaction, the oracle reserves a range of numbers in one go and hands them out from memory. Google’s Percolator describes this design, and TiDB uses the same one.
The general rule this illustrates is to send as little as possible through consensus. Here it’s a range of integers, and the data itself never passes through it.
The whole picture in one table
| Idea | What it solves | What it costs | Where you meet it |
|---|---|---|---|
| Async replication and gossip | Stay available while replicas are down | Stale reads, writes can be lost | Cassandra membership, Dynamo |
| Quorums, W + R > N | Fresh reads without waiting for every replica | A majority must be reachable | Cassandra, Riak |
| Read with write-back (ABD) | Reads that never go backwards | Every read is also a write | Linearizable key-value registers |
| One ordered log | Conditional operations like compare-and-swap | Needs consensus underneath | ZooKeeper, etcd, Kafka |
| Consensus (Paxos, Raft) | Agreement on each log entry | Can stall during network trouble | Chubby, etcd, Consul |
| Consistent hashing | Adding servers without moving every key | Needs virtual nodes for even load | Dynamo, Cassandra |
| Vector clocks and repair | Detecting concurrent writes | The application merges conflicts | Dynamo, Riak |
| Two-phase commit | Atomic changes across shards | Locks held until the decision arrives | Spanner, distributed SQL databases |
| MVCC with a timestamp oracle | Reads that don’t block writes | Old versions need cleanup | Percolator, TiDB |
Reading a new system’s design document gets much easier once you can place each of its parts in this table. The combination differs from system to system, and the parts are usually these.
Limitations
This is an overview, so every section leaves things out. I skipped Byzantine failures, where machines lie instead of crashing. I also skipped isolation levels, which decide what concurrent transactions may see of each other, and CRDTs, which are another way to merge concurrent writes.
The Paxos section describes the single-value algorithm and only sketches Multi-Paxos. Anyone implementing it should read the Raft paper in full, including the parts about membership changes and log compaction.
References
- Demers et al., Epidemic Algorithms for Replicated Database Maintenance, 1987
- Attiya, Bar-Noy, Dolev, Sharing Memory Robustly in Message-Passing Systems, 1995
- Schneider, Implementing Fault-Tolerant Services Using the State Machine Approach, 1990
- Fischer, Lynch, Paterson, Impossibility of Distributed Consensus with One Faulty Process, 1985
- Lamport, Paxos Made Simple, 2001
- Ongaro, Ousterhout, In Search of an Understandable Consensus Algorithm, 2014
- Karger et al., Consistent Hashing and Random Trees, 1997
- DeCandia et al., Dynamo: Amazon’s Highly Available Key-value Store, 2007
- Peng, Dabek, Large-scale Incremental Processing Using Distributed Transactions and Notifications, 2010
- Kleppmann, Designing Data-Intensive Applications, 2017