Distributed Systems II: Scale
What does each guarantee cost when data lives on many machines, and one of them is always failing?
The part opens with the Job run as MapReduce on sixteen Pebbles: Pebble 4 crashes at 0.4 s, three finished maps are redone, and the same top twenty words come out in 0.60 s against 2.65 s on one machine. It then prices the guarantees one at a time. Replicas lag, so 67% of immediate reads miss your own post; quorums with R + W > N never do, and sloppier ones are stale for a measured while. CAP is stated precisely on a 40/60 partition: refuse 40% of requests, or answer all of them and merge conflicts later. CRDTs make the merge a join that cannot conflict, a hash ring moves 8.6% of keys where modulo hashing moves 91%, and Chord finds a key in about half of log n hops. Two-phase commit blocks for 31 s behind a crashed coordinator, and Spanner waits out its clock uncertainty instead. Then the part turns from correctness to time: one slow server in a hundred makes 63.9% of requests slow at a fan-out of 100, hedging and two choices repair it, and a retry storm keeps a service down after its spike has passed. It ends by asking how little coordination a problem needs: the CALM theorem, and causal consistency as the most an always-available system can promise.
What you need. Elementary probability (independent events, the exponential distribution), hashing, and partial orders for the chapter on CRDTs.
- Mathematics, ideas and history
- replication and quorums, consistency models, CAP, CRDTs, consistent hashing, Chord, 2PC and Spanner, MapReduce, the tail at scale
- What we build or compute
- the Job on a 16-node cluster that loses a node
What you will be able to do
Degree
- Decide from N, R and W whether a read can miss an acknowledged write, and explain why.
- State the CAP theorem precisely and say what a CP and an AP system each do during a partition.
- Place keys on a consistent-hash ring and count how many move when a node joins.
Graduate
- Prove that replicas whose merge is commutative, associative and idempotent converge, and build a G-counter and an OR-set.
- Show where two-phase commit blocks, and compute Spanner's commit wait from the clock uncertainty.
- Derive the slow share 1 - (1 - p)^n of a fan-out and the effect of a hedged request.
Research
- State the CALM theorem and use invariant confluence to decide which invariants of an application need coordination.
- Explain why causal consistency is the strongest always-available convergent model, and what is open about its metadata and about metastable failures.
Industry
- Choose a consistency level as a product decision, naming the anomalies a user may see.
- Watch the 99th percentile, hedge reads that are safe to repeat, and give every request a deadline, backoff with jitter and a retry budget.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 21 min · Graduate 42 min · Research 46 min · Industry 32 min.
- 0Sixteen Pebbles, one crashDegree1 min
- 1The datacenter, and replicationDegree4 min
- 2Quorums and consistencyDegree5 min
- 3CRDTsGraduate5 min
- 4PartitioningDegree4 min
- 5Transactions across machinesGraduate5 min
- 6MapReduceDegree4 min
- 7The tail at scaleIndustry5 min
- 8Failure at scaleIndustry6 min
- 9Frontier: how little coordination?Research4 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
Sixteen Pebbles, one crashDegree1 min
The thirty novels, cut into forty-eight pieces and spread across sixteen Pebbles. Each Pebble counts the words in its pieces, the counts are shuffled so that every word goes to one place, and sixteen merges produce the answer: MapReduce, the way Google counted the web in 2004. Here is every task, on every machine, over time: maps in blue, then reduces in purple. At four tenths of a second, Pebble four dies. The task it was running is lost, and so are the outputs of the maps it had already finished, because they lived on its own disk. The master hands all of that work to the others. Near the end, idle machines run backup copies of the last slow tasks, and whichever copy finishes first wins. Six tenths of a second, against two point seven on one Pebble, with a machine lost along the way, and the twenty words and their counts identical to the one-machine Job's.
1The datacenter, and replicationDegree4 min
Luiz Barroso and Urs Hölzle called the modern datacenter a single computer: tens of thousands of servers, one program. Its distances are what shape everything in this part. Stretch time so that one processor cycle takes a second. Then a cache hit is three seconds and main memory five minutes. A round trip to another machine in the same building is seventeen days; reading a random spot on a solid-state disk, three and a half; a spinning disk's seek, a year. A round trip from California to Europe takes fifteen years, and a TCP retransmission timeout a century. So every protocol here is judged in round trips, and every clever idea is a way to make fewer of them.
Data is copied for three reasons: to survive failures, to serve more reads, and to be near users. There are three basic ways. A single leader takes every write and streams its log to followers, as PostgreSQL and MySQL do, and as Raft does. Several leaders, one per datacenter, let every region write locally, at the price of conflicts when two leaders accept different writes to the same thing. Or no leader at all: clients write to several replicas and read from several, and correctness comes from counting, as in Amazon's Dynamo. Independently, the leader can wait for followers before acknowledging a write, which is durable but slow and stalls if one follower dies, or not wait, which is fast, but leaves the followers behind.
Asynchronous followers lag, and users notice. Here is one leader and two followers that apply each write a hundred milliseconds late on average, and a user who posts something and immediately reloads the page, with the read sent to any replica. Two thirds of the time, the post is missing: the read went to a follower that has not seen it yet. After two hundred milliseconds, still nine percent. The usual remedies are small and specific: read your own data from the leader, or remember the position of your last write and wait for a replica that has reached it, and always read from the same replica, so that time never seems to run backwards.
With more than one leader, two regions can accept writes to the same key at the same moment. Here Europe sets a shopping cart to a book while the US sets it to a pen; each write takes fifty milliseconds to cross, so neither saw the other. They are concurrent, and something must decide. The simplest rule, last writer wins, keeps the larger timestamp and silently throws the other away. Worse, timestamps come from clocks. If the US clock runs a hundred milliseconds fast, a write from Europe that had already seen the American one can still carry a smaller timestamp, and lose: the newer value is discarded for the older. We simulated a busy key written five times a second from each region. About one write in five is concurrent with another, so last writer wins silently loses one write in ten, and with clock skew beyond the replication delay, inversions add more: almost a quarter of all writes at a quarter of a second of skew. Version vectors, Part 38's vector clocks with one counter per replica, tell the two cases apart exactly. Causally later writes replace earlier ones, and concurrent writes are kept side by side as siblings for the application to merge, as Dynamo and Riak do. Merging them automatically is what the next chapter is about.
2Quorums and consistencyDegree5 min
Leaderless systems count. Write to W of the N replicas, read from R of them, and keep whichever value carries the newest version number. If R plus W is greater than N, every set of replicas you read overlaps every set that was written, so at least one replica you read has the latest write: the majorities of Paxos, generalized. Amazon's Dynamo, in 2007, typically used three replicas, writing and reading two. For speed you can write and read one, and accept that reads may be stale. And when a home replica is unreachable, Dynamo writes to some other machine that hands the data back later, so writes never fail, at the cost that quorums no longer strictly overlap.
Peter Bailis and his colleagues asked how stale non-strict quorums actually are. We simulated it: a write reaches each replica after a random delay averaging ten milliseconds, and a read starts some time after the write was acknowledged. When R plus W exceeds N, no read was ever stale, as the argument says. With three replicas, reading and writing one, a read issued at the instant of acknowledgement misses the write more than half the time; five milliseconds later, a third; fifty milliseconds later, three in a thousand. Eventual consistency is usually very soon, and now we can say how soon.
Sloppy quorums and failed replicas leave copies that disagree, and something must find the differences. Comparing two replicas of a million keys by sending one hash per key costs sixteen megabytes, even when nothing differs. Ralph Merkle's tree of hashes does better. Each leaf hashes a small range of keys, each node hashes its children, and the root summarizes everything. Two replicas compare roots; if they match, they are done. If not, they compare the children, and descend only into the branches whose hashes differ. With ten keys out of a million differing, our replicas exchanged eleven kilobytes in six round trips and found every one. Even with ten thousand differences, the cost stays below a third of the naive one. Dynamo-style stores combine three repairs: read repair fixes stale replicas that a read happens to notice, hinted handoff delivers writes held for a replica that was down, and anti-entropy compares Merkle trees in the background. The same trees check the integrity of Git repositories, of BitTorrent's pieces, and of certificate transparency logs.
What should a read return? There is a ladder of answers. At the top, linearizability, from Part 33: the system behaves like a single copy, and every operation takes effect at one instant between its start and its end. Sequential consistency keeps a single order but loosens its tie to real time. Causal consistency promises only that you never see an effect before its cause. Session guarantees are promises to one user, like reading your own writes. And eventual consistency promises only that if writes stop, the replicas converge. Each step down needs less coordination. Linearizability needs a round trip to a majority for every operation; causal consistency can be served by any replica that has seen the causes.
Eric Brewer conjectured in 2000, and Seth Gilbert and Nancy Lynch proved in 2002, the CAP theorem. No system can be both linearizable and available, meaning every request to a live replica gets an answer, in a network that can partition. The proof is two lines. Cut replica A off from replica B. A client writes at A, and availability forces A to accept. Another reads at B, and availability forces B to answer, without being able to hear from A, so it returns the old value. So during a partition, a system either refuses the side without a majority, as Raft did in the last part, or answers everyone and sorts out the conflicting writes afterwards. Daniel Abadi pointed out that the more important choice is the everyday one: partitions are rare, but round trips are constant, so even without partitions every system trades latency against consistency.
3CRDTsGraduate5 min
Conflict-free replicated data types. Multi-leader and leaderless systems must merge conflicting copies. In 2011 Marc Shapiro and his colleagues found a way to make every merge safe: design the data type so that merging is a join. Merging must be commutative, so the order of messages does not matter; associative, so the grouping does not matter; and idempotent, so receiving the same state twice does nothing. Mathematically, the states form a join-semilattice: updates only move up, and merge takes the least upper bound. Then convergence is a theorem: if every update eventually reaches every replica, in any order and any number of times, all replicas end in the same state. The proof is that a replica's state is just the join of the updates it has seen, and the three laws let us reorder, regroup and deduplicate them freely.
The simplest example is a counter. A naive replicated counter, add the other replica's count when you merge, double-counts the moment a merge is repeated. A grow-only counter keeps one slot per replica. Each replica increments only its own slot, merging takes the maximum of each slot, and the value is the sum. Here replica A adds two and B adds one; C merges A; A merges B; then they gossip in no particular order. Every replica ends with two, one, zero: a value of three, though messages crossed and some states were merged twice. Two of them make a counter that can go down, and a last-writer-wins register keeps whichever value has the highest timestamp, which is a join too, though it silently discards the losing write.
We tested four CRDTs against a naive alternative, a thousand runs each: four replicas, forty random operations, merges between random pairs in random directions, and finally gossip until every pair has merged. Every CRDT converged in every run. The naive set, which merges by replaying the other replica's log of adds and removes, ended with every replica agreeing in only fifteen runs of a thousand, because adding and removing the same element do not commute.
The same idea scales to richer types. An observed-remove set tags every addition uniquely, and a removal deletes only the tags it has seen, so an addition concurrent with a removal survives. Sequence CRDTs give every character an identifier that sorts between its neighbours', so two people typing at the same spot see their characters interleaved the same way on every replica: the basis of collaborative editors that work offline. Google Docs took the other road, operational transformation, rewriting concurrent edits against each other through a central server. The catch: a CRDT guarantees that replicas agree, not that they agree on what users intended, and an invariant spanning replicas, like a balance that must not go negative, still needs coordination.
Text is the hardest case, because edits name positions, and positions shift. Alice and Bob share the sentence the cat sat. At the same moment Alice types fat in front of cat, and Bob changes sat to ran. If each replica simply replays the other's edits by position, insert at four, delete at eight, Bob ends up right by luck, and Alice's copy deletes the wrong word: the fat ran sat. The replicas disagree for ever. A sequence CRDT such as RGA, the replicated growable array, never uses positions. Every character gets a unique identifier, a counter and the replica's name, and an insertion says which character it follows. Deletions leave an invisible tombstone, and characters inserted after the same one are ordered by identifier. Both replicas now read the fat cat ran. In five hundred random sessions of three editors, RGA converged every time, and positional replay never did. Editors like Automerge and Yjs are built this way.
Convergence is not free. We edited one RGA document twenty thousand times, three edits in ten being deletions. Deleted characters cannot simply vanish, because a late insertion might still refer to them, so they stay as tombstones: after twenty thousand edits, eight thousand visible characters and almost six thousand tombstones. Every element carries its own identifier and its neighbour's, so the document costs forty-two bytes for each character you can see, against one for plain text. A tombstone can be thrown away only when every replica has seen the deletion, and knowing that requires the replicas to coordinate, the very thing CRDTs avoid. Practical libraries such as Automerge and Yjs store runs of consecutive identifiers and compress by column, and cut the overhead by orders of magnitude. Making that efficient was one of the research problems of the last decade.
4PartitioningDegree4 min
With more data than one machine holds, keys must be spread over many. The obvious rule, hash the key and take it modulo the number of machines, has a fatal flaw. Add an eleventh machine to ten, and ninety-one percent of all keys move. In 1997 David Karger and his colleagues, working on what became Akamai, proposed a ring instead. Hash the machines onto a circle, and hash each key onto the same circle; a key belongs to the first machine clockwise from it. A new machine lands somewhere on the circle and takes keys only from its neighbour. Adding the eleventh machine moves eight point six percent of the keys, close to the minimum possible, one eleventh. Jump hashing and rendezvous hashing achieve the same with less memory or simpler code.
One problem remains. With one point per machine, ten machines cut the circle into very unequal arcs. In our test with a hundred thousand keys, the busiest machine held three point four times its share and the idlest an eighth. So each machine is placed on the circle many times, as virtual nodes. With two hundred and fifty-six points each, the busiest holds sixteen percent more than its share, and the spread keeps falling as one over the square root of the number of points. A machine twice as large simply gets twice as many points.
Even a perfect hash spreads keys evenly, not requests. Real popularity follows Zipf's law: the most popular key gets a large share of all traffic, the second half as much, and so on. We sent two million requests for a million keys to a hundred shards. With uniform popularity, the busiest shard is within four percent of the mean. With Zipf's exponent one, the hottest key alone carries seven percent of all requests, and its shard is almost eight times busier than average; at one point two, twenty times. This is the celebrity problem: one account followed by millions. The remedy is to split the hot key: add a random suffix to every write, so it spreads over twenty sub-keys, and have readers fetch and merge them all. Splitting only the ten hottest keys brings the worst shard, at exponent one, under two times the mean. Caching the key in front of the shards, or replicating it more widely, works for reads. Range partitioning, used by Bigtable, HBase and Spanner, keeps neighbouring keys together so that scans are cheap, but it invites an even worse hot spot: if keys are timestamps, every new write goes to the last range.
Inside one datacenter, a table of who owns which arc fits on every machine. Across millions of peers it does not. In 2001 Ion Stoica and his colleagues built Chord. Each node keeps a small table of fingers: the node responsible for its own identifier plus one, plus two, plus four, and so on, doubling, thirty-two entries in all. To find a key, a node forwards the lookup to its farthest finger that does not pass the key. The distance remaining at least halves with each hop, so a lookup takes at most log n hops. We built rings of sixteen to sixteen thousand nodes: lookups took on average about half of log n, plus one, under eight hops with sixteen thousand nodes. Kademlia measures distance by exclusive-or instead, which is symmetric, and runs BitTorrent's peer discovery to this day.
5Transactions across machinesGraduate5 min
A transaction that touches data on several machines must commit everywhere or nowhere. Jim Gray's two-phase commit, from 1978, does it with a coordinator. In phase one the coordinator asks every participant to prepare. Each one makes its part of the transaction durable, holds its locks, and votes. A yes vote is a promise: I will commit if you tell me to, even if I crash and restart. If every vote is yes, the coordinator writes commit to its own log, which is the moment of decision, and tells everyone; any no means abort. Unlike consensus, any single participant can veto the outcome. That is what makes it atomic commitment.
The weakness is one moment. Here the coordinator crashes just after deciding to commit and before telling anyone. The participants voted yes, so they are not allowed to abort; they do not know the decision, so they cannot commit. They wait, holding their locks, for thirty-one seconds, until the coordinator recovers and reads its log. No other transaction can touch those rows in the meantime. Three-phase commit adds a round so participants can finish on their own, but it is safe only if the network is synchronous. Real systems do something simpler: they make the coordinator itself a replicated state machine, a Paxos or Raft group, so it never really goes away.
Google's Spanner, in 2012, ran transactions across datacenters on several continents and made them linearizable, using clocks. Its TrueTime interface does not return a time; it returns an interval guaranteed to contain the true time, a few milliseconds wide, kept narrow by GPS receivers and atomic clocks in every datacenter. To commit, a coordinator picks as timestamp the latest possible current time, and then waits until the earliest possible current time has passed it, about two epsilon, before releasing locks and reporting success. After that wait, any transaction that starts later in real time is certain to get a larger timestamp, so timestamp order is real-time order. The wait overlaps the Paxos round that replicates the commit, so with an epsilon of one or four milliseconds it costs nothing; with seven it adds six.
Most of us do not have atomic clocks in every building. We ran four processes whose clocks disagree by up to five milliseconds, sending each other messages that take up to three. Stamped with their physical clocks, one message in five appears to arrive before it was sent. Lamport's clock never gets causality wrong, but its numbers have nothing to do with time: after ten seconds it reads six thousand. Sandeep Kulkarni and his colleagues combined the two in 2014. A hybrid logical clock keeps the largest physical time it has heard of, from its own clock or from any message, plus a small counter to break ties. It never gets causality wrong, it never strays from true time by more than the clocks' own disagreement, and the counter stayed below eight. CockroachDB and MongoDB stamp their transactions this way. Without Spanner's guaranteed bound they cannot simply wait it out, so a read that meets a value within its clock uncertainty restarts at a later timestamp instead.
Most systems do not run consensus themselves. They ask a small coordination service, Google's Chubby or Apache ZooKeeper, built on Paxos-like protocols, to hold their locks, elect their leaders and store their configuration. A lock in such a service is really a lease: it expires unless the holder keeps renewing it, so a crashed holder cannot block everyone for ever. But a holder that is merely paused, by a long garbage collection, can wake up after its lease has expired and been granted to someone else, and write, unaware. The fix is a fencing token: every grant carries a number that only increases, and the storage refuses any write carrying a smaller number than one it has already seen.
6MapReduceDegree4 min
Jeffrey Dean and Sanjay Ghemawat's MapReduce, of 2004, let a programmer write two small functions and run them on thousands of machines. The input, stored in pieces across the cluster, is split, and a map function runs on each split: for the Job, it emits each word with a count of one, combined locally into a count per word. The shuffle sends every word to one reducer, chosen by hashing the word, so all the counts for a word meet in one place. Each reducer adds them up. For the novels: twenty-five megabytes in, six megabytes of partial counts shuffled, fifty-eight thousand distinct words out. The programmer writes none of the distribution, the scheduling or the recovery.
We ran the Job five ways. With nothing going wrong, half a second. With Pebble four crashing at four tenths of a second, six tenths, three finished maps redone, and the same answer. Re-execution is safe because map and reduce are functions: running a task twice gives the same output, and the master simply uses whichever copy it hears about first. Now make Pebble six eight times slower, a straggler, like a machine with a failing disk. With backup tasks the Job takes point five nine seconds; without them, point eight one, a third longer, because everyone waits for the slow machine's last task. Google's paper reported the same effect: a large sort forty-four percent slower with backup tasks turned off.
How far does it scale? One worker takes three point eight seconds, more than the plain Job, because of the overheads of splitting, scheduling and shuffling. Sixteen workers are seven times faster, not sixteen; sixty-four, barely faster than thirty-two. Every task pays a fixed start-up cost, the shuffle and the reduces do not shrink as mappers are added, and the slowest task sets the finishing time. It is Amdahl's law from Part 10 again, at the scale of a datacenter. MapReduce was built for jobs of terabytes, where these overheads vanish into the work.
The ledger gets row fifteen. The Job as MapReduce on sixteen Pebbles, one of which crashes: six tenths of a second, four and a half times faster than one Pebble, and correct despite the crash. The novels start out spread across the cluster's disks, as Google's file system kept its data. That is the real lesson of row fourteen: move the computation to the data, not the data across an ocean.
MapReduce wrote everything to disk between stages, which made long pipelines slow. Matei Zaharia's Spark, in 2012, kept datasets in memory, and handled failure by remembering each dataset's lineage, the chain of transformations that produced it: a lost piece is simply recomputed. Streaming systems run the same model on input that never ends, grouping events into windows by when they happened rather than when they arrived, with watermarks to say that no older events are expected, and a policy for those that arrive anyway. They get exactly-once results by taking Chandy and Lamport's snapshots of every operator, and replaying the input since the last one after a crash. The ideas that last are MapReduce's: deterministic tasks, recovery by re-execution, and computation moved to the data.
7The tail at scaleIndustry5 min
Jeff Dean and Luiz Barroso's paper of 2013 starts from one observation. A web search, or a social media feed, fans out: one user request becomes requests to a hundred or a thousand servers, and the answer waits for all of them. Suppose each server answers in ten milliseconds, except one request in a hundred, which takes a full second, because of a garbage collection, or a queue behind some large request. With one server, one percent of requests are slow. Waiting for ten, nearly ten percent. Waiting for a hundred, sixty-three percent: one minus point nine nine to the hundred. Our simulation lands on the curve. The rare event at each server is the usual event for the service. Making every server's tail shorter is expensive; the trick is to tolerate it.
The simplest remedy is to ask twice. If a server has not answered within thirty milliseconds, about its ninety-fifth percentile, send the same request to another replica and use whichever reply comes first. It costs about five percent more requests. With a fan-out of a hundred, the median falls from a full second to forty-three milliseconds. The ninety-ninth percentile improves too, until the fan-out is so large that some request meets two slow replicas in a row. Google's systems go further with tied requests: send to two servers at once, and whichever starts the work first tells the other to cancel.
Tails also come from uneven load, and one of the best results in randomized algorithms fixes that. Send a thousand requests to a thousand servers at random, and the busiest server gets about five and a half of them, as Part 20's balls-in-bins analysis predicts. Instead, sample two servers and send each request to the less loaded one: the busiest gets three. Exponentially better, for one extra probe. A third choice adds little. Load balancers like NGINX and Envoy ship the power of two choices as their default.
Requests are not balls that land and stay; they wait in queues and leave. Michael Mitzenmacher's supermarket model asks the same question for queues. A hundred servers, requests arriving at random, each taking a random time. Sent to a random server, each server becomes Part 31's single queue, and the tail explodes as load approaches capacity: at ninety-five percent load the ninety-ninth percentile is eighty-two times the service time. Round robin, which never sends two requests in a row to the same server, halves that, and no more, because job lengths still vary. Two random choices, picking the shorter of two queues, brings it to ten and a half: queue lengths now fall off doubly exponentially. Asking every server for its queue length gets five, but asking a hundred servers costs a hundred messages per request. Two choices gets most of the way for two.
Real requests pass through chains of services, and the tail travels with them. Give each service a median of ten milliseconds and a ninety-ninth percentile of sixty-five. Through three in a row, the end-to-end ninety-ninth percentile is a hundred and twenty milliseconds, not the hundred and ninety-two you get by adding; through ten, two hundred and sixty-five, not six hundred and fifty. Percentiles do not add, which makes naive latency budgets too generous for chains and, as we saw, far too stingy for fan-outs. Retries multiply. If the bottom service is down and each of three layers retries three times, every user request becomes sixty-four attempts at the bottom, just when it can least afford them: the retry storm of the next chapter, built in. The remedies are boring and effective: send the remaining deadline with every call so that work nobody awaits is never started, retry at one layer only, and cap retries at a tenth of requests, so that even four layers add less than half again.
8Failure at scaleIndustry6 min
At scale, failure stops being an event and becomes a rate. A hundred thousand disks failing at one percent a year means about three every day. Recovery has to be automatic, and so routine that nobody is paged. Worse, failures are not independent. A power unit or a top-of-rack switch takes down many machines at once; a bad configuration pushed everywhere takes down everything. So replicas go in different failure domains, and changes roll out slowly. Gray failures are machines that are slow, or fail only some requests, and still pass their health checks. And metastable failures, named in 2022, are the strangest: the trigger passes, but the system stays down, held there by its own reaction.
In 2009 Jeff Dean listed what a typical new Google cluster goes through in its first year. About a thousand individual machine failures and thousands of disk failures. Twenty racks failing, each taking forty to eighty machines with it, and five racks going wonky, losing half their packets. A dozen or so router failures and reloads, a network rewiring, and a power distribution failure that takes down five hundred to a thousand machines for six hours. Do the arithmetic for machines that last three years on average. A six-hour job on a thousand machines finishes without a single failure only four times in five. A day on ten thousand machines, essentially never. So recovery is the normal path, not the exception: MapReduce's re-execution, Raft's elections and Dynamo's hinted handoff are running somewhere every day.
Availability is measured in nines. Ninety-nine point nine percent, three nines, allows about nine hours of downtime a year. Parts in series multiply. A request that needs ten services, each at three nines, succeeds only ninety-nine percent of the time; a hundred, about ninety percent, more than a month of failure a year. That is why a page that calls many services must tolerate some of them failing. Replicas in parallel multiply the other way: if any one of three independent replicas will do, three nines become nine nines, thirty milliseconds of downtime a year. But the word independent carries the whole result. Put the three replicas in one rack whose switch fails a twentieth of a percent of the time, and they are worse than a single machine elsewhere. In three racks, two million simulated moments saw no outage at all. So never promise more than your dependencies multiply to, shorten the chain of things a request needs, and put replicas in separate failure domains: racks, power feeds, buildings, regions.
Every recovery we have seen starts with a decision: this machine has failed. But a machine that has crashed and one that is merely slow look the same from outside. We simulated heartbeats every hundred milliseconds across a network that alternates between calm and congested spells, with occasional garbage-collection pauses. A fixed timeout must be long enough for the worst spell: a timeout of a hundred and seventy-five milliseconds raises about a hundred false alarms an hour, and getting below a few an hour means waiting a quarter of a second or more. The phi accrual detector, used by Cassandra and Akka, instead keeps a window of recent gaps and raises its suspicion as the current silence becomes less likely. It needs no hand-tuned timeout, and it adapts when the network changes. But on our trace it lands on almost the same curve: faster detection buys false alarms, whichever detector you use. Neither can be certain, which is Part 38's lesson again. So a node that has been declared dead must be fenced off, by a new term, an epoch or a fencing token, because it may wake up and keep working.
Here is a metastable failure, simulated. A server can answer a hundred requests a second and normally gets eighty. Clients give up after one second and retry, up to three times. For ten seconds, load spikes to a hundred and sixty. Without retries the server falls behind, and when the spike passes it slowly drains its queue and recovers. With retries, every slow request comes back as two, three, four requests. The server is now working mostly on requests whose clients have already given up, every answer is too late, and goodput stays at zero long after the spike has gone. Random backoff does not save it. What does is refusing work that can no longer be useful: dropping requests whose deadline has passed brings the server straight back. Load shedding, retry budgets and circuit breakers are the same idea, and part 50 builds them.
Because failure is constant, the large operators practise it. Netflix's Chaos Monkey, from 2011, kills machines in production, at random, during working hours, so that recovery is exercised every day instead of discovered during a crisis. Companies hold game days that fail an entire datacenter on purpose. And the industry publishes blameless post-mortems of real outages, which show the same causes over and over: a configuration change, a retry storm, an expired certificate, a dependency loop where the recovery tool depends on the thing that failed. It is the lesson of our Raft campaign at datacenter scale: the code that runs only during failures is the least tested code in the system.
9Frontier: how little coordination?Research4 min
Every guarantee in this part costs coordination: replicas waiting for each other, across a datacenter or an ocean. So which problems actually need it? Joseph Hellerstein conjectured an answer in 2010, and Tom Ameloot and his colleagues proved it: a problem can be solved consistently without coordination if and only if it is monotonic, meaning new information never retracts an earlier conclusion. Counting likes and adding to a set are monotonic, and our set replicas converged in all thousand runs. Removing from a plain set is not, and converged in only fifteen. Unique usernames and non-negative balances are not monotonic either: some operations must wait. Peter Bailis turned this into an engineering tool, invariant confluence: check each invariant of an application separately. In the standard TPC-C benchmark, most of them need no coordination at all, and a database that knows it can run them many times faster.
CAP draws one line through the hierarchy of Chapter two: linearizable systems cannot stay available during a partition. But where exactly is the line? In 2011 Prince Mahajan, Lorenzo Alvisi and Mike Dahlin proved that no model stronger than a form of causal consistency can be both always available and convergent. Causality, Lamport's happened-before from Part 38, is the most an always-available system can promise. And it can be had at global scale: systems like COPS and Eiger give causal consistency across datacenters, even with transactions. What remains open is its price: how much metadata each write must carry to track causality among millions of clients. The lower bounds and the best systems are still far apart.
How would you know whether a database actually delivers what it promises? Watch only what clients saw, and look for a contradiction. In general this is hard: deciding whether a history is linearizable, or serializable, is NP-complete. Kyle Kingsbury and Peter Alvaro's Elle, in 2020, makes it easy by choosing the test. Every transaction appends unique numbers to lists and reads whole lists, so every read reveals exactly which writes came before it, and in what order. From that, Elle draws an edge whenever one transaction must have come before another. Here transaction three sixty appended three fifty to key four, and three sixty-two appended three fifty-one right after it, so three sixty came first. But three sixty-two had read key four without three fifty, so it came first. A cycle: no serial order explains what the clients saw. We ran two thousand transactions on two stores. On a single serial copy, no cycles. On a store that reads from a lagging replica, a hundred and forty-three of them, involving eight hundred and thirty-five transactions. Elle has found anomalies like these in a long list of production databases.
Where the field stands. Programming languages such as Bloom and Hydro try to find the monotonic parts of a program automatically, and to insert coordination only where the CALM theorem says it is unavoidable. Sequence CRDTs for collaborative text still struggle to avoid interleaving anomalies with bounded metadata, which matters for local-first software, where your data lives on your devices first. Metastable failures are found after they happen; predicting which systems have a stable bad state, and how big a trigger tips them over, is open. And hedging, retries and admission control interact in ways that have very little theory. This part's research problem sits right there: design a retry policy for our simulator that provably recovers from any finite spike, while keeping the tail benefit that hedging gave us.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. The datacenter as one computer, and what its distances cost. Replicas, their lag, and quorums whose overlap buys fresh reads, with the staleness of sloppier quorums measured. The hierarchy of consistency models, CAP stated precisely, and CRDTs, whose merges cannot conflict. A hash ring that moves almost no keys, and Chord's fingers. Two-phase commit, which can block for ever, and Spanner, which waits out its clock uncertainty. The Job as MapReduce on sixteen Pebbles, surviving a crash. And the tail: one slow server in a hundred, hedged requests, two choices, and failures that feed themselves.
Where this comes back. CRDTs return in version control and in local-first web apps, Parts 41 and 42. The tail returns as latency budgets across a graph of services and in search engines. Part 46 builds streams with watermarks and exactly-once state, and query engines that shuffle like MapReduce. Parts 48 and 49 design real systems with sharding, hot keys and fencing tokens. And Part 50 keeps them running, with the load shedding and retry budgets that cure metastable failures.
In practice. Treat consistency as a product decision: which anomalies may a user see? Start strong and relax only where you have measured the cost. Cassandra and DynamoDB use quorums; Spanner and CockroachDB use consensus and clocks; Redis Cluster splits keys into hash slots. Spark, Flink and Beam are MapReduce's model with memory and watermarks. Watch the ninety-ninth percentile, not the mean, hedge reads that are safe to repeat, and let the load balancer use two choices. And give every request a deadline: back off with jitter, budget your retries, and throw away work nobody is waiting for.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: our MapReduce survives any worker's crash, but not its master's. Make it survive that too, and show that the answer does not change. The last, marked with a star, is a research problem: a retry policy that provably recovers from any finite spike, without giving up what hedging bought.
That ends Act Seven, Many Machines. Next time, Part 40 opens Act Eight, Building Software, with software engineering: Parnas' information hiding, contracts and subtyping, testing and flaky tests, Brooks' and Conway's laws, and the dependency graph of the very repository that built this series, measured.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. CRDTs return in version control and local-first web apps (Parts 41 and 42). Part 46 builds streams with watermarks and query engines that shuffle like MapReduce, Parts 48 and 49 design systems with sharding, hot keys and fencing tokens, and Part 50 cures metastable failures with load shedding and retry budgets.
Key results
The part's results in one place, for revision.
Try it
Lab 39 · Quorums that overlap, and the tail at scale
Simulate reads that follow a write by t milliseconds on three replicas: with R + W > N no read is ever stale, and with R = W = 1 the stale share decays with t. Then fan a request out to n servers, one in a hundred of which is slow, compare the slow share with 1 - 0.99^n, and hedge.
python -m videos.cs.labs 39
needs numpy, scipy, matplotlib · download lab39.py ·
source on GitHubN = 3, R = 1, W = 1: stale reads at 0, 5, 20, 50 ms 52.7% 32.5% 7.1% 0.3% (the film: 54%, 32%, 7.4%, 0.34%)
N = 3, R = 2, W = 1: stale reads at 0, 5, 20, 50 ms 17.1% 6.7% 0.4% 0.0%
N = 3, R = 2, W = 2: stale reads at 0, 5, 20, 50 ms 0.0% 0.0% 0.0% 0.0%
fan-out 1: requests that wait a second 0.9% formula 1.0% median 7 ms, hedged 7 ms
fan-out 10: requests that wait a second 9.1% formula 9.6% median 29 ms, hedged 28 ms
fan-out 100: requests that wait a second 64.0% formula 63.4% median 1000 ms, hedged 42 ms
Overlapping quorums are never stale and non-overlapping ones are stale for a while; and a request that waits for a hundred servers is slow 63% of the time although each server is slow 1% of the time, until a second copy is sent after 30 ms.
The code (70 lines; it asserts its own result)
"""Lab 39: measure how stale a quorum read can be, and how a fan-out turns one slow server in a hundred into most requests."""
from videos.coursekit import labs
import numpy as np
from explainer.cs.dist import scale
TITLE = "Quorums that overlap, and the tail at scale"
GOAL = ("Simulate reads that follow a write by t milliseconds on three replicas: with R + W > N no read is ever "
"stale, and with R = W = 1 the stale share decays with t. Then fan a request out to n servers, one in a "
"hundred of which is slow, compare the slow share with 1 - 0.99^n, and hedge.")
TASKS = [
"Try N = 5 with (R, W) = (2, 3), (3, 3) and (1, 5). Which are never stale, and which has the cheapest reads?",
"Make servers slow 1 time in 1,000 (p_slow=0.001). At what fan-out are half of all requests slow now?",
"Move the hedge from 30 ms to 5 ms and to 200 ms. What does each do to the median at fan-out 100, and what does 5 ms cost in extra requests?",
]
DELAYS = (0, 5, 20, 50)
FANOUTS = (1, 3, 10, 30, 100, 300)
def run(seed=0):
lab = labs.Lab()
configs = [(1, 1), (2, 1), (1, 2), (2, 2), (1, 3), (3, 1)]
stale = {(r, w): [scale.pbs(3, r, w, t, trials=6000, seed=seed + 7 * k) for k, t in enumerate(DELAYS)]
for r, w in configs}
for (r, w), row in stale.items():
if (r, w) in ((1, 1), (2, 1), (2, 2)):
lab.row(f"N = 3, R = {r}, W = {w}: stale reads at 0, 5, 20, 50 ms",
" ".join(f"{p:.1%}" for p in row) + (" (the film: 54%, 32%, 7.4%, 0.34%)" if (r, w) == (1, 1) else ""))
for (r, w), row in stale.items():
if r + w > 3:
assert max(row) == 0, f"R = {r}, W = {w}: the quorums overlap, so a read always meets the write"
else:
assert row[0] > 0.1 and row[0] > row[1] > row[2] >= row[3], "no overlap: staleness, fading with time"
one = stale[1, 1]
assert abs(one[0] - 0.54) < 0.04 and abs(one[1] - 0.32) < 0.04 and abs(one[2] - 0.074) < 0.02 and one[3] < 0.012
plain = scale.tail(FANOUTS, trials=20000, seed=seed)
hedged = scale.tail(FANOUTS, trials=20000, hedge_at=30.0, seed=seed)
for row, h in zip(plain, hedged):
if row["fanout"] in (1, 10, 100):
lab.row(f"fan-out {row['fanout']}: requests that wait a second",
f"{row['frac_slow']:.1%} formula {row['formula']:.1%} median {row['p50']:.0f} ms, hedged {h['p50']:.0f} ms")
n = max(200, 20000 // row["fanout"])
se = np.sqrt(row["formula"] * (1 - row["formula"]) / n)
assert abs(row["frac_slow"] - row["formula"]) < 4 * se + 0.003, "the slow share is 1 - 0.99^n"
at100 = [r for r in plain if r["fanout"] == 100][0], [r for r in hedged if r["fanout"] == 100][0]
assert at100[0]["p50"] > 900 and at100[1]["p50"] < 100, "at fan-out 100 the median is a slow server; a hedge removes it"
lab.note = ("Overlapping quorums are never stale and non-overlapping ones are stale for a while; and a request "
"that waits for a hundred servers is slow 63% of the time although each server is slow 1% of the "
"time, until a second copy is sent after 30 ms.")
fig, ax = labs.figure(2, size=(11, 4.2))
ts = np.arange(0, 61, 4)
for (r, w), color in (((1, 1), labs.RED), ((2, 1), labs.GOLD), ((2, 2), labs.GREEN)):
ys = [scale.pbs(3, r, w, float(t), trials=1500, seed=seed + 100 + j) for j, t in enumerate(ts)]
ax[0].plot(ts, ys, color=color, marker="o", ms=3, label=f"R = {r}, W = {w}" + (": R + W > N" if r + w > 3 else ""))
ax[0].set(title="Three replicas: how often a read misses the last write", xlabel="milliseconds between the write's acknowledgement and the read",
ylabel="share of reads that are stale", ylim=(-0.02, 0.7))
ax[0].legend(loc="upper right")
grid = np.logspace(0, np.log10(300), 100)
ax[1].plot(grid, 1 - 0.99 ** grid, color=labs.MUTED, ls="--", label="1 - 0.99^n")
ax[1].scatter(FANOUTS, [r["frac_slow"] for r in plain], color=labs.RED, zorder=3, label="simulated, no hedge")
ax[1].scatter(FANOUTS, [r["frac_slow"] for r in hedged], color=labs.GREEN, zorder=3, label="simulated, hedged at 30 ms")
ax[1].set(title="One server in a hundred takes a second", xlabel="fan-out n (servers a request waits for)",
ylabel="share of requests that take a second", xscale="log", ylim=(-0.03, 1.05))
ax[1].legend(loc="upper left")
lab.fig = fig
return lab
Now change it
- Try N = 5 with (R, W) = (2, 3), (3, 3) and (1, 5). Which are never stale, and which has the cheapest reads?
- Make servers slow 1 time in 1,000 (p_slow=0.001). At what fan-out are half of all requests slow now?
- Move the hedge from 30 ms to 5 ms and to 200 ms. What does each do to the median at fan-out 100, and what does 5 ms cost in extra requests?
Problems, with solutions
Try each problem before opening its solution.
-
Quorums. Prove that if R + W > N every read quorum meets every write quorum, and give a run with R + W ≤ N that returns a stale value.
Solution
A read set and a write set are subsets of the N replicas of sizes R and W; if they were disjoint their union would have R + W > N elements, impossible. So some replica in the read set holds the latest acknowledged write, and taking the highest version returns it. For R + W ≤ N, take N = 3, W = 1, R = 1: write v₂ to replica A only, acknowledged; read from replica C, which still holds v₁. Our simulation of (3, 1, 1) returns the stale value 54% of the time at the moment of acknowledgement.
-
CRDT convergence. Prove that a state-based CRDT whose merge is the join of a semilattice converges.
Solution
Each replica's state is the join of its initial state and of the states it has merged, plus local updates, which are inflations (s ≤ u(s)). Because ⊔ is associative and commutative, the result of any sequence of merges is the join of the set of all updates' effects that reached the replica, independent of order and grouping; because ⊔ is idempotent, receiving a state twice changes nothing. Two replicas that have received the same set of updates therefore hold the join of the same set: the same state. Our test: 1,000 random gossip orders, every CRDT converged.
-
Consistent hashing. Show that adding an (n+1)-th node moves 1/(n+1) of the keys in expectation, and that h(k) mod n moves n/(n+1).
Solution
With n + 1 random points on the circle, by symmetry each node's arc has expected length 1/(n+1), and the new node takes exactly the keys in its arc, so the expected fraction moved is 1/(n+1). For modulo: a key stays iff h mod n = h mod (n+1). For h uniform over a range that is a multiple of n(n+1), h mod n(n+1) is uniform, and by the Chinese remainder theorem (n and n+1 are coprime) the pair (h mod n, h mod (n+1)) is uniform over n(n+1) pairs, of which n agree (h mod n(n+1) < n). So a fraction n/(n(n+1)) = 1/(n+1) stays and n/(n+1) moves (91% for n = 10, as measured).
-
Two-phase commit and Spanner. Show that 2PC blocks if the coordinator crashes after one participant votes yes, and explain why commit wait makes timestamps respect real time.
Solution
A participant that voted yes has promised to commit if told to, so it cannot abort on its own (the coordinator may have decided commit and told someone); it cannot commit either (the coordinator may have decided abort, for example because another participant voted no). Nothing it can learn from other participants that are also uncertain resolves this, so it waits for the coordinator. Spanner: a transaction T₁ picks s₁ = TT.now().latest and does not report commit until TT.now().earliest > s₁, so its true commit time t₁ > s₁. Any T₂ that starts after T₁'s commit is reported starts at true time > t₁ > s₁, and picks s₂ = TT.now().latest ≥ its true start time > s₁. So real-time order implies timestamp order. The wait is about 2ε.
-
Build. Let our MapReduce survive the master's crash.
Solution
Solution sketch. The master's state is the task table: each task's state (idle, in progress, done), its worker, and, for finished maps, where their outputs live. Append every change to a log on stable storage (or replicate it with Raft from Part 38). On restart, replay the log; tasks in progress are reset to idle, since their workers may have died too, and finished maps whose worker is gone are reset as in a worker failure. Because tasks are deterministic and reducers use whichever copy of a map output they get, duplicate executions do not change the result. Test it by crashing the master at random times and comparing the top twenty words with the reference.
-
★ Research. Design a retry and admission policy for our metastable simulator that provably recovers from any finite spike while keeping hedging's tail benefit.
Discussion. This is open in general. Directions: a retry budget (retries at most a fraction β of first attempts) bounds the offered load by (1 + β)λ, so if (1 + β)λ < μ the queue is stable after any spike; dropping requests whose deadline has passed bounds the queue's useful work; hedges count against the same budget. What is missing is a proof for realistic clients (timeouts, backoff, many layers) and a characterization of the largest spike each policy survives, ideally checked against adversarially chosen spikes in our simulator.
Notes and sources
Glossary
- quorum — a set of replicas whose agreement suffices; read and write quorums overlap when R + W > N.
- sloppy quorum, hinted handoff — accepting writes on stand-in replicas during failures, delivered later.
- anti-entropy — background comparison and repair of replicas, usually with Merkle trees.
- probabilistically bounded staleness (PBS) — the probability that a read is stale, against time since the write.
- consistency model — what reads may return: linearizable, sequential, causal, session guarantees, eventual.
- CAP, PACELC — under a partition choose consistency or availability; else latency or consistency.
- CRDT — a replicated data type whose merge is a semilattice join, so replicas converge without coordination.
- version vector, siblings — per-replica counters that detect concurrent writes; the concurrent values kept.
- RGA, tombstone — a sequence CRDT ordering elements by unique ids; a deleted element kept as a marker.
- consistent hashing, virtual node — keys and nodes hashed onto a ring; each node placed many times.
- hot key, salting — a key with outsized traffic; splitting it into sub-keys with random suffixes.
- two-phase commit, commit wait — atomic commit through a coordinator; Spanner's wait of about 2ε.
- hybrid logical clock — (physical time heard of, counter): causal like Lamport, close to real time.
- lease, fencing token — a lock that expires; a number the resource checks to reject a stale holder.
- straggler, backup task — a slow task; a duplicate run near the end, first result wins.
- tail latency, hedged request — high percentiles; a second request sent after a delay.
- power of two choices — route each request to the less loaded of two random servers.
- gray failure, metastable failure — partial failures that evade detection; a bad state sustained by the system's own reaction.
- phi accrual detector — suspicion as −log₁₀ of the probability of the current silence.
- CALM, invariant confluence — monotonic programs need no coordination; invariants that merges preserve.
Sources
- M. Kleppmann, Designing Data-Intensive Applications (2017), chs. 5–9.
- L. A. Barroso, U. Hölzle and P. Ranganathan, The Datacenter as a Computer (3rd ed., 2018).
- J. Saltzer and F. Kaashoek, Principles of Computer System Design (2009); M. van Steen and A. Tanenbaum, Distributed Systems (4th ed., 2023).
- G. DeCandia et al., "Dynamo: Amazon's highly available key-value store", SOSP 2007.
- P. Bailis et al., "Probabilistically bounded staleness for practical partial quorums", VLDB 2012; "Coordination avoidance in database systems", VLDB 2014.
- S. Gilbert and N. Lynch, "Brewer's conjecture and the feasibility of consistent, available, partition-tolerant web services", 2002; D. Abadi, "Consistency tradeoffs in modern distributed database system design", 2012.
- M. Shapiro, N. Preguiça, C. Baquero and M. Zawirski, "Conflict-free replicated data types", SSS 2011; H.-G. Roh et al., "Replicated abstract data types", JPDC 2011; M. Kleppmann et al., "Local-first software", Onward! 2019.
- R. Merkle, "A digital signature based on a conventional encryption function", CRYPTO 1987.
- D. Karger et al., "Consistent hashing and random trees", STOC 1997; J. Lamping and E. Veach, "A fast, minimal memory, consistent hash algorithm", 2014; I. Stoica et al., "Chord", SIGCOMM 2001; P. Maymounkov and D. Mazières, "Kademlia", IPTPS 2002.
- J. Gray, "Notes on data base operating systems", 1978; J. Corbett et al., "Spanner", OSDI 2012; S. Kulkarni et al., "Logical physical clocks", OPODIS 2014.
- M. Burrows, "The Chubby lock service", OSDI 2006; P. Hunt et al., "ZooKeeper", USENIX ATC 2010.
- J. Dean and S. Ghemawat, "MapReduce", OSDI 2004; M. Zaharia et al., "Resilient distributed datasets", NSDI 2012; T. Akidau et al., "The dataflow model", VLDB 2015.
- J. Dean and L. A. Barroso, "The tail at scale", CACM 2013; M. Mitzenmacher, "The power of two choices in randomized load balancing", 1996; Y. Azar et al., "Balanced allocations", STOC 1994.
- J. Dean, "Designs, lessons and advice from building large distributed systems", LADIS 2009 keynote.
- N. Hayashibara et al., "The φ accrual failure detector", SRDS 2004.
- P. Huang et al., "Gray failure", HotOS 2017; N. Bronson et al., "Metastable failures in distributed systems", HotOS 2021; L. Huang et al., "Metastable failures in the wild", OSDI 2022.
- J. M. Hellerstein and P. Alvaro, "Keeping CALM", CACM 2020; T. Ameloot, F. Neven and J. Van den Bussche, "Relational transducers for declarative networking", JACM 2013; P. Mahajan, L. Alvisi and M. Dahlin, "Consistency, availability, and convergence", UT Austin TR 2011; W. Lloyd et al., "COPS", SOSP 2011.
- P. Gibbons and E. Korach, "Testing shared memories", SIAM J. Comput. 1997; K. Kingsbury and P. Alvaro, "Elle", VLDB 2020.
About this partfrom its README
Part 39 of a sixty-one-part course in computer science (see the series plan and the syllabus), the last part of Act VII, Many Machines. At the scale of a datacenter, every guarantee has a price in latency or availability. CAP states the trade-off, CRDTs avoid it by making merges commutative, and Spanner pays for it with atomic clocks. One slow server in a hundred makes most requests slow. The Job finally runs as MapReduce on sixteen machines, one of which dies.
The instruments are in explainer/cs/dist/ (tested in tests/test_cs39_scale.py and tests/test_cs39_replicas.py):
scale.py: probabilistically bounded staleness for N, R, W; replication lag; CRDTs (G-counter, PN-counter, OR-set, LWW register) and a naive set under random gossip; consistent hashing with virtual nodes, jump and rendezvous hashing; Chord's fingers; two-phase commit behind a crashed coordinator; Spanner's commit wait; fan-out tails and hedged requests; the power of two choices; a metastable retry storm.mapreduce.py: the Job as MapReduce on simulated Pebbles (real counting, splits, a hashed shuffle, a crash with re-execution, stragglers and backup tasks, a timeline of every task attempt).replicas.py: two leaders under last-writer-wins with clock skew against version vectors; Merkle-tree anti-entropy; RGA, a sequence CRDT, against positional replay, and its tombstone overhead; hot keys under Zipf popularity, and salting.service.py: load balancing as queueing (random, round robin, two choices, shortest queue); availability in series, in parallel and with correlated rack failures; failure detection by fixed timeouts and phi accrual; tails through a chain of services; retry amplification.clocks.py(from Part 38) gains hybrid logical clocks;history.pyis an Elle-style checker that infers the dependency graph of list-append transactions and finds its cycles.
Chapter notes
- Hook. The Job on sixteen Pebbles: 48 maps, a shuffle, 16 reduces. Pebble 4 crashes at 0.4 s; three finished maps are redone; backup copies finish the last slow tasks. 0.60 s against 2.65 s on one Pebble, and the same top twenty words.
- 1. The datacenter, and replication. Latency numbers on a scale where one cycle is a second (a datacenter round trip: seventeen days; California to Europe: fifteen years). Single-leader, multi-leader and leaderless replication. Replication lag: 67% of immediate reads miss your own post, 9% after 200 ms; read-your-writes, monotonic reads. Two leaders writing one key five times a second each: 19% of writes concurrent, so last-writer-wins silently loses 9.7%; with 250 ms of clock skew, 22.7%; version vectors lose none and keep siblings.
- 2. Quorums and consistency. R + W > N; Dynamo's sloppy quorums and hinted handoff. Probabilistically bounded staleness: (3, 1, 1) is stale 54%, 32%, 7.4% and 0.34% of the time at 0, 5, 20 and 50 ms; strict quorums never. Merkle-tree anti-entropy on a million keys: 11 KB in six round trips for ten differences, against 16 MB for one hash per key. The consistency hierarchy; CAP (Gilbert–Lynch) with a 40/60 partition: CP refuses 40% of requests, AP answers all with stale minority reads and 200 conflicting writes; PACELC.
- 3. CRDTs. Join-semilattices: commutative, associative, idempotent merges, and the convergence theorem. A G-counter step by step. A thousand gossip runs each: G-counter, PN-counter, OR-set and LWW register always converge; a naive log-replaying set in 15. OR-sets and sequence CRDTs. Two people editing "the cat sat": positional replay diverges ("the fat ran sat"), RGA gives "the fat cat ran" on both; 500 random sessions: RGA 500, replay 0. The cost: after 20,000 edits, 8,404 visible characters, 5,798 tombstones, 42 bytes per visible character.
- 4. Partitioning. Modulo hashing moves 91% of keys when an eleventh node joins; a consistent-hash ring 8.6% (minimum 9.1%); jump and rendezvous hashing. Virtual nodes: the busiest of ten nodes at 3.39× its share with one point, 1.16× with 256. Hot keys: Zipf(1) puts 7% of requests on one key and its shard at 7.8× the mean; salting the ten hottest keys twenty ways brings it to 1.8×. Range partitioning and timestamp hot spots. Chord: 2.8 hops for 16 nodes, 7.9 for 16,384, about ½ log₂ n + 1; Kademlia.
- 5. Transactions across machines. Two-phase commit, and its blocking: a coordinator crash after deciding leaves participants holding locks for 31 s. 3PC; commit over Paxos groups. Spanner's TrueTime and commit wait (2ε; free for ε = 1 and 4 ms, 6 ms extra for 7). Hybrid logical clocks: on four processes 5 ms apart, physical timestamps put 21% of receipts before their sends; HLC none, within 3.4 ms of true time, counter at most 7. Chubby, ZooKeeper, leases and fencing tokens.
- 6. MapReduce. Map, shuffle, reduce: 25 MB in, 6 MB shuffled, 57,895 distinct words. Five runs: plain 0.51 s; a crash 0.60 s with 3 maps redone; a straggler 0.59 s with backups and 0.81 s without; all correct. Scaling: 3.85 s on one worker, 0.55 s on 16, 0.42 s on 64 (Amdahl). Ledger row 15. Spark's lineage, streaming with watermarks, exactly-once by snapshots.
- 7. The tail at scale. One request in a hundred taking a second: 1 − 0.99ⁿ of requests are slow, 63.9% at a fan-out of 100 (simulated). Hedging at 30 ms: the median at fan-out 100 falls from 1,000 ms to 43 ms. Two choices: the busiest of 1,000 servers 5.5 → 3. The supermarket model at 95% load: p99 of 82 service times for random routing, 46 for round robin, 10.5 for two choices, 5.4 for the shortest queue. Through a chain of 3 and 10 services: p99 120 and 265 ms, against 192 and 648 by adding; retries through 3 layers: 64 attempts per request.
- 8. Failure at scale. Correlated, gray and metastable failures. A cluster's first year (Dean 2009); a 6-hour job on 1,000 machines sees no failure 80% of the time. Nines: ten dependencies at 99.9% give 99.0%; three independent replicas 99.9999999%; three in one rack 99.95%. Failure detection: a 175 ms timeout raises 101 false alarms an hour; phi accrual has no hand tuning but the same trade-off. A retry storm: after a ten-second spike, goodput 78/s without retries, 0 with retries (with or without backoff), 80/s when expired requests are dropped. Chaos engineering and post-mortems.
- 9. Frontier: how little coordination? The CALM theorem (monotonic iff coordination-free) and invariant confluence; CAC: no model stronger than real-time causal consistency is always available and convergent; COPS. Checking histories: Elle's dependency cycles on 2,000 list-append transactions, none on a serial store, 143 on a stale replica. Four open problems, and the ★ research problem.
- Outro. Recap, payoffs, practice, problems, next part.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- The datacenter as a computer; latency numbers every programmer should know (cited, on the "cycle = second" scale).
- Replication: single-leader, multi-leader, leaderless; synchronous against asynchronous; replication-lag anomalies.
- Quorums R + W > N; sloppy quorums and hinted handoff (Dynamo 2007); probabilistically bounded staleness (computed).
- Consistency models from linearizable to eventual, as a hierarchy; session guarantees.
- CAP (Brewer; the Gilbert–Lynch proof), stated precisely; PACELC.
- CRDTs (Shapiro et al. 2011): join-semilattices whose merge is commutative, associative and idempotent, which gives convergence (proved); counters, OR-sets, sequence CRDTs for collaborative editing.
- Partitioning: hash against range; consistent hashing (Karger et al. 1997) with virtual nodes (load variance computed); rendezvous and jump hashing.
- DHTs: Chord's fingers and O(log n) lookups; Kademlia's XOR metric.
- Distributed transactions: 2PC and its blocking; 3PC; Spanner (2012): TrueTime and commit wait, animated; Calvin.
- MapReduce (Dean & Ghemawat 2004): map, shuffle, reduce. The Job on sixteen simulated Pebbles, with a crash and re-execution; stragglers and backup tasks. Ledger row 15.
- Spark's RDDs and lineage; streaming with watermarks; exactly-once via Chandy–Lamport (callback to Part 38).
- Coordination: Chubby and ZooKeeper; leases and fencing tokens.
- The tail at scale (Dean & Barroso 2013): 1 − 0.99¹⁰⁰ ≈ 63% (computed); hedged requests; two choices (callback to Part 20).
- Failure at scale: correlated, gray and metastable failures; chaos engineering; post-mortems (cited). Outro.
Computed: PBS; CRDT convergence under random delivery orders; consistent-hashing variance; Chord hops; 2PC blocking; Spanner's timeline; the MapReduce Job with a failure; tail amplification; hedging. Visuals: the consistency hierarchy as a map; replicas merging up a lattice; the hash ring; Chord fingers; the shuffle as colored streams; the fan-out tail. In practice: Cassandra, DynamoDB, Spanner and CockroachDB, Redis Cluster, Spark; consistency choices as product decisions. Reading: Kleppmann, Designing Data-Intensive Applications; Barroso, Hölzle & Ranganathan, The Datacenter as a Computer; Saltzer & Kaashoek, Principles of Computer System Design; van Steen & Tanenbaum; DeCandia et al. 2007; Corbett et al. 2012; Dean & Ghemawat 2004; Zaharia et al. 2012; Shapiro et al. 2011; Gilbert & Lynch 2002; Karger et al. 1997; Stoica et al. 2001; Dean & Barroso 2013; Burrows 2006; Hunt et al. 2010; Bailis et al. 2012; Akidau et al. 2015.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
法定人数。 证明若 R + W > N,则每个读集合都与每个写集合相交;并给出一个 R + W ≤ N 时读到旧值的执行。
解答
读集合与写集合分别是 N 个副本中大小为 R 和 W 的子集;若二者不相交,它们的并有 R + W > N 个元素,不可能。 所以读集合中某个副本持有最新的已确认写入,取最高版本即可读到它。若 R + W ≤ N,取 N = 3、W = 1、R = 1:v₂ 只写到副本 A 并被确认;从仍持有 v₁ 的副本 C 读取。我们对 (3, 1, 1) 的模拟在确认的那一刻有 54% 的读是旧值。
-
CRDT 的收敛。 证明合并为半格上并运算(join)的基于状态的 CRDT 一定收敛。
解答
每个副本的状态是其初始状态、它合并过的状态与本地更新的并,而本地更新都是膨胀(s ≤ u(s))。由于 ⊔ 满足结合律和交换律,任何合并序列的结果都等于到达该副本的全部更新效果之集合的并,与顺序和分组无关;由于 ⊔ 幂等, 重复收到同一状态不改变任何东西。因此收到同一组更新的两个副本持有同一集合的并,即同一状态。我们的测试:1,000 种随机传播顺序,每种 CRDT 都收敛。
-
一致性哈希。 证明加入第 n+1 个节点时期望移动 1/(n+1) 的键,而 h(k) mod n 移动 n/(n+1)。
解答
圆上有 n + 1 个随机点时,由对称性每个节点的弧期望长度为 1/(n+1),新节点恰好接管其弧内的键,所以期望移动比例为 1/(n+1)。取模时:键不动当且仅当 h mod n = h mod (n+1)。若 h 在 n(n+1) 的倍数范围内均匀分布,则 h mod n(n+1) 均匀, 由中国剩余定理(n 与 n+1 互素),二元组 (h mod n, h mod (n+1)) 在 n(n+1) 个组合上均匀,其中 n 个相等(h mod n(n+1) < n)。 所以留下的比例为 1/(n+1),移动 n/(n+1)(n = 10 时为 91%,与测量一致)。
-
两阶段提交与 Spanner。 证明若协调者在某参与者投赞成票后崩溃,2PC 会阻塞;并说明提交等待为何使时间戳符合真实时间。
解答
投了赞成票的参与者已承诺“被告知就提交”,所以不能自行中止(协调者可能已决定提交并告诉了别人);也不能提交 (协调者可能因另一参与者投反对票而决定中止)。从同样不确定的其他参与者那里得不到能解决此问题的信息,所以它只能等协调者。 Spanner:事务 T₁ 取 s₁ = TT.now().latest,直到 TT.now().earliest > s₁ 才报告提交,所以其真实提交时刻 t₁ > s₁。在 T₁ 报告提交后才开始的 T₂,其真实开始时刻 > t₁ > s₁,取 s₂ = TT.now().latest ≥ 其真实开始时刻 > s₁。所以真实时间顺序蕴含 时间戳顺序。等待时间约为 2ε。
-
动手。 让我们的 MapReduce 在主节点崩溃后仍能完成。
解答
解答要点。 主节点的状态就是任务表:每个任务的状态(空闲、进行中、完成)、所在工作机,以及已完成 map 的输出位置。把每次 变更追加到稳定存储上的日志(或用第 38 部分的 Raft 复制)。重启时重放日志;进行中的任务重置为空闲(其工作机可能也已死), 工作机已不在的已完成 map 像工作机故障时一样重置。由于任务是确定性的、reduce 采用它拿到的任意一份 map 输出,重复执行不改变结果。 测试方法:在随机时刻让主节点崩溃,把前二十个词与参考答案比较。
-
★ 研究。 为我们的亚稳态模拟器设计一种重试与准入策略,可证明地从任何有限的突发中恢复,同时保留对冲请求的尾延迟收益。
讨论。 一般情形尚未解决。方向:重试预算(重试最多占首次请求的 β 比例)把负载限制在 (1 + β)λ,于是若 (1 + β)λ < μ, 任何突发之后队列都稳定;丢弃已过截止时间的请求限制了队列中的有用工作;对冲请求计入同一预算。缺少的是对真实客户端 (超时、退避、多层)的证明,以及对每种策略能承受的最大突发的刻画,最好在我们的模拟器中用对抗性选择的突发来检验。
Build the film
python -m videos.cs.cs39.compute # the part's numbers, into .cache/cs39
python tools/build.py cs39 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs39 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs39. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs39.compute
python -m unittest tests.test_cs39_scale tests.test_cs39_replicas
python tools/build.py cs39