System Design II: Case Studies
What is the one hard idea inside each of eight systems that almost everyone uses?
The part opens with eight systems and the eight ideas they turn on: the birthday bound, fan-out, logical clocks, Bloom filters, the assignment problem, control loops, idempotency and CRDTs. Each system is designed by Part 48's method, from the napkin to the hard part examined with numbers. A URL shortener needs seven base-62 characters for a trillion links, and a truncated hash collides often enough that every write must check. A news feed on a synthetic power-law graph of 100,000 users costs 6.9 million timeline writes a day pushed and 276 million fetches pulled, and the hybrid turns out to buy a bound on one post's fan-out, not fewer operations. A chat service orders messages by the conversation's sequence numbers, a crawler stays polite and forgets nothing with a Bloom filter, a dispatcher's optimal assignment beats the nearest driver, and three video players trade bitrate against stalls. A ledger that sums to zero still charges 1,390 payments twice until idempotency keys are added, and concurrent edits converge only when they are transformed. A Dynamo-style store and a metrics pipeline follow, the Job runs at a million books a day, and the frontier asks how designs fail and whether design can be checked before it is built.
What you need. Logarithms and the idea of a probability; the systems themselves are familiar from daily use.
- Mathematics, ideas and history
- URL shortener, news feed fan-out, chat, web crawler, ride-hailing dispatch, video streaming (adaptive bitrate), payment ledgers, collaborative editing, a Dynamo-style store
- What we build or compute
- eight designs simulated; the Job at a million books a day
What you will be able to do
Degree
- Compute how many base-62 characters N links need, and convert a number to its code by repeated division.
- Explain why a conversation's sequence numbers order messages where the senders' clocks do not.
- Write a payment as balanced ledger lines in cents and check that the entry sums to zero.
Graduate
- Derive the daily cost of fan-out on write, on read and of the hybrid over a power-law follower graph, and show that their ratio is reads over posts.
- Transform two concurrent inserts so that both sites converge, and exhibit the divergence without transformation.
- Compute the chance of a stale read for a quorum setting (N, R, W), and say when it is zero.
Research
- Explain why the count of operations gives the hybrid feed no interior optimum, and name what must be priced for a finite threshold to appear.
- Summarize what studies of post-mortems say about how designs fail, and what formal models and deterministic simulation can check before a system is built.
Industry
- Size a crawler, a chat service or a metrics pipeline on a napkin: rates, connections, storage, machines.
- Make a payment API safe to retry with an idempotency key stored in the same transaction as its reply.
- Compare adaptive-bitrate players by mean bitrate, seconds stalled and quality switches on the same traces.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 20 min · Graduate 49 min · Research 51 min · Industry 45 min.
- 0Eight systems everyone usesDegree1 min
- 1A URL shortenerDegree4 min
- 2A news feed: fan-outDegree4 min
- 3A news feed: ranking and readingIndustry4 min
- 4A chat serviceDegree4 min
- 5A web crawlerIndustry4 min
- 6Ride-hailing dispatchIndustry4 min
- 7A video platformIndustry4 min
- 8A payment ledgerDegree4 min
- 9A collaborative editorGraduate4 min
- 10A Dynamo-style key-value storeIndustry4 min
- 11A metrics pipelineIndustry4 min
- 12The Job at a million books a dayIndustry2 min
- 13Frontier: how designs fail, and what is unknownResearch2 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.
Eight systems everyone usesDegree1 min
This part designs eight systems that almost everyone uses. A URL shortener, a news feed, a chat service and a web crawler. A ride-hailing dispatcher, a video platform, a payment ledger and a collaborative editor. Each one turns on a single hard idea, and every one of those ideas is something this series has already built: the birthday bound, fan-out, logical clocks, Bloom filters, the assignment problem, control loops, idempotency and CRDTs. Each design starts on a napkin and ends in a simulation.
Every case follows the method of Part 48. Requirements first: what the system must do, and how well, in numbers. Then the napkin: peak queries per second, storage and bandwidth. Then the interface and the data model, the calls and the keys. Then a high-level design built from the blocks, with one request traced through it. Then the hard part, the one place where the design could fail, examined with numbers. And last, the trade-offs it forced, because there is never a design without them.
1A URL shortenerDegree4 min
A URL shortener has two calls. One turns a long address into a short code; the other redirects from the code to the address. Links must last for years, and redirects must be fast. On the napkin, suppose a hundred million new links a month: about 39 a second. If each is followed a hundred times, that is about 3,858 redirects a second, three times that at the peak: overwhelmingly read-heavy. Five years make six billion links, and at five hundred bytes each, three terabytes, before replication.
How short can the code be? Letters in both cases and digits make sixty-two symbols, so N links need the logarithm of N to base sixty-two characters, rounded up. A million links fit in four characters, a billion in six, a trillion in seven. Converting a number is Part 4's positional notation: divide by sixty-two again and again, and the remainders, read upwards, are the digits of the trillionth link. Our six billion links need only six characters. The length was never the problem. Choosing each link's number is.
The design uses Part 48's blocks. A click reaches a load balancer, Maglev hashing, which spreads requests over stateless app servers. Behind them sit a cache, and a key-value store mapping codes to addresses, the Dynamo-style store of chapter ten. Follow a read. An app server asks the cache, where a hot code almost always is, and answers with a redirect; a record of the click goes onto a log, Part 46's streams, where a job counts clicks per link. A write is rarer. The app server takes the next number from a block of a million that a coordinator handed it, stores the code and address, and returns the code.
There are three ways to choose the number. The first hashes the address and keeps k characters. By Part 17's birthday bound, collisions come long before the space is full: with six characters, about nine among a million links, eighty-eight thousand among a hundred million. So every write must check the store and retry on a clash. The second is a counter, handed out in blocks: no checks, the shortest codes, but consecutive codes are guessable. The third is Part 48's Snowflake identifier: no coordination at all, but its sixty-four bits take 11 characters. A common choice is the counter, passed through a fixed scrambling bijection when codes must not be guessable.
The redirect itself is a choice, from Part 42's HTTP caching. A three-oh-one says the move is permanent. Browsers and edge caches remember it, and the second click never reaches us: cheap, but we lose the analytics and can never repoint the link. A three-oh-two says temporary, so every click comes back and is counted. Zipf's law makes that affordable: a few links get most clicks. On Part 48's Zipf traffic, a cache holding one percent of the items catches 43 percent of requests, and ten percent catches 65. The trade-off is our servers' load against the data and control we keep; a three-oh-one with a short cache lifetime sits in between.
2A news feed: fan-outDegree4 min
A news feed shows each user the recent posts of everyone they follow. The data is a follower graph, and real follower graphs follow a power law: most accounts have a few dozen followers, and a handful have millions. Our instrument draws a synthetic graph of 100,000 users from such a law. The median account has 37 followers, but the mean is 138, pulled up by the giants, and the largest is followed by everyone. Each user posts half a time a day and opens the timeline twenty times: fifty thousand posts against two million reads. The question is when to do the work of putting those posts together.
There are two ways. Fan-out on write, or push: when someone posts, write the post into the timeline of every follower, so that reading a timeline is a single fetch. Fan-out on read, or pull: store each post once, with its author, and at every read gather the recent posts of everyone the reader follows. On our graph, push costs fifty thousand posts times 138 followers, about 6.9 million timeline writes a day. Pull costs two million reads times 138 followees, about 276 million fetches. Every follow is one follower and one followee, so the two averages are equal, and the ratio is just reads over posts: 40 times. Read-heavy, so push wins on total work.
Push has a flaw, and it lives at the top of the power law. When the largest account posts, the system must write 99,999 timelines, a burst of work on the timeline store, and the last follower sees the post only when the last write lands. On a log scale the gap is plain: the median post fans out to 37 timelines, the mean to 138, and the largest to all of them. One such post costs as much as 2,703 ordinary ones. And the giants are few but heavy: the 119 accounts with at least ten thousand followers, about a tenth of a percent of users, receive 27 percent of all follows. Real networks have accounts with tens of millions of followers.
The cure is a hybrid. Push the posts of ordinary accounts, and pull the posts of accounts above a threshold at read time, merging them in. Our instrument counts both kinds of work for each threshold. Counted in operations, pure push is still cheapest: pulling the 119 giants multiplies the total about 12 fold, because pulls happen at every read. What the hybrid buys is the worst case. No post now fans out to more than 9,833 timelines, and the pulled posts are the same few hot items read by everyone, which a cache serves almost for free. Silberstein and colleagues made the choice per pair in 2010, comparing how often the author posts with how often the reader reads. The trade-off is total work against the tail.
3A news feed: ranking and readingIndustry4 min
Chapter two decided how posts reach a timeline. Now read one. The reader's request reaches a stateless timeline service. It fetches the reader's timeline from a cache, a list of post identifiers that pushes have filled, and the latest posts of the few giants the reader follows, which are pulled. It merges the two lists, newest first, then hydrates them: looks each identifier up in the post store to get its text and author. A ranker orders them, and a page of twenty goes back. Timelines hold identifiers, not copies. Twitter described keeping about eight hundred per timeline in 2013; for our hundred thousand users, at eight bytes each, that is about 640 megabytes. And deleting a post is one write, not one per follower.
The newest post is rarely the one a reader most wants. Here are six candidates, newest first, with made-up numbers. Facebook's EdgeRank, described in 2010, scored each one as a product: the reader's affinity with the author, a weight for the kind of post, and a decay with age. Sorted by score, the order changes completely: the top is no longer the newest post, and a close friend's photo from sixteen hours ago outranks a stranger's from an hour ago. Modern feeds replace the hand-made product with learned models that predict each action a reader might take, Part 47's learning to rank, in two stages: a cheap one to choose candidates, and an expensive one to order the survivors.
A reader scrolls, and the app asks for the next page. Here is a timeline, newest first, and the first page of four. While the reader looks at it, two new posts arrive at the top. If the next page is requested by offset, skip four and take four, the list has moved: the reader sees 2 posts again, and the database still walks past every skipped row, the problem of Part 43. A cursor instead says where the last page ended: everything older than this post. It is a position in the data, found with one index seek, and new posts at the top cannot disturb it. A ranked feed reorders between pages as well, so its cursor names a snapshot of the ranked list, cached for the session, and a position within it.
One more anomaly, from Part 39's replication. You post. The write goes to the leader, and replicas catch up a moment later. You open your timeline at once, the read lands on a replica that has not caught up, and your post is not there. So you post it again. There are three cures. Read from the leader for a minute after you write. Or carry the position of your last write, and have a replica answer only once it has applied that position, one of Part 39's session guarantees. Or let the app show your own post itself. Only the writer needs the guarantee. Everyone else can see the post a second late, and the feed stays cheap.
4A chat serviceDegree4 min
A chat service carries one-to-one and group messages. Each must arrive exactly once, in order, on every device, including phones that were off, with receipts and end-to-end encryption. Suppose a hundred million daily users sending forty messages each: about 46,000 a second, three times that at the peak. The bodies are small, about 400 gigabytes a day. The unusual number is connections: a waiting phone keeps one open, so fifty million are open at the peak. WhatsApp reported two million on one server in 2012, so twenty-five machines could in principle hold them; a real fleet is larger.
Here is the design. Each phone keeps a WebSocket open to a gateway: one long-lived connection on which the server can send without being asked. Gateways hold connections and nothing else, so they can be many and simple. Ana sends. Her gateway passes the message to the chat service, partitioned by conversation, which appends it to that conversation's log. A session registry, with short leases, says Ben's phone is on gateway three, and the message goes down that connection. If Ben's phone is asleep, the push service wakes it through the phone maker's notification system, and the phone connects and fetches what it missed.
The hard part is order. Ben asks, dinner at eight? Ana reads it and answers yes. But her phone's clock runs three seconds slow, so her answer is stamped earlier than his question. Sorted by the phones' clocks, the answer comes first. Server clocks differ too, as Part 38 showed: unsynchronised clocks cannot order events reliably. The fix is a sequence number. Each conversation has one owner, its partition's leader, which numbers messages as they arrive. Ana answered after seeing forty-one, so her answer gets a larger number. The order holds within a conversation only, which is all a reader sees, and a retried send carries the same client identifier, Part 43's idempotency key, and keeps its number.
Sequence numbers also give receipts and offline sync almost for free. Each conversation's log is numbered. Ben's phone acknowledges what it has received, up to forty-four: that is the second tick, delivered. When Ben has looked, his phone reports read up to forty-two. Each receipt is a watermark, one number per member and device, not a record per message. Now Ben's phone is switched off, and three more messages arrive. When it reconnects it asks for everything after forty-four, and gets exactly the three it missed. And a phone that holds forty-four and suddenly receives forty-six knows that forty-five is missing, and asks for it.
Two last pieces. A group message is stored once and fanned out to every member, the push of chapter two, with pulls for very large groups. With end-to-end encryption the server only ever relays ciphertext. Between two devices, Signal's double ratchet, published by Trevor Perrin and Moxie Marlinspike in 2016, derives each message's key by hashing the previous chain key, Part 29, and deletes it after use, so a stolen phone cannot read old messages. Each reply also mixes in a fresh Diffie-Hellman exchange, Part 30, which locks a thief out of new ones. WhatsApp's groups use sender keys, distributed pairwise once, so a message is encrypted once. The price: the server cannot search or filter content, and every extra device is another recipient.
5A web crawlerIndustry4 min
Requirements first. A search engine, like the one of Part 47, wants a billion pages fetched every month, politely, and never the same page twice. A billion pages in thirty days is about three hundred and eighty-six pages a second. If a fetch takes half a second, about a hundred and ninety-three are in flight at once; at a hundred kilobytes a page, that is about a third of a gigabit a second, and one machine could carry it. What makes the crawler hard is manners. A polite crawler asks any one host for at most one page a second, so to keep its rate it must be busy with at least three hundred and eighty-six different hosts at once. And it must remember every URL it has seen: a billion of them.
The design is a loop. Seed URLs enter the frontier, the list of pages still to fetch. A fetcher takes one, looks up its host name and downloads the page, and the parser stores it. Name lookups would dominate if done naively, so every fetcher keeps a DNS cache, Part 37's resolver; Mercator, the crawler Allan Heydon and Marc Najork described in 1999, found lookups slow enough to write its own resolver. The parser also extracts the page's links. Each is checked against the set of URLs already seen, and only new ones go back to the frontier. Across machines the work is split by a hash of the host name, so everything about one host lives on one machine, and a link to another host is forwarded to the machine that owns it.
The frontier is the heart of a crawler, and Mercator's design of it is still the textbook one. New URLs are first sorted by priority, by importance or how often a page changes, into a few front queues. Behind them sit back queues, one for each host, each holding only that host's URLs. A heap, the priority queue of Part 17, keyed by the earliest time each host may be visited again, decides what is fetched next. Pop the host whose time has come, fetch the URL at the head of its queue, and push the host back with a new time. The new time is the politeness rule: here one request a second; a common heuristic waits several times as long as the last fetch took, so a struggling server is asked less often.
And the crawler must not fetch a page twice. The seen set is a Bloom filter, from Part 20: each URL sets a few bits, chosen by independent hashes. A new URL whose bits are all set is reported as seen, sometimes wrongly: these three were set by two other URLs. We measured our filter: two hundred thousand URLs at nine point six bits each and seven hashes gave one point zero zero five percent false positives, against zero point nine nine seven from the formula. For a billion URLs that is one point two gigabytes, in memory. A false positive costs a page never fetched; there are no false negatives, so nothing is fetched twice. Different URLs often serve the same text, so crawlers also fingerprint content. With Moses Charikar's SimHash, similar pages get fingerprints a few bits apart, and Gurmeet Manku and colleagues at Google reported in 2007 that sixty-four bits, at most three differing, worked across eight billion pages.
6Ride-hailing dispatchIndustry4 min
A dispatcher must know where every driver is, all the time. Say a million drivers are online, each phone reporting its position every four seconds: that is two hundred and fifty thousand writes a second, each one replacing the last. So the hot store keeps only each driver's latest position, in memory, indexed by map cell, and lets stale entries expire; the history goes to a log, as in Part 46. The cells are hexagons, as in Uber's H3 index from Part 48. A hexagon's six neighbours are all the same distance away, so the drivers near a rider are simply those in the rider's cell and the ring around it.
Here is the whole service. Phones keep a connection open to a gateway, the same connection servers as the chat of Chapter 4. On the write path, drivers' pings flow through a location service that overwrites each driver's entry in the geo index. On the read path, a rider's request reaches dispatch, which asks the index for the drivers in the nearby cells, ranks them by driving time from the ETA service, and sends the chosen driver an offer over the connection that driver already has open. If the driver declines or does not answer within a few seconds, the offer moves to the next.
The hard idea: which driver takes which rider? The obvious rule is greedy: as each request arrives, give it the nearest free driver. Here rider A arrives first and takes the only driver near B, so B gets the far one. Collect both requests and match them together, and the total is smaller. Matching a batch is the assignment problem of Part 18, solved exactly; Harold Kuhn's Hungarian algorithm of 1955 was the first, and our solver reaches the same optimum by a faster modern method. We simulated it: sixty riders and seventy drivers scattered over a ten-kilometre city, two hundred times. Greedy's mean pickup was one point one seven kilometres; batched, zero point nine six. The worst pickup in each round fell much more, from four point eight to three point zero, because greedy's last riders get whatever is left. The price is a batching window of a few seconds.
To choose among drivers, dispatch needs driving times, thousands a second. Contraction hierarchies, from Robert Geisberger and colleagues in 2008, prepare the road graph in advance. Remove the least important junction; wherever the shortest path between two of its neighbours ran through it, add a shortcut of the same length. Repeat for every junction, in order of importance, and the graph gains a hierarchy of shortcuts. A query then runs Dijkstra's search from both ends, each only climbing upward, and the two meet near the top. As Part 18 measured, such a query settles a small fraction of the junctions that plain Dijkstra would.
The last piece is economic. In each cell, every minute or two, the system compares open requests with free drivers. The price settles where supply and demand cross. When a concert ends, demand jumps, and at the old price there are not enough drivers. A higher price clears the market: it draws drivers in and persuades some riders to wait. Jonathan Hall, Cory Kendrick and Chris Nosko compared, in 2015, a night when Uber's surge pricing worked with one when it briefly failed: without it, fewer requests were completed and waits grew. The trade-off here is not technical: efficiency against fairness, and so surge is capped in emergencies.
7A video platformIndustry4 min
A video platform must start quickly, never stall, and look as good as each viewer's connection allows. So every upload is encoded several times, into a ladder of qualities, here six from zero point three to four point three megabits a second, and each version is cut into segments two seconds long. A manifest lists them: Apple's HTTP Live Streaming, from 2009, and the MPEG-DASH standard of 2012 work this way. Every segment is an ordinary file fetched over HTTP, so the caches of Part 42 serve video as they serve anything else. The player chooses a rung for every segment; here are the choices our buffer-based player made. The napkin: an hour at the top rung is about one point nine gigabytes to send, and storing every rung costs about five gigabytes per hour of video.
The design follows. An upload goes into a queue, and encoders work through it. Because segments are independent, one title is encoded by many machines at once, a batch job of the kind Part 45 rents by the minute. The finished segments sit in a blob store, the origin, and are served through the content delivery network of Part 42. Popularity follows a Zipf law, as Part 37 found for words: a few titles take most of the views, so the edges hold the head, and a request for something in the long tail travels back to the origin. Netflix goes further: its Open Connect caches sit inside internet providers' own networks, filled overnight with what is likely to be watched the next day.
Choosing the rung is a control problem, the same shape as Part 37's congestion control: act, observe, adjust. The grey line is the bandwidth of one simulated connection, wandering between good, fair and poor. The obvious controller is rate-based: estimate the throughput of recent downloads and pick the highest rung beneath it. But estimates are noisy, and a wrong guess drains the buffer. Te-Yuan Huang and colleagues at Netflix argued in 2014 for choosing from the buffer alone: the lowest rung while the buffer is below a reservoir, the highest once it passes a cushion, and a straight line between. Here is that player: its quality follows its buffer. Xiaoqi Yin and colleagues, in 2015, used model predictive control: predict the bandwidth, try each bitrate held over the next five segments, choosing the one that maximizes quality minus penalties for stalls and switches, take the first step, and plan again.
We ran all three on five synthetic ten-minute traces. Mean quality: rate-based two point three three megabits a second, buffer-based two point six six, MPC two point seven nine. Stalls: the buffer-based player never stalled at all. The rate-based player stalled for about three seconds, and our MPC for about five: it bought the best picture by trusting its forecast and keeping less in reserve, so sudden drops caught it. Yin and colleagues, with a better predictor, found MPC ahead. All three switched quality between fifty and sixty-five times. Which matters most? Florin Dobrian and colleagues found in 2011 that, of the quality measures they studied, time spent rebuffering hurt viewers' engagement most. How to weigh picture against stalls is a product decision, written into the controller's objective.
8A payment ledgerDegree4 min
A payment system is first of all a ledger, kept the way accountants have kept books for five hundred years. Every payment is a journal entry with several lines: fifty dollars leave the customer, forty-eight fifty reach the merchant, and a dollar fifty goes to fees. The lines sum to zero. Amounts are whole numbers of cents, never floating point, as Part 4 warned. A second payment, the same way. Because every entry sums to zero, the whole ledger does, by the induction of Part 2: money is moved, never made or lost. Entries are only ever appended. A mistake is fixed by a new entry that reverses it, so the ledger is its own audit trail.
The design. A client asks the payments API to charge fifty dollars. The API writes the ledger entry to a single-leader database, and an outbox, Part 43's pattern, carries the request to the card processor. Then the reply is lost. The client cannot know whether the charge happened, so it must retry, and a naive server would charge twice. The cure is an idempotency key. The client chooses one key per payment and sends it with every attempt. The server records the key and its result in the same transaction as the ledger entry, so a repeat finds the key and returns the stored reply instead of charging again. Pat Helland put it simply in 2012: in a world of retries, every request should be idempotent.
We simulated it with our ledger instrument: five thousand payments of random amounts, where some attempts time out and are retried and some are declined. Without keys, six thousand two hundred and nine entries were posted, and one thousand three hundred and ninety payments, nearly three in ten, were charged twice. With keys, no payment was charged twice. Now look at the invariant. Both ledgers sum to exactly zero. Every double charge was itself a perfectly balanced entry, so the books balance and are still wrong. Balance is one invariant; at most one entry per payment is another, and only the key table enforces it.
A card payment is a state machine. It is created; the card's bank authorizes it, placing a hold; the merchant captures it, and money moves; days later it settles, and the cash arrives. Along the way it can be declined, voided before capture, or refunded after. Transitions only go forward, and each is a compare-and-set on the current state, so a duplicate capture finds the payment already captured and does nothing. The state change, its ledger lines and the outbox message are written in one database transaction, from Part 35, so none is ever seen without the others.
Two more duties remain. The ledger is only our account of events; the processor and the banks keep theirs. Every day, each of our entries is matched against the processor's settlement file. Most agree. Some do not: an amount that differs, an entry one side has and the other lacks. These go to a queue for people. The last trade-off is the one Part 39 named. During a network partition, a ledger refuses to write rather than let two replicas disagree about a balance; it chooses consistency over availability. Availability is won back at the edge: accept the request, answer pending, and let the outbox finish the work when the ledger can.
9A collaborative editorGraduate4 min
A collaborative editor lets several people type into one document at once. Every keystroke must appear at once on the typist's own screen; nobody waits for a server. When the typing stops, every copy must hold the same text: convergence. And each edit should land where its author meant it, whatever others typed meanwhile. The design is small. Editors hold WebSocket connections to a collaboration server, which relays each operation and appends it to a log, compacted into snapshots. The load is tiny, perhaps fifty operations a second for a busy document. The hard part is order.
Here is why order is hard. Two people share the text, the cat sat. At the same moment, A inserts the letter z at position one, and B appends an x at position eleven, the end. Then each applies the other's operation as sent. At B, that is still right. But at A, position eleven no longer means the end: the z pushed everything one place right, so the x lands between the a and the t. Two copies, two texts. A position only means something in the state it was made in.
Operational transformation, from Clarence Ellis and Simon Gibbs in 1989, repairs an operation before applying it. A transforms B's insert at eleven against its own concurrent insert at one. That came earlier in the text, so B's position shifts right, to twelve. Now both copies agree. The rules are few: an insert before you pushes you right, a delete before you pulls you left, and a tie is settled by a fixed priority between sites. Over five thousand random pairs of concurrent edits, transformation converged every time; applied as sent, only about six in a hundred did. With many sites the original algorithm was later found to diverge, so Jupiter, in 1995, and later Google Docs route every operation through one server, which fixes a single order.
The other answer is to stop using positions. In a sequence CRDT, here the replicated growable array of Roh and colleagues, 2011, every character gets a permanent name: a counter, and the replica that made it. An insert names the character it goes after. Here two people type after the t at once. A fixed rule decides: the larger name comes first, on every replica, in any arrival order. A deleted character stays as a tombstone, so later inserts can still name it. In fifty sessions of three people making thirty edits, delivered in a random order that respects causality, the array always converged. Replaying positions as sent, no session did.
Cursors raise the same question. B's cursor sits before the s of sat. Stored as an offset, eight, it points into cat once A types big in front. Anchored to the name of the s, it moves with the text. Presence, who is here and where each cursor is, shares those connections but is never logged: a lost update is replaced by the next. So which to choose? Transformation keeps operations and documents small, but wants one server to fix the order. A CRDT merges in any order, offline or peer to peer, as in Yjs and Automerge, and pays with the names and tombstones the document keeps, as Part 39 measured.
10A Dynamo-style key-value storeIndustry4 min
In 2007 Giuseppe DeCandia and colleagues at Amazon described Dynamo, the store behind the shopping cart. Adding to a cart must succeed even while machines and networks fail. The interface is two calls, get and put, with a context that carries version information. Latency is promised at the ninety-nine point nine percentile, not the mean: three hundred milliseconds, in the paper's example. There is no master. Every node is equal, and the cluster grows a machine at a time. On a napkin, a billion two-kilobyte values, three copies, on half-full one-terabyte disks, need twelve machines.
Dynamo partitions keys by consistent hashing, from Part 39. Keys and nodes are hashed onto one ring, and many virtual nodes per machine even out the load. Walk clockwise from a key: the first N distinct nodes, here three, hold its copies. That is its preference list. A put goes to the first, the coordinator, which writes locally and forwards to the others. It answers as soon as W copies, here two, are written; the third catches up. A get likewise waits for R replies. And adding a machine moves only the keys on its new arcs.
How many replies are enough? If a write waits for W copies and a read for R, and R plus W exceeds N, every read set overlaps every write set, so a read always meets the latest write. Three, two, two is the setting the Dynamo paper reports as common. With R and W both one, the sets can miss. We simulated reads with Part 39's model of replication delays. Right after a write is acknowledged, with N three and R and W one, a read returns the old value fifty-three percent of the time; ten milliseconds later, nineteen percent. With overlapping quorums, never. Small quorums buy speed with staleness.
At this scale machines fail constantly, and Dynamo keeps writing through it. Suppose D, in the key's preference list, is down. Rather than refuse, the coordinator sends D's copy to the next healthy node, F, with a hint saying whom it is for: a sloppy quorum. When D returns, F hands the copy over and deletes its own. That is hinted handoff. Replicas still drift apart, so in the background they compare Merkle trees, hash trees over their key ranges. Equal roots mean equal data. Where hashes differ, descend, and exchange only those ranges: the cost grows with the differences, not with the data.
Because any node can accept a write, two clients can update one cart while the network is split. Dynamo tags every version with a version vector, Part 38's vector clock, one counter per coordinating node. Here two versions descend from the second through different nodes, and neither has seen the other. A get returns both, as siblings, and the cart merges them by union; as the paper notes, a removed item can come back. The quorum sizes are a dial, from fast and always writable but sometimes stale, to fresh but slower. Dynamo chose availability, and Cassandra and Riak followed. A payment ledger, from chapter eight, could not.
11A metrics pipelineIndustry4 min
Every service in a large system reports numbers about itself: requests, errors, latencies, queue depths. Each sample is a metric's name, a set of labels, a time and a value. Agents scrape or receive the samples and push them into a log, Part 46's, which absorbs bursts. Ingesters shard them by a hash of the series and append them to a time-series store, and a downsampler moves older data to object storage. The workload is unusual. Writes far outnumber reads, samples arrive in time order and are never updated, recent data is read most, and queries aggregate across time and labels.
The hard part of a metrics system is not the rate of samples but the number of series. A series is a metric's name plus one value for each of its labels, and every distinct combination is stored separately. Start with fifty services. Label each request with its endpoint, forty each, and there are two thousand series; with its status, twelve thousand; with its region, ninety-six thousand. Add the pod, two hundred of them, and one metric becomes nineteen point two million series. Add a user identifier, for a million users, and it is about nineteen trillion, which no time-series store can hold. Questions about one user belong in logs and traces.
Now the napkin. Take those nineteen point two million series and sample each every ten seconds: about two million samples a second, a hundred and sixty-six billion a day. Stored plainly, eight bytes of time and eight of value, that is over two and a half terabytes a day. Facebook's Gorilla, described by Tuomas Pelkonen and colleagues in 2015, compressed samples to one point three seven bytes each on average. Timestamps arrive at a steady rhythm, so it stores the change in the gap, usually zero, in a single bit. Values change slowly, so it stores each value's exclusive or with the previous one, again usually zero. That brings our day down to about two hundred and twenty-seven gigabytes.
Old data is read less often, and less finely, so it is downsampled. Here is an hour of one series at ten-second resolution, three hundred and sixty points. Cut it into five-minute buckets, and keep four numbers for each: the minimum, the maximum, the sum and the count. The mean alone would have hidden this spike; the maximum keeps it. Sums and counts still give exact averages and rates over any longer window. But percentiles cannot be combined: the average of two ninety-ninth percentiles is not a ninety-ninth percentile. For latency, keep a histogram or a mergeable sketch in each bucket, which Part 50 builds.
Put together, the store keeps tiers. The last fifteen days at full ten-second resolution, in memory and on fast disks. Ninety days of one-minute buckets on ordinary disks, and two years of hourly buckets in cheap object storage, Part 45's blob store. For one series that is about seven hundred thousand numbers instead of six point three million: nearly nine times fewer, with every dashboard still drawable. The trade-off is detail against cost, and the costliest knob is cardinality, so teams are given a budget of series. Part 50 builds its service-level objectives and alerts on exactly this pipeline.
12The Job at a million books a dayIndustry2 min
Scale the Job up to a million books a day. A million uploads a day is about eleven and a half a second. If each book's results are read twenty times, that is about two hundred and thirty reads a second, and with a cache answering sixty percent of them, most cost nothing. At an evening peak of three times the mean, the workers must count about 313 books a second. At eighty milliseconds a book, and keeping them sixty percent busy so the queue stays short, that is 42 workers. And storing the text and its results, at six hundred kilobytes a book, grows by about 219 terabytes a year.
Then we simulated an hour at the peak. The median count that reaches a worker finishes in about 56 milliseconds, and the ninety-ninth percentile in about 372: the long tail of an exponential service time, not of queueing, because the workers are only sixty percent busy. 42 workers rented at Part 45's list price cost about 2,903 dollars a month, which is about a hundredth of a cent per book. Storage, the network and above all the people who run it would cost more. But the counting itself, the thing this series has been optimizing since Part 6, is now almost free.
The ledger gets row eighteen. On this service the thirty novels are thirty requests running in parallel, and the slowest of thirty counts sets the time: about a third of a second, for about 3 thousandths of a dollar. Part 6's single Pebble took two hundred and eighty seconds. Every layer of the series in between, pipelines, caches, compilers, algorithms, networks and services, is somewhere in that factor.
13Frontier: how designs fail, and what is unknownResearch2 min
What do real outages teach, that designs miss? Real outages are studied the way accidents are. Ding Yuan and colleagues analysed failures in five widely used distributed systems in 2014, and found that most of the catastrophic ones came from mishandling errors that were not fatal in themselves, often in code that no test had ever run. Google's site reliability engineers estimate that about seventy percent of their outages are caused by changes to a live system: deploys, configuration and migrations. And Haryadi Gunawi and colleagues read hundreds of public reports of cloud outages: upgrades, configuration, overload and cascading failures recur; plain hardware failure rarely causes them alone. Designs are drawn for the happy path. Outages live in the error paths, the changes, and the coupling between the blocks.
Every design in this part was a set of choices among the same few trade-offs. How consistent it must be, from eventual for a feed to strict for a ledger. How fast it must answer. What dominates its cost: storage and bandwidth for video, fan-out for a feed. And how much complexity it carries, which is also how much can go wrong in operation. The table is a summary, not a measurement. Its point is that no design is good in every column, and that a good design knows which columns it has given up.
System design is starting to become a subject of research in its own right. Lightweight formal models, in TLA-plus or the P language, are written and model-checked before code, as Amazon and Microsoft now do for storage and messaging services. Deterministic simulation runs a whole system against simulated networks, disks and clocks, injecting failures from a random seed so that every bug can be replayed. And tools are appearing that propose designs and capacity from requirements, language models among them, which deserve the same caution as Part 40's automated authors. What does not yet exist is a calculus of design: blocks with known guarantees, composed into systems whose guarantees follow.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. A shortener whose identifiers are sized by a logarithm and protected by the birthday bound. A feed whose fan-out is chosen on a power-law graph, pushing for most users and pulling for celebrities. A crawler that is fast only by being polite to many hosts at once. A dispatcher that assigns riders in batches rather than grabbing the nearest driver. Bitrate adaptation as a control loop that trades quality against stalls. A ledger whose entries always sum to zero, and whose payments are charged once. Editors that converge. And the Job, at a million books a day, for a hundredth of a cent a book. One idea runs through it: every design is a few hard ideas, and you have met them all before.
Where this comes back. Part 50 runs these systems, with service-level objectives, incident response and capacity planning. Part 51 opens the graphics and video pipelines behind the streaming service. Part 54 proves protocols and ledgers correct. Part 55 asks whether we can trust the software these systems run on. And Part 59 returns to the theory of distributed algorithms underneath them all.
In practice. Write requirements and do the napkin arithmetic before drawing any boxes. Find the one hard part of the problem and spend your design effort there. Name every trade-off you make, and what you gave up for it. Design the error paths and the way changes are deployed, not only the happy path. And simulate the design under load and failure before you build it.
Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: add hinted handoff to a three-replica store and measure what it buys when one node is cut off. The last, marked with a star, is a research problem: the fan-out policy that provably minimizes a feed's work on a power-law graph.
Next time, Part 50: keeping it running. A system is only as good as its worst hour, and reliability engineering turns that into mathematics: availability composed in series and in parallel, error budgets that make reliability a resource to spend, alerts as hypothesis tests, and incidents and the post-mortems that learn from them.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 50 runs these systems, with service-level objectives, incident response and capacity planning, and uses the metrics pipeline. Part 51 opens the graphics and video pipelines behind the streaming service. Part 54 proves protocols and ledgers correct, and Part 59 returns to the theory of the distributed algorithms underneath.
Key results
The part's results in one place, for revision.
Try it
Lab 49 · Four designs under test: fan-out, dispatch, dedup and double entry
Cost a news feed on a power-law follower graph by pushing, pulling and the hybrid, match riders to drivers greedily and by optimal assignment, measure a Bloom filter's false positives against its formula, and replay payments with retries to see which invariant catches a double charge.
python -m videos.cs.labs 49
needs numpy, scipy, matplotlib · download lab49.py ·
source on GitHubfollower graph median 37, mean 138, largest 99,999
operations a day: push all, pull all 6.9 M, 276.0 M (ratio 40 = reads / posts)
hybrid, pull accounts with 100+ followers 213.1 M a day; pulls 16,953 accounts (power law: 17,027); worst post 99 writes
hybrid, pull accounts with 1,000+ followers 137.9 M a day; pulls 1,336 accounts (power law: 1,352); worst post 999 writes
hybrid, pull accounts with 10,000+ followers 79.5 M a day; pulls 119 accounts (power law: 107); worst post 9,833 writes
dispatch, 60 riders and 70 drivers mean pickup 1.20 km greedy, 0.99 km optimal; worst in a round 5.03 against 3.17 km
Bloom filter at 9.6 bits a URL 7 hashes, false positives 1.02% measured, 1.00% from the formula
3,000 payments with retries without keys 3,711 entries, 823 charged twice; with keys 2,909 and 0; both ledgers sum to 0
2,000 concurrent pairs of edits converged: transformed 100%, as sent 6.8%
Counted in operations pushing everything is cheapest and the hybrid buys only a bound on one post's fan-out; the optimal batch beats greedy; the filter errs as the formula says; and a ledger needs 'one entry per payment' beside 'sums to zero'.
The code (95 lines; it asserts its own result)
"""Lab 49: stress four case studies: a feed's fan-out, a dispatcher's matching, a crawler's Bloom filter, a ledger's retries."""
from videos.coursekit import labs # noqa: I001 (must stay first: it lets explainer.cs import without manim)
import math
import numpy as np
from explainer.cs.design import cases
TITLE = "Four designs under test: fan-out, dispatch, dedup and double entry"
GOAL = ("Cost a news feed on a power-law follower graph by pushing, pulling and the hybrid, match riders to drivers "
"greedily and by optimal assignment, measure a Bloom filter's false positives against its formula, and "
"replay payments with retries to see which invariant catches a double charge.")
TASKS = [
"Set reads_per_user_day to 0.2 in cases.feed_cost, so that people post more than they read. Which end of the threshold scale is cheapest now, and why does the ratio of pull to push equal reads over posts?",
"Give the dispatcher 60 riders and 61 drivers, then 60 and 200. How does the gap between greedy and optimal pickup distance change with spare drivers?",
"Run cases.ot_experiment with start='ab' and with a 40-character string. Why does applying operations as sent converge more often on the long string, and does transformation still converge every time?",
]
USERS, F_MIN, ALPHA = 100_000, 20, 2.1
def run(seed=0):
lab = labs.Lab()
# 1. fan-out on write, on read, and the hybrid at three thresholds
feed = cases.feed_cost(users=USERS, seed=seed)
ratio = feed["pull_reads"] / feed["push_writes"]
assert abs(ratio - feed["reads"] / feed["posts"]) < 1e-9, "pull over push is reads over posts: the means are equal"
hybrid = feed["hybrid"] # thresholds 100, 1,000, 10,000 and 'nobody is pulled'
totals = [h["total"] for h in hybrid]
assert all(a > b for a, b in zip(totals, totals[1:])), "with reads above posts, raising the threshold only saves"
assert abs(totals[-1] - feed["push_writes"]) < 1e-6 and all(h["max_fanout_per_post"] < h["threshold"] for h in hybrid)
lab.row("follower graph", f"median {feed['median_followers']:.0f}, mean {feed['mean_followers']:.0f}, "
f"largest {feed['max_followers']:,}")
lab.row("operations a day: push all, pull all", f"{feed['push_writes'] / 1e6:.1f} M, {feed['pull_reads'] / 1e6:.1f} M "
f"(ratio {ratio:.0f} = reads / posts)")
for h in hybrid[:3]:
model = USERS * (F_MIN / h["threshold"]) ** (ALPHA - 1) # accounts above the threshold under the Pareto law
assert abs(h["celebrities"] - model) < 5 * math.sqrt(model) + 5, "the tail follows the power law"
lab.row(f"hybrid, pull accounts with {h['threshold']:,}+ followers",
f"{h['total'] / 1e6:.1f} M a day; pulls {h['celebrities']:,} accounts (power law: {model:,.0f}); "
f"worst post {h['max_fanout_per_post']:,} writes")
# 2. dispatch: the optimal assignment of a batch against nearest free driver
d = cases.dispatch(riders=60, drivers=70, rounds=40, seed=seed + 2)
gain = d["batched_mean"] / d["greedy_mean"]
assert d["batched_mean"] < d["greedy_mean"] and 0.7 < gain < 0.92, "the assignment cuts the mean pickup by a sixth or so"
assert d["batched_worst"] < d["greedy_worst"]
lab.row("dispatch, 60 riders and 70 drivers", f"mean pickup {d['greedy_mean']:.2f} km greedy, {d['batched_mean']:.2f} km "
f"optimal; worst in a round {d['greedy_worst']:.2f} against {d['batched_worst']:.2f} km")
# 3. the crawler's Bloom filter against (1 - exp(-kn/m))^k
bits = (4.8, 7.2, 9.6, 12.0)
bloom = [cases.bloom_check(n=20_000, bits_per=b) for b in bits]
for b in bloom:
assert abs(b["false_positive"] - b["theory"]) < 4 * math.sqrt(b["theory"] / 20_000) + 0.001
lab.row("Bloom filter at 9.6 bits a URL", f"{bloom[2]['hashes']} hashes, false positives {bloom[2]['false_positive']:.2%} "
f"measured, {bloom[2]['theory']:.2%} from the formula")
# 4. the ledger: sum = 0 holds with and without idempotency keys, so it cannot see a double charge
keyed = cases.ledger(n=3000, seed=seed + 4, idempotent=True)
bare = cases.ledger(n=3000, seed=seed + 4, idempotent=False)
assert keyed["sum"] == 0 and bare["sum"] == 0 and keyed["double_charges"] == 0 and bare["double_charges"] > 100
assert keyed["entries"] <= 3000 and bare["entries"] - bare["double_charges"] <= 3000, "at most one first charge each"
lab.row("3,000 payments with retries", f"without keys {bare['entries']:,} entries, {bare['double_charges']} charged twice; "
f"with keys {keyed['entries']:,} and 0; both ledgers sum to {bare['sum']}")
ot = cases.ot_experiment(trials=2000, seed=seed + 5)
assert ot["converged_transformed"] == 1.0 and ot["converged_naive"] < 0.2
lab.row("2,000 concurrent pairs of edits", f"converged: transformed {ot['converged_transformed']:.0%}, as sent "
f"{ot['converged_naive']:.1%}")
lab.note = ("Counted in operations pushing everything is cheapest and the hybrid buys only a bound on one post's "
"fan-out; the optimal batch beats greedy; the filter errs as the formula says; and a ledger needs "
"'one entry per payment' beside 'sums to zero'.")
fig, ax = labs.figure(2, size=(11, 4.3))
names = ["pull all"] + [f"pull {h['threshold']:,}+" for h in hybrid[:3]] + ["push all"]
push = [0.0] + [h["push_writes"] / 1e6 for h in hybrid]
pull = [feed["pull_reads"] / 1e6] + [h["pull_reads"] / 1e6 for h in hybrid]
x = np.arange(5)
ax[0].bar(x, push, color=labs.BLUE, label="timeline writes (pushed)")
ax[0].bar(x, pull, bottom=push, color=labs.ORANGE, label="fetches at read time (pulled)")
ax[0].set(title="A feed's daily operations, by who is pulled", ylabel="millions a day")
ax[0].set_xticks(x, names)
ax[0].legend()
grid = np.linspace(4, 13, 60)
theory = [(1 - math.exp(-max(1, round(b * math.log(2))) / b)) ** max(1, round(b * math.log(2))) for b in grid]
ax[1].semilogy(grid, theory, color=labs.GOLD, label="(1 - exp(-kn/m))^k, k = round(0.69 m/n)")
ax[1].semilogy(bits, [b["false_positive"] for b in bloom], "o", color=labs.BLUE, label="measured on 20,000 URLs")
ax[1].axhline(0.01, color=labs.MUTED, ls="--", lw=1)
ax[1].set(title="A Bloom filter's false positives", xlabel="bits per URL", ylabel="false-positive rate")
ax[1].legend()
lab.fig = fig
return lab
Now change it
- Set reads_per_user_day to 0.2 in cases.feed_cost, so that people post more than they read. Which end of the threshold scale is cheapest now, and why does the ratio of pull to push equal reads over posts?
- Give the dispatcher 60 riders and 61 drivers, then 60 and 200. How does the gap between greedy and optimal pickup distance change with spare drivers?
- Run cases.ot_experiment with start='ab' and with a 40-character string. Why does applying operations as sent converge more often on the long string, and does transformation still converge every time?
Problems, with solutions
Try each problem before opening its solution.
-
Short IDs. How many base62 characters does a shortener need for 10¹² links, and how many collisions does a 7-character truncated hash give at 10⁸?
Solution
L characters give 62^L codes, so we need the least L with 62^L ≥ N: L = ⌈log₆₂ N⌉. For N = 10¹², log₆₂ 10¹² = 12/log₁₀ 62 = 12/1.7924 ≈ 6.69, so L = 7: 62⁶ = 56,800,235,584 is too few and 62⁷ = 3,521,614,606,208 leaves room for 2.5 trillion more. The trillionth link, by repeated division by 62, is
hBxM5A4. For a hash kept to k = 7 characters, model the m codes as independent and uniform over N = 62⁷ values. Each of the C(m, 2) pairs collides with probability 1/N, so by linearity the expected number of colliding pairs is C(m, 2)/N = m(m − 1)/(2N) ≈ m²/(2N); equivalently, inserting the links one at a time, the i-th lands on a used code with probability about (i − 1)/N, and the sum is the same. For m = 10⁸: 10¹⁶/(2 × 3.5216 × 10¹²) ≈ 1,420. Triple collisions add only about m³/(6N²) ≈ 0.013, and the chance of no collision at all is about e^(−1420): the collisions are certain, which is why every write must check the store and retry with a salt. The retries themselves are cheap (1,420 in a hundred million writes); the cost is the check on every write. At 10⁶ links the same hash gives 0.14; to bring 10⁸ links below one expected collision needs 62ᵏ > 5 × 10¹⁵, so k ≥ 9 (0.37). A counter handed out in blocks needs neither the check nor the extra characters. -
Fan-out. For followers drawn from a power law with exponent α, derive the expected cost of fan-out on write and on read, and the best celebrity threshold.
Solution
Take U users, each posting p and reading r times a day, with follower counts F independent and P(F > x) = (f_m/x)^(α−1) for x ≥ f_m (a density proportional to x^(−α)), capped at M = U − 1; our instrument has α = 2.1, f_m = 20, p = 0.5 and r = 20. Every follow is one follower and one followee, so the mean number of followees is also E[F]. Push writes each post into F timelines, E[F] per post and pUE[F] a day; pull fetches from every followee at each read, E[F] per read and rUE[F] a day; the ratio r/p = 40 does not depend on α. Integrating the density, E[F] = f_m(α − 1)/(α − 2) for α > 2 without the cap (220 here), and with the cap E[F] = f_m[(α − 1) − (f_m/M)^(α−2)]/(α − 2) = 134.7, against 138.0 measured (the standard error of the mean is about 4.6, since the standard deviation is 1,454). So push costs 50,000 × 138 ≈ 6.9 million writes a day and pull 276.0 million fetches. The mean hides the tail: for α < 3 the uncapped variance is infinite, and one post can cost 99,999 writes. The hybrid pushes accounts with F < τ and pulls the rest, which costs W(τ) = U[p E[F; F < τ] + r E[F; F ≥ τ]], with E[F; F ≥ τ] = f_m[(α − 1)(f_m/τ)^(α−2) − (f_m/M)^(α−2)]/(α − 2) and U(f_m/τ)^(α−1) accounts pulled. At τ = 100, 1,000 and 10,000 the model's share of follows going to pulled accounts is 76%, 47% and 24% (measured 77%, 49% and 27%), and it pulls 17,027, 1,352 and 107 accounts (measured 16,953, 1,336 and 119). Now W(τ) = U[pE[F] + (r − p)E[F; F ≥ τ]] decreases in τ whenever r > p: with every operation costing the same there is no interior optimum, and pushing everything is cheapest (6.9 million against 79.5 million at τ = 10,000). A finite best threshold appears only when something the count omits is priced. (a) A deadline: if a post must reach every follower within L seconds and a server writes s timelines a second, then τ ≤ sL, and since W decreases, τ* = sL; with the instrument's s = 50,000 (the largest account's post takes 2.0 s on one server) and L = 0.2 s, τ* = 10,000, pulling 119 accounts. (b) A price κ per unit of worst-case fan-out (capacity provisioned for the biggest burst), with a pushed write costing c_w and a pulled fetch c_r (cheap, since pulled posts are hot and cached): W(τ) = U[p c_w E[F; F < τ] + r c_r E[F; F ≥ τ]] + κτ, and since the density is (α − 1)f_m^(α−1)τ^(−α), W′(τ) = −U(r c_r − p c_w)(α − 1)f_m^(α−1)τ^(1−α) + κ. If r c_r > p c_w, W′ rises from negative values towards κ, so it crosses zero once, at a minimum: τ* = [U(α − 1)f_m^(α−1)(r c_r − p c_w)/κ]^(1/(α−1)), nearly proportional to U(r c_r − p c_w)/κ for α = 2.1 (the exponent is 0.91); if p c_w ≥ r c_r, W′ > 0 and everything is pulled. Silberstein et al.'s rule, push the pair (author u, reader v) when p_u c_w ≤ r_v c_r, is exact when edges cost independently, as in the linear model; with our uniform rates it pushes everything.
-
Batched dispatch. Show that a batched assignment never has a larger total pickup distance than greedy, and give an example where it is much smaller.
Solution
Fix a batch: riders R, free drivers D with |D| ≥ |R|, and distances d(r, x). Any rule that gives each rider a different driver defines an injective map σ: R → D, and greedy, in whatever arrival order, is one of them. The batched assignment minimizes Σ_r d(r, σ(r)) over all such maps, so its total is at most greedy's, with equality when greedy happens to be optimal. A family where greedy is exponentially worse lies on a line: drivers at d₀ = 0, d₁ = 2 − ε and d_k = 2d_(k−1) − ε; rider 1 at 1, then rider k at d_(k−1) for k = 2, …, n, in that order. Rider 1 takes d₁ (at 1 − ε, nearer than d₀ at 1); rider k finds d_(k−1) taken and takes d_k, at d_(k−1) − ε, just nearer than d₀ at d_(k−1). Greedy's total telescopes to d_n − 1 ≈ 2ⁿ − 1, while the batch sends rider 1 to d₀ and every other rider to the driver standing where it is: a total of 1. With ε = 0.001, n = 5 gives 30.97 against 1 and n = 10 gives 1,021.98 against 1. In our random city the gain is modest, a mean pickup of 1.17 km against 0.96 km (18% less), with the worst pickup in a round falling from 4.80 to 3.04 km; but minimizing the sum does not in general minimize the worst pickup, which is the bottleneck assignment problem. Two caveats: across successive windows, each optimal for the riders it holds, the comparison with greedy over a whole day is no longer a theorem, since earlier batches change which drivers later ones see; and the window itself adds waiting time.
-
The ledger. Prove that double-entry posting preserves Σ balances = 0, and that idempotency keys prevent double charges under retries.
Solution
Let the balances be B: accounts → ℤ (integers of cents, so sums are exact; in floating point a balanced entry can sum to a tiny non-zero amount). An entry is a list of lines (a_j, v_j) with Σ_j v_j = 0, which the instrument asserts when it builds each entry. Posting sets B′(a) = B(a) + Σ_(j: a_j = a) v_j, so Σ_a B′(a) = Σ_a B(a) + Σ_j v_j = Σ_a B(a). Initially every balance is 0, so by induction over the sequence of posted entries Σ B = 0 after each. This needs each entry posted atomically: if entries are transactions, every serializable execution is equivalent to some sequence, while a half-posted entry visible to a reader would break the invariant; and since entries are only appended, a correction is a new, reversing entry that also sums to zero. For idempotency, the server handles a request with key k in one transaction: if k is recorded, return the stored reply; otherwise post the entry and record (k, reply) under a unique index. Claim: at most one entry carries k. A transaction that posts for k also records k, so any later one finds k and posts nothing; two concurrent ones cannot both commit, since serializability (or the unique index) aborts one. The client sends the same key with every attempt of one payment, so all its retries share k and it is charged at most once. The argument needs the key chosen before the first attempt and kept by the client, never reused for another payment, retained by the server at least as long as retries can arrive, and checked inside the transaction that posts (a check outside it lets two concurrent retries both pass); a retry with the same key but a different amount should be refused. In our simulation (5,000 payments, 30% retried once, 5% of attempts declined) the naive server charged 1,390 payments twice (27.8%, near the 0.3 × 0.95² ≈ 27.1% expected when both attempts go through) and the keyed one none, while both ledgers summed to exactly 0: every double charge was itself a balanced entry, so balance and "at most one entry per key" are separate invariants. The instrument records a key only when an attempt posts, so a retry after a decline may still succeed: what to store for a failed attempt is a design decision.
-
Build. Add hinted handoff to a three-replica store, and measure availability and stale reads when one node is partitioned.
Solution
Solution sketch. A handoff needs somewhere to go, so use five nodes with N = 3: each key's preference list is the first three nodes clockwise from its hash (Part 39's ring, with
scale's hashing), and the next two are its fallbacks. Give every node a dictionary from key to a set of versions tagged with version vectors (Part 38), one counter per coordinator, and keep only versions not dominated by another. Draw replication delays as inscale.pbs(exponential, mean 10 ms) and run a Poisson workload of gets and puts over Zipf keys from clients that can reach the majority side. Partition node D from everyone for 60 s, then heal it. Compare two policies for each (R, W) in (1, 1), (2, 2) and (1, 3): a strict quorum, where a put succeeds only if W of the three home replicas answer within a timeout and a get if R do; and a sloppy quorum with hinted handoff, where an unreachable home replica is replaced by the first healthy fallback, which stores the version with a hint naming D and, when D is reachable again, delivers it and deletes its copy; runreplicas.merkle_syncbetween the home replicas every T seconds as the background repair. Measure the fraction of puts and gets that succeed; the fraction of successful gets that return a version dominated by one already acknowledged (stale); the siblings created; and, after the heal, how long D keeps answering stale reads. What a complete answer should find, and explain: with D gone, the keys whose lists contain D (three fifths of them) keep full availability under strict quorums when R, W ≤ 2, but lose every put when W = 3; the sloppy quorum restores those puts, at the price that R + W > N no longer guarantees overlap, since the W copies may include a fallback that no read asks. After the heal, R = 1 reads that reach D return old values until the hints arrive; with handoff that window is about the handoff delay, without it the anti-entropy period T. A further run lets clients on D's side write as well: then both sides accept puts, and the siblings the cart must merge appear. -
★ Research. The provably optimal fan-out policy for a power-law follower graph.
Discussion. Open in the form asked: a policy chosen per user and per post that minimizes the total work of a feed for a given power law and ratio of reads to writes, with a proof. Under the linear model, where each pushed timeline write and each pulled fetch has a fixed price and edges are independent, the problem is easy and is solved per edge: push the pair (u, v) when u's post rate times the write price is at most v's read rate times the fetch price (Silberstein et al.); with uniform rates and reads more frequent than posts it pushes everything, as problem 2 showed. What makes it hard is everything the linear model leaves out and real feeds depend on: pulled posts are shared and cached, so the price of pulling a celebrity falls with the number of readers who pull it (Che's approximation of Part 48 makes that price a function of the whole policy); write capacity is provisioned for the worst burst, a maximum rather than a sum; a delivery deadline caps fan-out; posting and reading rates are correlated with follower counts and with each other; and a ranked feed needs a candidate set, so pulling changes which posts can be ranked at all. A good partial answer would fix one such coupled model, for instance per-edge prices plus an LRU cache of pulled posts under the independent reference model plus a peak-capacity term, prove that an optimal policy is a threshold in (follower count, post rate) or show that it is not, derive the threshold for a Pareto law with exponent α, and check it on our synthetic graph against the hybrid's measured costs.
Notes and sources
Glossary
- base62, ID space, truncated hash, counter blocks, bijective scrambling — short codes from digits and both cases of letters; how many there are; hashing and keeping a prefix; ranges of numbers handed out in advance; making consecutive numbers unguessable.
- 301 and 302 redirects — a move that caches remember, and one they do not.
- fan-out on write (push), fan-out on read (pull), hybrid fan-out, celebrity problem — building timelines when posts are written or when they are read; pushing most accounts and pulling the largest; the accounts whose posts reach millions.
- power-law (Pareto) degree distribution — a few accounts with most of the followers.
- timeline cache, hydration, two-stage ranking, EdgeRank — lists of post IDs; looking the IDs up; cheap candidate selection then expensive ordering; an early hand-made feed score.
- offset and cursor pagination, read-your-writes — counting rows against naming a position; seeing one's own writes at once.
- connection gateway, session registry, per-conversation sequence number, receipt watermark, offline sync — holding devices' connections; finding them; ordering within a conversation; delivered-up-to and read-up-to; fetching what was missed.
- end-to-end encryption, double ratchet, chain key, sender keys — servers that relay only ciphertext; keys that change with every message and every reply; one encryption per group message.
- URL frontier, front and back queues, politeness, DNS cache — what a crawler fetches next; priority in front, one queue per host behind; limiting the rate per host.
- Bloom filter, SimHash, near-duplicate detection — a set with false positives and no false negatives; fingerprints that differ in few bits for similar pages.
- geo index, location update, greedy and batched matching, assignment problem, Hungarian method, bottleneck assignment — drivers by cell; matching each request at once or a window of them optimally; minimizing the sum or the maximum.
- contraction hierarchy, shortcut, surge pricing — road graphs prepared for fast queries; prices that clear a local market.
- encoding ladder, segment, manifest, HLS, DASH, CDN, Open Connect — one title at several bitrates, cut into files listed for the player and served from the edge.
- adaptive bitrate (ABR), rate-based, buffer-based, model predictive control (MPC), rebuffering, reservoir, cushion, QoE — choosing each segment's quality from throughput, from the buffer, or by planning ahead; stalls; the buffer levels between which quality rises; the objective traded off.
- double-entry bookkeeping, journal entry, reversing entry, idempotency key, outbox — entries that sum to zero; corrections by new entries; making retries harmless; sending messages from inside a transaction.
- authorization, capture, settlement, void, refund, reconciliation, settlement file — a card payment's states; matching our records against the outside world's.
- operational transformation (OT), transformation function, TP1, Jupiter — rewriting concurrent operations so copies converge; the property it must have; one server fixing the order.
- sequence CRDT, replicated growable array (RGA), tombstone, presence — characters with permanent names; deleted ones kept; who is here, never logged.
- preference list, coordinator, (N, R, W), sloppy quorum, hinted handoff, anti-entropy, Merkle tree, siblings, probabilistically bounded staleness (PBS) — the parts of a Dynamo-style store, and how stale its reads are.
- time series, label, cardinality, delta-of-delta, XOR compression, Gorilla — a metric per combination of labels; how many there are; compressing timestamps and values to a bit or so.
- downsampling, rollup (min, max, sum, count), retention tier, mergeable sketch — keeping old data coarsely; what survives aggregation; percentiles that do.
- change-induced outage, mishandled non-fatal error, deterministic simulation, lightweight formal methods — how systems actually fail, and two ways to find it before production does.
Sources
- A. Xu, System Design Interview: An Insider's Guide (2020), and A. Xu and S. Lam, volume 2 (2022); M. Kleppmann, Designing Data-Intensive Applications (2017); B. Burns, Designing Distributed Systems (2018); B. Beyer, C. Jones, J. Petoff and N. R. Murphy (eds.), Site Reliability Engineering (2016).
- A. Silberstein, J. Terrace, B. F. Cooper and R. Ramakrishnan, "Feeding frenzy: selectively materializing users' event feeds", SIGMOD 2010; R. Krikorian, "Timelines at scale", QCon San Francisco talk, published by InfoQ.
- T. Perrin and M. Marlinspike, "The Double Ratchet Algorithm", Signal specification (2016); I. Fette and A. Melnikov, RFC 6455, "The WebSocket Protocol" (2011).
- A. Heydon and M. Najork, "Mercator: a scalable, extensible Web crawler", World Wide Web 1999; M. Najork and A. Heydon, "High-performance Web crawling", Compaq SRC Research Report 173 (2001); B. H. Bloom, "Space/time trade-offs in hash coding with allowable errors", Comm. ACM 1970; M. Charikar, "Similarity estimation techniques from rounding algorithms", STOC 2002; G. S. Manku, A. Jain and A. Das Sarma, "Detecting near-duplicates for web crawling", WWW 2007.
- H. W. Kuhn, "The Hungarian method for the assignment problem", Naval Research Logistics Quarterly 1955; R. Geisberger, P. Sanders, D. Schultes and D. Delling, "Contraction hierarchies: faster and simpler hierarchical routing in road networks", WEA 2008; J. Hall, C. Kendrick and C. Nosko, "The effects of Uber's surge pricing: a case study" (2015); the H3 documentation (h3geo.org).
- T.-Y. Huang, R. Johari, N. McKeown, M. Trunnell and M. Watson, "A buffer-based approach to rate adaptation: evidence from a large video streaming service", SIGCOMM 2014; X. Yin, A. Jindal, V. Sekar and B. Sinopoli, "A control-theoretic approach for dynamic adaptive video streaming over HTTP", SIGCOMM 2015; F. Dobrian et al., "Understanding the impact of video quality on user engagement", SIGCOMM 2011; R. Pantos and W. May, RFC 8216, "HTTP Live Streaming" (2017); ISO/IEC 23009-1, MPEG-DASH (2012).
- J. Gray, "The transaction concept: virtues and limitations", VLDB 1981; P. Helland, "Idempotence is not a medical condition", ACM Queue 2012.
- C. A. Ellis and S. J. Gibbs, "Concurrency control in groupware systems", SIGMOD 1989; D. A. Nichols, P. Curtis, M. Dixon and J. Lamping, "High-latency, low-bandwidth windowing in the Jupiter collaboration system", UIST 1995; H.-G. Roh, M. Jeon, J.-S. Kim and J. Lee, "Replicated abstract data types: building blocks for collaborative applications", J. Parallel and Distributed Computing 2011; M. Shapiro, N. Preguiça, C. Baquero and M. Zawirski, "Conflict-free replicated data types", SSS 2011.
- D. Karger, E. Lehman, T. Leighton, R. Panigrahy, M. Levine and D. Lewin, "Consistent hashing and random trees", STOC 1997; G. DeCandia et al., "Dynamo: Amazon's highly available key-value store", SOSP 2007; P. Bailis, S. Venkataraman, M. J. Franklin, J. M. Hellerstein and I. Stoica, "Probabilistically bounded staleness for practical partial quorums", PVLDB 2012.
- T. Pelkonen et al., "Gorilla: a fast, scalable, in-memory time series database", PVLDB 2015.
- D. Yuan et al., "Simple testing can prevent most critical failures: an analysis of production failures in distributed data-intensive systems", OSDI 2014; H. S. Gunawi et al., "Why does the cloud stop computing? Lessons from hundreds of service outages", SoCC 2016; C. Newcombe et al., "How Amazon Web Services uses formal methods", Comm. ACM 2015; J. Zhou et al., "FoundationDB: a distributed unbounded key-value store", SIGMOD 2021.
About this partfrom its README
Part 49 of a sixty-one-part course in computer science (see the series plan and the syllabus), the fifth part of Act IX, Systems at Scale, and the second of two parts on system design. Eight systems almost everyone uses (a URL shortener, a news feed, a chat service, a web crawler, a ride-hailing dispatcher, a video platform, a payment ledger and a collaborative editor) are each designed from the napkin up, and each turns on one hard idea the series has already built: the birthday bound, fan-out, logical clocks, Bloom filters, the assignment problem, control loops, idempotency and CRDTs. Each is stress-tested in simulation, a Dynamo-style store and a metrics pipeline follow, and the Job runs as a service at a million books a day.
The instruments are in explainer/cs/design/cases.py (tested in tests/test_cs49_cases.py), with Part 39's
explainer/cs/dist/; two chapters reuse the cached results of Parts 46 and 48:
cases.py: the shortener's base-62 lengths for 10⁶, 10⁹ and 10¹² links and the expected collisions m²/(2·62ᵏ) of hashes truncated to k characters, withbase62itself; a synthetic follower graph of 100,000 users (Pareto tail of exponent α = 2.1 from a minimum of 20, capped at 99,999) and the daily cost of fan-out on write, on read and of the hybrid at thresholds of 100, 1,000 and 10,000 followers; the crawler's napkin for a billion pages a month, and a Bloom filter at 9.6 bits a URL with its false positives measured against (1 − e^(−kn/m))ᵏ; ride-hailing dispatch, greedy nearest-driver against the optimal assignment of a batch (SciPy'slinear_sum_assignment), 60 riders and 70 drivers in a 10 km city over 200 rounds; adaptive bitrate on Markov-modulated bandwidth traces (good, fair and poor states) with a six-rung ladder, 2 s segments and a 30 s buffer, comparing a rate-based player (the highest rung under the harmonic mean of the last five throughputs), a buffer-based one (Huang et al.: a 5 s reservoir and a 20 s cushion) and RobustMPC (Yin et al.: a five-segment lookahead, each rung held for the horizon, the forecast discounted by the recent worst error); a double-entry ledger of 5,000 payments with timeouts, retries and declines, with and without idempotency keys; operational transformation of random concurrent pairs of inserts and deletes on "the cat sat", against applying the remote operation unchanged; the cardinality of one metric as labels are added; and the Job at a million books a day (uploads, cached reads, workers sized for 60% utilization at a 3× peak, an hour at the peak simulated on a central queue, and the monthly bill).explainer/cs/dist/replicas.py(Part 39):edit_session, three replicas making 30 random edits with the replicated growable array or with positions replayed as sent, the operations delivered in random order (causally ready order for the array); 50 sessions of each.explainer/cs/dist/scale.py(Part 39):pbs, Bailis et al.'s probabilistically bounded staleness, the chance that a read just after an acknowledged write returns the old value, for six settings of (N, R, W).- Part 48's
blocks.cache_experiment(W-TinyLFU on Zipf traffic over 100,000 items), for the shortener's hit rates; Part 46's ledger, to whichcompute.pyappends row 18.
Chapter notes
- Hook. Eight systems and the eight ideas they turn on (the birthday bound, fan-out, logical clocks, Bloom filters, the assignment problem, control loops, idempotency, CRDTs). The method of Part 48: requirements, the napkin, the API and data model, a high-level design with one request traced through it, the hard part examined with numbers, and the trade-offs.
- 1. A URL shortener. Two calls,
POST /shortenandGET /hBxM5A4. The napkin (illustrative): 100 million new links a month is about 39 a second; 100 clicks a link is about 3,858 redirects a second, 11,574 at a 3× peak; six billion links in five years, 3 TB at 500 bytes each before replicas. Base 62, L = ⌈log₆₂ N⌉: a million links in 4 characters (14,776,336 codes), a billion in 6 (56,800,235,584), a trillion in 7 (3,521,614,606,208); the trillionth link converted by repeated division (Part 4) ishBxM5A4. The design from Part 48's blocks: Maglev, stateless app servers, a W-TinyLFU cache, the key–value store of chapter 10, blocks of a million numbers handed to each app server, and a click log counted by a stream job (Part 46). Three ways to choose the number: a hash truncated to k characters, with m²/(2·62ᵏ) expected collisions by Part 17's birthday bound (6 characters: 8.8 among a million links, 88,028 among a hundred million; 7: 0.14 and 1,420; 8: 0.0023 and 22.9), so every write must check and retry; a counter handed out in blocks (no checks, the shortest codes, but guessable); Snowflake IDs (no coordination, but 64 bits take 11 characters). The choice: the counter, scrambled by a fixed bijection when codes must not be guessable. 301 against 302 (Part 42's caching): a permanent redirect lets browsers and CDNs absorb later clicks but loses the analytics and the right to repoint the link. Zipf makes 302 affordable: on Part 48's traffic a W-TinyLFU cache holding 0.1%, 0.3%, 1%, 3% and 10% of the items catches 24%, 33%, 43%, 52% and 65% of requests. - 2. A news feed: fan-out. A synthetic power-law follower graph of 100,000 users: median 37 followers, mean 138, the largest account followed by all 99,999 others; half a post and twenty timeline reads per user a day, 50,000 posts against 2.0 million reads. Push (fan-out on write) costs 50,000 × 138 ≈ 6.9 million timeline writes a day; pull (fan-out on read) costs 2.0 million × 138 ≈ 276.0 million fetches; every follow is one follower and one followee, so the two means are equal and the ratio is reads over posts, 40×. The celebrity problem: one post by the largest account costs as much as 2,703 by a median one, and the 119 accounts with at least 10,000 followers (0.12% of users) receive 27% of all follows. The hybrid, pushing ordinary accounts and pulling those above a threshold: operations a day 6.9 M (push all), 79.5 M (pull ≥ 10,000), 137.9 M (≥ 1,000), 213.1 M (≥ 100), 276.0 M (pull all); the worst fan-out of one post 99,999, 9,833, 999 and 99. Counted in operations pure push is cheapest (pulling the 119 giants costs 12× as much); what the hybrid buys is the tail, and the pulled posts are the same few hot items for everyone. Silberstein et al. (2010) choose per pair of author and reader.
- 3. A news feed: ranking and reading. The read path: a stateless timeline service merges the pushed IDs from a timeline cache with the giants' latest posts, hydrates them from the post store, ranks them and returns a page of twenty. Timelines hold IDs, not copies: 800 per timeline (Twitter's figure, after Krikorian) × 100,000 users × 8 bytes = 640 MB, and a deleted post is one write. Ranking: six illustrative candidates scored EdgeRank-style as affinity × weight × e^(−age/12) (a video 5 h old 0.53, a link 2 h old 0.46, a close friend's photo 16 h old 0.25, a stranger's photo 1 h old 0.18, statuses 8 h and 3 h old 0.15 and 0.04); learned two-stage ranking (Part 47). Paging a moving list (illustrative IDs 120 … 112, then 122 and 121 arrive): page 2 by offset 4 shows 2 posts again and still walks past the skipped rows (Part 43); a cursor "older than 117" returns 116 … 113 with one index seek (Part 35); a ranked feed's cursor names a cached snapshot. Read your own writes (Part 39): read from the leader for a minute after writing, carry the last write's log position, or let the app show the post itself.
- 4. A chat service. Requirements: one-to-one and group messages, each delivered once and in order to every
device, receipts, end-to-end encryption. The napkin (illustrative): 100 million daily users × 40 messages, about
46,000 a second, 138,000 at a 3× peak; 400 GB of bodies a day; 50 million open connections, 25 servers at the 2
million a server WhatsApp reported in 2012. Gateways holding WebSockets (RFC 6455), a chat service partitioned by
conversation appending to a log per conversation, a session registry with short leases, and a push service for
sleeping phones. Order: Ana's clock runs 3 s slow, so her "Yes!" is stamped 09:59:58, before Ben's "Dinner at 8?" at
10:00:00; the conversation's owner numbers them 41 and 42, and a retried send keeps its number (Part 43). Receipts
as watermarks (delivered up to 44, read up to 42); a phone that was off asks
sync(conversation, after=44)and gets exactly 45, 46 and 47; a phone holding 44 that receives 46 asks for 45. Group fan-out with sender keys; the double ratchet (Perrin and Marlinspike, 2016): message keys from a hash chain (Part 29), deleted after use, and a fresh Diffie–Hellman (Part 30) on each reply; the server can no longer search or filter. - 5. A web crawler. A billion pages in 30 days: 386 pages a second; 193 fetches in flight at half a second each; 0.31 Gbit/s at 100 kB a page; 0.39 of one machine at 500 connections; at one request a second per host, at least 386 hosts busy at once; a Bloom filter at 1% false positives needs 9.6 bits a URL, 1.2 GB. The loop: frontier, fetcher with a DNS cache (Mercator wrote its own resolver), parser, page store, a seen-before test, and hosts assigned to machines by a hash of the name. Mercator's frontier: front queues by priority, back queues one per host, and a heap of the times each host may next be asked. Dedup: a 24-bit, 3-hash Bloom filter reporting a false "seen"; measured on 200,000 URLs at 9.6 bits each and 7 hashes, 1.005% false positives against 0.997% from theory; no false negatives, so nothing is fetched twice. SimHash (Charikar 2002) for near-duplicate content: Manku et al. (2007) used 64-bit fingerprints, at most 3 bits apart, over 8 billion pages.
- 6. Ride-hailing dispatch. A million drivers reporting every 4 s is 250,000 writes a second, about 25 MB/s (illustrative), kept as the latest position per driver keyed by an H3 cell (Part 48), with the history on the log. The design: a connection gateway, a location service writing a geo index, dispatch asking it for drivers in the rider's cell and the ring around it, an ETA service, and an offer over the driver's open connection. Greedy against batched: an illustrative pair of riders on a line where greedy gives B the far driver; then 60 riders and 70 drivers at random in a 10 km city, 200 rounds: mean pickup 1.17 km greedy against 0.96 km for the optimal assignment of the batch (the assignment problem of Part 18, Kuhn 1955), and the worst pickup in a round 4.80 km against 3.04 km. ETAs by contraction hierarchies (Geisberger et al., 2008) on a five-junction road: removing v adds the shortcut a–b of length 6, and queries climb upward from both ends. Surge pricing as a market in every cell (illustrative curves; the equilibrium moves from 5 rides an hour at price 5 to 6.875 at 6.5 when a concert ends); Hall, Kendrick and Nosko (2015); prices capped in emergencies.
- 7. A video platform. A six-rung ladder from 0.3 to 4.3 Mbit/s cut into 2-second segments, listed in an HLS or DASH manifest; the buffer-based player's choices traced on it. An hour at the top rung is 1.9 GB of transfer, and an hour stored at every rung (11.25 Mbit/s in all) 5.1 GB. Encoding through a queue, in parallel by segment; an origin blob store and CDN edges holding the Zipf head; Netflix's Open Connect. Adaptive bitrate as a control loop on one simulated session (bandwidth, rung and buffer drawn): rate-based, buffer-based (reservoir and cushion) and MPC. Over five synthetic ten-minute traces: mean bitrate 2.33, 2.66 and 2.79 Mbit/s; stalls 3.0 s, 0.0 s and 5.0 s; 53, 61 and 63 quality switches. Our MPC bought the best picture by trusting its forecast and keeping a smaller buffer (Yin et al., with a better predictor, found MPC ahead); Dobrian et al. (2011) found rebuffering the quality metric that hurt engagement most.
- 8. A payment ledger. Double entry: $50.00 leaves the customer, $48.50 reaches the merchant and $1.50 goes to fees, then a $20.00 payment ($19.40 and $0.60); every entry sums to zero, so by induction (Part 2) the ledger does; integers in cents; append-only, mistakes reversed by new entries. The design: a payments API, a single-leader ledger database, an outbox (Part 43) to the card processor; a lost reply forces a retry, and an idempotency key stored with its reply in the same transaction makes it harmless (Helland 2012). Five thousand simulated payments: without keys 6,209 entries and 1,390 payments charged twice; with keys 4,839 entries and none; both ledgers sum to exactly 0, so Σ = 0 cannot catch a double charge and "at most one entry per payment" is a second invariant. A card payment as a state machine (created, authorized, captured, settled; declined, voided, refunded), each transition a compare-and-set, written with its ledger lines and outbox message in one transaction (Part 35). Daily reconciliation against the processor's settlement file (illustrative: $12.50 against $12.05, an entry missing on each side); consistency over availability during a partition (Part 39), with "pending" answered at the edge.
- 9. A collaborative editor. Requirements: local first, convergence, intention; about 50 operations a second for
a busy document, relayed by a collaboration server to an operation log compacted into snapshots. Positions shift:
on "the cat sat", A inserts
zat 1 while B appendsxat 11; applied as sent, A ends with "tzhe cat saxt" and B with "tzhe cat satx". Operational transformation (Ellis and Gibbs, 1989) shifts B's insert to 12, and both read "tzhe cat satx"; over 5,000 random concurrent pairs, transformation converged in 100% and applying operations as sent in 6.3%. The original algorithm diverges with many sites; Jupiter (1995) and later Google Docs route operations through one server. A sequence CRDT, the replicated growable array (Roh et al., 2011): permanent names (counter, replica), inserts naming the element they follow, the larger name first, tombstones; in 50 sessions of three people making 30 edits, the array converged every time and positional replay never. Cursors anchored to names (an offset of 8 points into "cat" once "big " is typed); presence never logged; transformation against CRDTs (Yjs, Automerge). - 10. A Dynamo-style key-value store. DeCandia et al. (2007): an always-writable cart, latency at the 99.9th
percentile (300 ms in the paper's example), no master,
getandputwith a context. The napkin (illustrative): 10⁹ keys × 2 kB = 2 TB, 6 TB with N = 3, 12 machines on half-full 1 TB disks, 4,167 requests a second each at a peak of 50,000. Consistent hashing with virtual nodes; the preference list C, D, E; the coordinator answers after W = 2 writes. Quorums, R + W > N, simulated with Part 39's PBS model (20,000 writes a row, exponential delays of mean 10 ms): the chance that a read just after the acknowledgement is stale is 52.8% for (3, 1, 1) and 19.4% 10 ms later; 26.4% and 9.6% for (3, 1, 2); 19.7% and 2.7% for (5, 2, 2); 0% for (3, 2, 2), the paper's common setting, (3, 1, 3) and (5, 3, 3). Failures (illustrative): a sloppy quorum sends D's copy to F with a hint, handed back when D returns; Merkle trees find the differing key ranges. Conflicts: version vectors, siblings, a cart merged by union so that a removed pen comes back; R and W as a dial; Dynamo chose availability, Cassandra and Riak followed, a ledger could not. - 11. A metrics pipeline. A sample is a name, labels, a time and a value; agents, a log (Part 46), ingesters sharded by series, time-series shards, a downsampler and object storage. Cardinality multiplies: 50 services, then × 40 endpoints = 2,000 series, × 6 statuses = 12,000, × 8 regions = 96,000, × 200 pods = 19.2 million, × a million user IDs ≈ 1.9 × 10¹³. The napkin for 19.2 million series every 10 s: 1.92 million samples a second, 1.66 × 10¹¹ a day, 2.65 TB a day at 16 bytes a sample, about 227 GB at Gorilla's 1.37 bytes (Pelkonen et al., 2015), from delta-of-delta timestamps and XORed values, each usually a single 0 bit. Downsampling an hour of 360 points into 12 five-minute buckets of min, max, sum and count keeps a spike the mean hides; percentiles need a histogram or a sketch (Part 50). Retention tiers (illustrative): 15 days at 10 s, 90 days of minutes, 2 years of hours, 718,080 numbers per series against 6,307,200 at full resolution, about 9× fewer.
- 12. The Job at a million books a day. 11.6 uploads a second; 20 reads per upload, 231 a second, 60% of them (assumed) answered by a cache; work at a 3× peak 313 books a second; at 80 ms a book (Part 48's model) and 60% busy, 42 workers; 219 TB of storage a year at 600 kB a book. An hour at the peak simulated on one queue: median 56 ms and 99th percentile 372 ms for the requests that reach a worker, the tail of the exponential service time itself (80 ln 100 ≈ 368 ms); 42 workers at Part 45's on-demand price cost $2,903 a month, 0.0097 cents a book. Ledger row 18: the thirty novels as thirty parallel requests, the slowest of thirty, 80 ms × H₃₀ ≈ 0.32 s, for 0.290 cents, against Part 6's 281 s.
- 13. Frontier: how designs fail, and what is unknown. Yuan et al. (OSDI 2014): most catastrophic failures in five distributed systems came from mishandled non-fatal errors; Google's SRE book (2016): about 70% of outages come from changes to a live system; Gunawi et al. (2016): hundreds of cloud outage reports. Eight designs against five trade-offs (a qualitative table). Research on design itself: lightweight formal models (TLA⁺, P), deterministic simulation (FoundationDB, Antithesis), designs proposed from requirements. 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
Each turns on one hard idea, and each idea is one the series has already built. The capstone is the Job as a service at a million books a day.
- The method and the card of blocks (callback to Part 48).
- URL shortener: the ID space (base62 length for N links, derived); hashing against counters against Snowflake IDs; 301 against 302 and their caching; read-heavy Zipf traffic; click analytics as a stream (callback to Part 46).
- News feed I: fan-out on write against fan-out on read, with the cost model derived over a power-law follower graph; the celebrity problem; the hybrid (computed on a synthetic graph).
- News feed II: ranking (callback to Part 47); cursor pagination (callback to Part 43); timeline caches; read-your-writes (callback to Part 39).
- Chat: connection servers and WebSockets; per-conversation sequence numbers for ordering (callback to Part 38); receipts; offline sync; group fan-out; end-to-end encryption with the double ratchet, briefly (callbacks to Parts 29–30).
- Web crawler (callback to Part 47): the frontier as per-host priority queues; politeness; DNS caching; dedup by Bloom filters and SimHash (callback to Part 20); partitioning by host hash; the throughput for a billion pages.
- Ride-hailing dispatch:
- hexagonal geo-indexes (callback to Part 48);
- location-update write rates;
- batched matching as bipartite assignment (callback to Part 18) against greedy matching;
- ETAs by contraction hierarchies (callback to Part 18);
- surge pricing as a market.
- Video streaming:
- encoding ladders and HLS/DASH segments; CDN placement under Zipf popularity (callback to Part 45);
- adaptive bitrate as control: buffer-based (Huang et al. 2014) against MPC (Yin et al. 2015), simulated with rebuffering.
- Payments: double-entry bookkeeping as an invariant (Σ = 0, callback to Part 2); idempotency (callback to Part 43); a payment's state machine; reconciliation with outside processors; why a ledger chooses consistency over availability (callback to Part 39).
- Collaborative editing: operational transformation (Ellis & Gibbs 1989) against CRDTs (callback to Part 39); cursors and presence; convergence checked on our sequence CRDT.
- A Dynamo-style key–value store, end to end: partitioning, replication, quorums, Merkle-tree anti-entropy (callback to Part 29), hinted handoff, simulated under failures (callbacks to Parts 38–39).
- A metrics pipeline: high-cardinality time series, downsampling, retention tiers (Part 50 uses it).
- The Job at a million books a day: p99, cost and cache hit rates from the simulated load test. Ledger row 18.
- How designs fail, from post-mortems; a checklist of trade-offs (consistency, latency, cost, complexity, operability). Outro.
Computed: base62 sizing; fan-out costs on a power-law graph; ordering anomalies with and without sequence numbers; crawler throughput and dedup accuracy; greedy against optimal dispatch; ABR simulations (rebuffer ratio against mean bitrate); ledger invariants under concurrent retries; CRDT convergence; the key–value store under failures; the Job service at scale. Visuals: each architecture built block by block, with requests flowing through it as packets; the follower graph's celebrities as giant nodes; an ABR buffer trace with bitrate steps; a double-entry ledger balancing; hexagons over a city. In practice: the system design interview canon, and how large consumer products are actually built. Reading: Xu, System Design Interview vols. 1–2; Kleppmann; Burns, Designing Distributed Systems; DeCandia et al. 2007; Silberstein et al. 2010; Huang et al. 2014; Yin et al. 2015; Perrin & Marlinspike 2016; Ellis & Gibbs 1989; Heydon & Najork 1999; published engineering write-ups (cited where used).
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
短标识符。 一个短链接服务存放 10¹² 个链接需要多少个 base62 字符?截断为 7 个字符的哈希在 10⁸ 个链接时会产生多少次冲突?
解答
L 个字符给出 62^L 个代码,所以需要满足 62^L ≥ N 的最小 L:L = ⌈log₆₂ N⌉。N = 10¹² 时, log₆₂ 10¹² = 12/log₁₀ 62 = 12/1.7924 ≈ 6.69,所以 L = 7:62⁶ = 56,800,235,584 不够,62⁷ = 3,521,614,606,208 还能再容纳 2.5 万亿个。第一万亿个链接反复除以 62,得到
hBxM5A4。对截断为 k = 7 个字符的哈希,把 m 个代码看作在 N = 62⁷ 个值上独立且均匀分布。 C(m, 2) 对中的每一对以概率 1/N 冲突,由期望的线性性,冲突对数的期望为 C(m, 2)/N = m(m − 1)/(2N) ≈ m²/(2N);等价地,逐个插入链接, 第 i 个落在已用代码上的概率约为 (i − 1)/N,求和结果相同。m = 10⁸ 时为 10¹⁶/(2 × 3.5216 × 10¹²) ≈ 1,420。三重冲突只增加约 m³/(6N²) ≈ 0.013,完全没有冲突的概率约为 e^(−1420):冲突是必然的,所以每次写入都必须检查存储,冲突时加盐重试。重试本身很便宜 (一亿次写入中 1,420 次);代价在于每次写入都要做的检查。同样的哈希在 10⁶ 个链接时为 0.14;要让 10⁸ 个链接的期望冲突低于一次, 需要 62ᵏ > 5 × 10¹⁵,即 k ≥ 9(0.37)。分块发放的计数器既不需要检查,也不需要多出的字符。 -
扇出。 对服从指数为 α 的幂律的关注者数,推导写时扇出与读时扇出的期望代价,以及最佳的名人阈值。
解答
设有 U 个用户,每人每天发帖 p 次、阅读 r 次,关注者数 F 相互独立,x ≥ f_m 时 P(F > x) = (f_m/x)^(α−1)(密度正比于 x^(−α)),并截断在 M = U − 1;我们的工具取 α = 2.1、f_m = 20、p = 0.5、r = 20。每一次关注都是一个关注者和一个被关注者,所以被关注 数的均值也是 E[F]。推把每个帖子写进 F 条时间线,每帖 E[F],每天 pUE[F];拉在每次阅读时从每个被关注者处取,每次阅读 E[F],每天 rUE[F];两者之比 r/p = 40,与 α 无关。对密度积分,不截断且 α > 2 时 E[F] = f_m(α − 1)/(α − 2)(这里为 220),截断后 E[F] = f_m[(α − 1) − (f_m/M)^(α−2)]/(α − 2) = 134.7,测得 138.0(标准差为 1,454,所以均值的标准误约为 4.6)。于是推每天约 50,000 × 138 ≈ 690 万次写入,拉 2.760 亿次读取。均值掩盖了尾部:α < 3 时不截断的方差是无穷大,一个帖子就可能要写 99,999 次。混合 方案推送 F < τ 的账号,拉取其余的,代价为 W(τ) = U[p E[F; F < τ] + r E[F; F ≥ τ]],其中 E[F; F ≥ τ] = f_m[(α − 1)(f_m/τ)^(α−2) − (f_m/M)^(α−2)]/(α − 2),被拉取的账号有 U(f_m/τ)^(α−1) 个。τ = 100、1,000 和 10,000 时, 模型给出的指向被拉取账号的关注比例为 76%、47% 和 24%(测得 77%、49% 和 27%),被拉取的账号为 17,027、1,352 和 107 个(测得 16,953、1,336 和 119 个)。而 W(τ) = U[pE[F] + (r − p)E[F; F ≥ τ]],只要 r > p 就随 τ 递减:每次操作代价相同时没有内部最优,全部推送 最便宜(690 万对 τ = 10,000 时的 7,950 万)。只有给计数所忽略的东西定价,才会出现有限的最佳阈值。(a) 截止时间:若一个帖子必须在 L 秒内送达每个关注者,而一台服务器每秒写 s 条时间线,则 τ ≤ sL;由于 W 递减,τ* = sL。取工具中的 s = 50,000(最大账号的一个帖子 在一台服务器上要 2.0 秒)和 L = 0.2 秒,τ* = 10,000,拉取 119 个账号。(b) 给最坏扇出的每个单位定价 κ(为最大突发预留的容量), 推送一次写入的代价为 c_w,拉取一次读取为 c_r(被拉取的帖子是热门且有缓存的,所以便宜): W(τ) = U[p c_w E[F; F < τ] + r c_r E[F; F ≥ τ]] + κτ;密度为 (α − 1)f_m^(α−1)τ^(−α),所以 W′(τ) = −U(r c_r − p c_w)(α − 1)f_m^(α−1)τ^(1−α) + κ。若 r c_r > p c_w,W′ 从负值向 κ 上升,只穿过零一次,那里是最小值: τ* = [U(α − 1)f_m^(α−1)(r c_r − p c_w)/κ]^(1/(α−1)),α = 2.1 时几乎正比于 U(r c_r − p c_w)/κ(指数为 0.91);若 p c_w ≥ r c_r,则 W′ > 0,全部拉取。Silberstein 等的规则(当 p_u c_w ≤ r_v c_r 时推送(作者 u,读者 v)这一对)在各条边代价相互独立时是精确的,线性 模型正是如此;在我们均匀的速率下,它全部推送。
-
批量派单。 证明批量指派的总接驾距离从不大于贪心,并给出一个它小得多的例子。
解答
固定一批:乘客集合 R,空闲司机集合 D,|D| ≥ |R|,距离为 d(r, x)。任何给每位乘客分配不同司机的规则都定义一个单射 σ: R → D,贪心无论按什么到达顺序,都是其中之一。批量指派在所有这样的映射上最小化 Σ_r d(r, σ(r)),所以它的总和至多等于贪心的, 贪心恰好最优时取等号。贪心坏到指数级的一族例子在一条直线上:司机位于 d₀ = 0、d₁ = 2 − ε 和 d_k = 2d_(k−1) − ε;乘客 1 在 1,然后 乘客 k 在 d_(k−1)(k = 2, …, n),依次到达。乘客 1 选 d₁(距离 1 − ε,比距离为 1 的 d₀ 近);乘客 k 发现 d_(k−1) 已被占用,选 d_k, 距离 d_(k−1) − ε,刚好比距离为 d_(k−1) 的 d₀ 近。贪心的总和逐项相消为 d_n − 1 ≈ 2ⁿ − 1,而批量把乘客 1 派给 d₀,其余每位乘客派给就站 在其所在位置的司机:总和为 1。取 ε = 0.001,n = 5 时为 30.97 对 1,n = 10 时为 1,021.98 对 1。在我们随机的城市里收益不大:平均接驾 1.17 公里对 0.96 公里(少 18%),每轮最远的接驾从 4.80 公里降到 3.04 公里;但最小化总和一般并不最小化最远的接驾,那是瓶颈指派问题。 两点保留:在相继的多个时间窗口上,每个窗口对它所含的乘客都最优,但与整天的贪心相比就不再是定理了,因为前面的批次改变了后面的批次 能看到哪些司机;而且窗口本身增加了等待时间。
-
账本。 证明复式记账的过账保持 Σ 余额 = 0,并证明幂等键能防止重试下的重复扣款。
解答
设余额为 B: 账户 → ℤ(以分为单位的整数,所以求和是精确的;用浮点数时,一笔平衡的分录加起来可能是一个极小的非零值)。一笔分录是 若干行 (a_j, v_j),Σ_j v_j = 0,工具在构造每笔分录时都断言这一点。过账令 B′(a) = B(a) + Σ_(j: a_j = a) v_j,所以 Σ_a B′(a) = Σ_a B(a) + Σ_j v_j = Σ_a B(a)。开始时每个余额都是 0,所以对已过账分录的序列归纳,每一步之后都有 Σ B = 0。这要求每笔 分录原子地过账:若分录是事务,则每个可串行化的执行都等价于某个序列,而被读者看到的过了一半的分录会破坏不变量;又因为分录只追加, 更正是一笔新的、反向的分录,它的和也是零。关于幂等:服务器在一个事务中处理带键 k 的请求:若 k 已有记录,返回存下的回复;否则过账, 并在唯一索引下记录 (k, 回复)。断言:至多一笔分录带有 k。为 k 过账的事务也记录了 k,所以之后的任何事务都会找到 k 而不过账;两个并发的 事务不可能都提交,因为可串行化(或唯一索引)会让其中一个中止。客户端在同一笔支付的每次尝试中都发送同一个键,所以它的所有重试共享 k, 至多扣款一次。这个论证要求:键在第一次尝试之前选定并由客户端保存,从不用于另一笔支付,服务器保留它至少与重试可能到达的时间一样长, 并且在过账的同一事务内检查(在事务外检查,会让两个并发的重试都通过);键相同而金额不同的重试应被拒绝。在我们的模拟中(5,000 笔 支付,30% 重试一次,5% 的尝试被拒付),朴素的服务器对 1,390 笔支付扣了两次款(27.8%,接近两次尝试都成功时的期望 0.3 × 0.95² ≈ 27.1%),带键的服务器一笔也没有,而两个账本的和都恰好为 0:每次重复扣款本身都是一笔平衡的分录,所以平衡与"每个键 至多一笔分录"是两个独立的不变量。工具只在某次尝试过账时才记录键,所以拒付之后的重试仍可能成功:失败的尝试应存下什么,是一个设计 决定。
-
动手。 给一个三副本的存储加上提示移交,并测量一个节点被分区时的可用性和陈旧读。
解答
解答要点。 移交需要有地方可去,所以用五个节点、N = 3:每个键的偏好列表是从它的哈希起顺时针的前三个节点(第39部分的环,用
scale的哈希),接下来的两个是它的后备。给每个节点一个从键到版本集合的字典,版本用版本向量(第38部分)标记,每个协调者一个计数器, 只保留不被其他版本支配的版本。复制延迟按scale.pbs的方式抽取(指数分布,均值 10 毫秒),由能到达多数派一侧的客户端在 Zipf 分布的 键上运行泊松的读写负载。把节点 D 与所有人分区 60 秒,然后恢复。对 (R, W) 取 (1, 1)、(2, 2) 和 (1, 3),比较两种策略:严格法定人数, 写入只有在三个本属副本中有 W 个在超时内应答时才成功,读取要 R 个;宽松法定人数加提示移交,不可达的本属副本由第一个健康的后备代替, 后备保存这个版本和一条指明 D 的提示,D 重新可达时交付并删除自己的副本;每 T 秒在本属副本之间运行replicas.merkle_sync作为后台 修复。测量成功的写和读的比例;成功的读中,返回的版本被某个已确认版本支配(陈旧)的比例;产生的兄弟值;以及恢复之后 D 继续给出 陈旧读的时间。完整的答案应发现并解释:D 不在时,偏好列表含 D 的那些键(占五分之三)在严格法定人数下,R、W ≤ 2 时仍完全可用,但 W = 3 时失去所有写入;宽松法定人数恢复了这些写入,代价是 R + W > N 不再保证相交,因为 W 个副本中可能有一个没有读去询问的后备。 恢复之后,到达 D 的 R = 1 读在提示到达之前返回旧值;有移交时这个窗口约为移交的延迟,没有时为反熵的周期 T。再做一次运行,让 D 一侧的 客户端也写入:两侧都接受写入,购物车必须合并的兄弟值就出现了。 -
★ 研究。 对幂律关注图可证明最优的扇出策略。
讨论。 按题目的提法尚未解决:一个按用户、按帖子选择的策略,对给定的幂律和读写比最小化信息流的总工作量,并给出证明。在线性 模型下,每次推送的时间线写入和每次拉取的读取各有固定的价格,各条边相互独立,问题很容易,按边求解:当 u 的发帖速率乘以写的价格不超过 v 的阅读速率乘以读的价格时,推送 (u, v) 这一对(Silberstein 等);速率均匀、阅读比发帖频繁时,它全部推送,正如第 2 题所示。难的是 线性模型忽略、而真实信息流所依赖的一切:被拉取的帖子是共享的、有缓存的,所以拉取一个名人的价格随拉取它的读者数下降(第48部分的 Che 近似使这个价格成为整个策略的函数);写入容量按最坏的突发来预留,是最大值而不是总和;送达的截止时间限制了扇出;发帖和阅读的 速率与关注者数相关,彼此也相关;排序的信息流需要候选集,所以拉取改变了哪些帖子能被排序。好的部分答案应固定一个这样耦合的模型,例如 按边定价,加上独立引用模型下对被拉取帖子的 LRU 缓存,再加上峰值容量项;证明最优策略是(关注者数,发帖速率)上的阈值,或证明它不是; 对指数为 α 的帕累托分布推导出阈值,并在我们的合成图上对照混合方案测得的代价检验它。
Build the film
python -m videos.cs.cs49.compute # the part's numbers, into .cache/cs49
python tools/build.py cs49 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs49 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs49. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs49.compute
python -m unittest tests.test_cs49_cases
python tools/build.py cs49