CComputer Science, Built

Act IX · Systems at Scale

Part 48 of 61

System Design I: Building Blocks

Degreestarts at this level52 min of film17 chaptersprerequisites: Part 20, Part 31, Part 39, Part 43

Which few blocks is a large system assembled from, and what does the arithmetic of each one promise?

The part opens on a napkin: 10 million users a day times 20 actions is 200 million requests, about 2,315 a second on average and 6,944 at the evening peak, and 199 TB of storage in five years. A design is then made in eight decisions, followed through on a pastebin, and each block the decisions call for is built and measured. Two random choices beat round robin on 50 servers, and Maglev's table is compared with a hash ring when one of 20 backends leaves. Che's approximation, with one unknown called the characteristic time, predicts an LRU cache's hit rate on Zipf traffic to within half a point. A hot key's expiry causes about 400 rebuilds until XFetch's random early refresh replaces them with one, and a token bucket is shown to be a guarantee: at most sigma + rho s requests in any interval. The part goes on through queues, storage engines, sharding, replication, identifiers that sort by time, blobs, and space-filling curves that turn a map into keys. It ends by load-testing the Job as a service made of these blocks, with and without its cache, and at the frontier with a learned index and the question of predicting a system before it is built.

What you need. Arithmetic with powers of ten, and the exponential function; no experience of running a service is assumed.

Mathematics, ideas and history
napkin estimation, load balancing (two choices, Maglev), caching (Che's approximation, stampedes), rate limiting (token buckets), sharding, replication, unique IDs, geospatial indexes
What we build or compute
the Job as a service, load-tested

What you will be able to do

Degree

  • Estimate a service's requests a second, storage and bandwidth from its daily users, a peak factor and an object size.
  • Explain why a consistent-hash ring moves only the departed backend's keys, and what hash modulo N moves instead.
  • Lay out a Snowflake ID's bits and compute how many years and how many IDs a millisecond it allows.

Graduate

  • Derive Che's approximation and find the characteristic time by bisection.
  • Prove that a token bucket of depth sigma and rate rho admits at most sigma + rho s requests in any interval of length s.
  • Derive XFetch's trigger probability and the time before expiry at which a refresh is expected.

Research

  • Build a learned index with a bounded error and compare its size and comparisons with a B+ tree's inner nodes.
  • State what a competitive guarantee for cache admission on drifting Zipf traffic would have to compare against, and why the classical bounds do not give it.

Industry

  • Size a worker pool with Little's law and a target utilization, and say why the queue's age is the signal to scale on.
  • Choose a shard key for a workload, and handle a hot key by salting it.
  • Load-test a design in simulation and report the median and the 99th percentile against the request rate, with and without the cache.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 19 min · Graduate 51 min · Research 52 min · Industry 38 min.

  1. 0The napkinDegree2 min
  2. 1How a design is madeDegree4 min
  3. 2Load balancingDegree3 min
  4. 3Caching: where, and what to keepGraduate3 min
  5. 4Caching: staleness and stampedesGraduate3 min
  6. 5Rate limitingGraduate3 min
  7. 6Queues and asynchronyDegree2 min
  8. 7Choosing storageIndustry3 min
  9. 8ShardingIndustry3 min
  10. 9Replication in practiceIndustry3 min
  11. 10Unique IDsDegree4 min
  12. 11Blobs and the edgeIndustry3 min
  13. 12Maps as keysGraduate4 min
  14. 13Real-time blocksIndustry3 min
  15. 14The Job as a serviceIndustry3 min
  16. 15Frontier: design as a scienceResearch1 min
  17. 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.

The napkinDegree2 min

Every design begins on a napkin. Suppose ten million people use a service each day, twenty times each: two hundred million requests. A day has eighty-six thousand four hundred seconds, so that is about two thousand three hundred requests a second, on average. Traffic is not flat: the evening peak might be three times the mean, nearly seven thousand a second. If one request in eleven writes, about two hundred writes a second. At two kilobytes a write, kept for five years in three copies, about two hundred terabytes. And the reads at the peak move a dozen megabytes a second. Five minutes of arithmetic, and we know this needs a cluster, not a laptop, but not a datacentre either.

Napkin arithmetic needs a few numbers in your head. A memory reference takes about a hundred nanoseconds. Reading a megabyte from memory, about ten microseconds; a random read from a solid-state disk, about a hundred. A round trip inside a datacentre, around half a millisecond. A spinning disk's seek, ten milliseconds, and a round trip across a continent, fifty to a hundred. And a few conversions: two to the tenth is about a thousand, a day is about a hundred thousand seconds, and a year is pi times ten to the seventh. These are orders of magnitude, after the lists Jeff Dean and Peter Norvig made famous; the point is to be right to within a factor of a few.

A large system is assembled from a small set of blocks. Load balancers, caches, rate limiters and queues; shards and replicas; identifiers, blob stores and content delivery, and indexes for maps. Each block has mathematics of its own, much of it from earlier parts: hashing that rebalances gracefully, caches that survive a stampede, rate limiters that are token buckets in disguise, identifiers that sort by time without any coordination, and curves that turn a map into a list of keys.

1How a design is madeDegree4 min

A design is a sequence of decisions, made in order. First the requirements: what the system must do, and how well. Then a capacity model, the data, and the interface. Only then a high-level design, deep dives into its riskiest parts, the trade-offs, and a written document. It is not a waterfall: a deep dive that breaks an estimate sends you back. We will follow one small service through it, a pastebin: store a text, get a link.

Requirements come in two kinds. Functional ones say what the system does: create a paste and get a link, read it, let it expire; and, as useful, what it will not do. Non-functional ones say how well: fast, available, durable, at a given scale. As words, they cannot be checked. So turn them into service-level objectives, numbers over a window: ninety-nine percent of reads within two hundred milliseconds; ninety-nine point nine percent of requests succeeding over thirty days. The second is an error budget, about forty-three minutes a month, to spend on failures. Part 50 lives within it.

Next, the capacity model: the hook's napkin, turned into decisions. About seven thousand requests a second at the peak. If a server handles a thousand, kept half busy, as Part 31 advises, that is 14 servers behind a load balancer. About two hundred writes a second, six hundred at the peak: one primary database, with replicas for reads. Ten reads per write: a cache earns its place. Two hundred terabytes will not fit one machine: shard the records, and put the texts in a blob store. A dozen megabytes a second is a tenth of one gigabit link: not the problem.

Then the data model. A paste is a record: an identifier, an owner, when it was made and when it expires, its size, and where its text is kept. It is always read by its identifier, so a key-value store will do. Then the interface. Creating a paste carries an idempotency key, Part 43's device, so that a retried request does not make two. Reading an expired paste says gone, not missing. And listing a user's pastes returns a cursor rather than a page number, so the list stays correct while it changes.

Only now, the high-level design. Clients reach a load balancer, which spreads requests over stateless application servers. They read through a cache, keep the records in a sharded key-value store, and put the texts in a blob store. Every box hides questions, and deep dives take the riskiest first. Which server takes each request? How are identifiers made without a central counter? What happens when a popular entry expires and a thousand requests miss at once? Which key spreads the shards? The rest of this part answers each in turn.

No design is free, and a good one says what it gives up. The cache makes reads fast, and a paste can be stale for as long as its entry lives. Sharding takes the data past one machine, and gives up cheap queries across shards. The blob store keeps bytes cheaply and durably, and every create now writes two systems that must agree. All of it goes into a design document: context, goals and non-goals, the design, the alternatives and why they lost, the trade-offs, and open questions. Reviewers argue with the document, and Part 49 writes eight.

2Load balancingDegree3 min

A load balancer stands in front of many servers and decides which one gets each piece of work. It can decide at two levels. A layer-four balancer reads only addresses and ports, and forwards whole TCP connections; it never sees the request inside. Google's Maglev and Linux's IPVS work this way, and they are cheap. A layer-seven balancer, like NGINX, Envoy or HAProxy, ends the connection, decrypts it and reads each HTTP request, so it can route by path, retry a failed request on another server, and balance request by request rather than connection by connection. That control costs work on every request.

To compare policies we simulated 50 servers at 90 percent load. Choosing at random gives each server its own random queue, Part 31's single-server queue, with a mean of ten service times and a tail near fifty. Round robin spaces each server's arrivals evenly, and roughly halves both. The power of two choices, from Part 20: pick two servers at random and join the shorter queue. The mean falls below three, and the tail to 9. Asking every server, least connections in its ideal form, does better still, but needs fresh counts from every queue; with many balancers and stale counts, all pile onto the same idle-looking server. Two choices needs two looks, and avoids the herd.

Sometimes the same key must reach the same server: a user's session, or a shard of a cache. Hashing the key modulo the number of servers does that, until a server leaves; then most keys move. Part 39's consistent hashing puts servers and keys on a ring. A key belongs to the next server clockwise, and each server sits at many points, virtual nodes, to even out the arcs. Remove a server, and only its own keys move, each to its clockwise neighbour. Everything else stays where it was.

Google's Maglev balancer, described by Eisenbud and colleagues in 2016, replaces the ring with a lookup table. Each backend derives, from two hashes of its name, its own order of preference over the table's slots. The backends take turns, each claiming its most preferred slot still free, until the table is full. A packet's hash picks a slot, and the slot names the backend. With twenty backends and sixty-five thousand five hundred and thirty-seven slots, every backend owns three thousand two hundred and seventy-six slots, or one more. Then we removed one. Its five percent of the keys must move; Maglev also moved a third of a percent of the others, which the ring did not. In return, its busiest backend carried three percent more than the mean, against the ring's thirteen.

3Caching: where, and what to keepGraduate3 min

There are four common ways to connect a cache to the data behind it. In cache-aside, the commonest, the application asks the cache, and on a miss reads the database and fills the cache itself; on a write it updates the database and deletes the cached copy. In read-through, the cache does the loading itself. Write-through sends each write through the cache to the database before acknowledging it: never stale, but every write is slower. Write-back acknowledges at once and writes the database later, as Part 9's processor caches do: fast, but what it has not yet written is lost if it fails.

When the cache is full, something must go. LRU evicts the entry used least recently. It adapts quickly, but one pass over cold data flushes it. LFU evicts the entry used least often: good for steady popularity, slow to forget yesterday's favourites. W-TinyLFU, by Einziger, Friedman and Manes, combines them. New entries land in a small LRU window; one leaving it enters the main cache only if it has been used more than the main cache's victim, as counted by Part 20's Count-Min sketch, halved now and then so that it forgets. When we ran a one-off scan of cold keys, LRU's hot entries came straight back: nearly all the damage was the scan's own misses.

How large must a cache be? In 2002 Che, Tung and Wang gave LRU a formula. An LRU cache of C entries holds exactly the items of the most recent stretch of requests in which C different items appear. Call its length T, and assume that it hardly varies: that is the approximation. If item i is a fraction p i of requests, it was missed by all T with probability one minus p i to the T, about e to the minus p i T. The cache holds C items, so the chances of being cached add up to C, which fixes T. A request hits when its item is cached, so the hit rate is the sum of p i times that chance.

Now the measurement: a catalogue of 100,000 items with Zipf popularity and 400,000 requests. LRU's hit rate climbs steadily as the cache grows tenfold, and tenfold again: 16 percent at 100 entries, 34 at a thousand, 60 at ten thousand. Che's formula lies on top of it, within half a percentage point at every size. Frequency does better: TinyLFU and LFU reach 43 and 44 percent at a thousand entries, close to the best fixed set, the thousand most popular items, at 47. So one percent of the catalogue serves over a third of the requests, and the formula gives the size before you buy the memory.

4Caching: staleness and stampedesGraduate3 min

A line usually credited to Phil Karlton says there are only two hard things in computer science: cache invalidation, and naming things. The usual rule on a write is: update the database, then delete the cached copy, rather than updating it, because two updates can reach the cache in the wrong order. Even deletion has a race. A reader misses, and reads the old value from the database. Before it stores that value, a writer commits a new one and deletes the key. Then the reader's set lands. The cache holds the old value, the database the new one, and nothing is left to remove it, except its time to live.

A time to live puts a bound on how wrong a cache can be. The database changes at the moment of the write. The cached copy carries on serving the old value until it expires. So with no invalidation at all, a value is stale for at most the TTL, and with invalidation, the TTL still catches whatever the races let through. One trap. Keys filled together, after a restart or a deploy, also expire together, and all miss at once. Adding a small random jitter to each TTL spreads the expiries out.

Expiry has a second danger, for a key that is hot. In our experiment, one key is requested two hundred times a second, lives for sixty seconds, and takes two seconds to rebuild. When it expires, every request in those two seconds misses, and each one rebuilds the same value. Over five minutes, four expiries caused one thousand six hundred and three rebuilds, at worst two hundred and twenty-three in a single second, all on the database. This is the thundering herd, or cache stampede: the cache's own expiry aims the full load at the store it was there to protect.

The first remedy is to rebuild once. Request coalescing, sometimes called single flight, lets the first miss start the rebuild and makes every other request for that key wait for its result: one query instead of hundreds. Facebook's memcache, described by Rajesh Nishtala and colleagues in 2013, does this with leases. On a miss, the cache hands out a token, at most once every ten seconds for each key, and other clients wait briefly and try again. Only the holder of the token may set the value, and a delete in the meantime voids it, which closes the race we began with. They reported that leases cut the peak rate of database queries from seventeen thousand a second to thirteen hundred.

5Rate limitingGraduate3 min

A rate limiter protects a service from callers who send too much. The commonest is the token bucket. Tokens drip into a bucket at a steady rate, rho, up to a depth, sigma. Each request takes a token, or, if the bucket is empty, is refused, with Part 43's status code four hundred and twenty-nine. A burst passes at once, up to sigma requests, here twenty. Then the bucket is dry, and only the rate gets through, a hundred a minute. On our bursty test traffic, one thousand and eighty-eight requests in ten minutes, it admitted seven hundred and sixty-six.

The token bucket is also a guarantee. Take any interval of length s. At its start the bucket holds at most sigma tokens; during it, at most rho times s more arrive; and every admitted request spends one. So the number admitted in any interval is at most sigma plus rho s, a straight line, which the greediest allowed sender follows. We checked every interval of up to ten seconds in our trace: none crosses the line. Rene Cruz built network calculus on such envelopes in 1991. Envelopes add, so a service fed by limited clients has a worst case it can be sized for. A leaky bucket instead queues the excess and drains it steadily: it smooths, where the token bucket refuses.

Many limiters count instead. The simplest keeps one counter per minute and refuses requests once it reaches the limit. But a burst at the end of one window and another at the start of the next both pass: twice the limit in a single minute. On our trace, with a limit of one hundred, the worst minute admitted one hundred and thirty-eight. A sliding log, keeping every timestamp, is exact but costly. The sliding-window counter keeps two numbers: it weights the previous window's count by how much of it the last minute still covers. That assumes the previous window was evenly spread, and bursts are not: against the exact count, our trace's mean error is fifteen percent, and the worst above a hundred percent. On real traffic it does far better: in 2017 Cloudflare reported only three wrong decisions in a hundred thousand requests.

6Queues and asynchronyDegree2 min

Some work need not happen while the caller waits: resizing an image, or sending an email. The web tier records the request, puts a job on a queue, and answers at once with Part 43's two hundred and two, accepted. Workers take jobs at their own pace. A burst now fills the queue, which drains. The queue has turned a problem of rate into a problem of delay. But only if, on average, the workers keep up: a queue absorbs bursts, never a shortfall. In return, the caller never waits for slow work, a failed job can be retried from the queue, and the producers and consumers can be scaled separately.

How long is the delay? Part 31 answered that. With random arrivals and random job sizes, the mean time in the system is one over one minus the utilization, in units of the service time: two at half load, ten at ninety percent, about twenty-one at ninety-five. The slowest one percent are worse: forty-eight service times at ninety percent. And variability costs as much as load. At eighty percent, jobs of identical size wait three service times on average; exponential sizes, five; and sizes that vary ten times as much, twenty-two. So a design leaves headroom, and watches how long jobs wait in the queue, not merely how busy the workers are.

How many workers? Little's law says the number of jobs in service is the arrival rate times the time each one takes. Take the napkin's two hundred and ten writes a second, and suppose each starts a job of half a second. On average, a hundred and five workers are busy. Add headroom, running at seventy percent: a pool of a hundred and fifty. One shared queue feeding many workers can run hotter than many small queues: Erlang's pooling. Scale the pool on the age of the oldest waiting job, not on processor load, and bound the queue so that overload is refused early. Part 49 will size whole systems this way, and Part 50 will decide what waits they may promise.

7Choosing storageIndustry3 min

Every design needs somewhere to keep its data, and databases come in a handful of shapes. Relational databases keep tables of rows and join them when asked, with transactions, and a planner that answers questions nobody anticipated, as Part 35 showed. A key-value store answers one question, the value for this key, very fast, and scales by splitting the keys. A document store keeps a whole nested record together. Wide-column stores, after Google's Bigtable, keep sorted rows of sparse columns, built for heavy writes. Graph databases follow edges, hop after hop; and time-series databases append timestamped points and summarise them over windows.

The shape that fits is the one that matches the questions you will ask, so list the access patterns first. Take one analytical question over a million rows of sixteen columns: add up column three wherever column seven is below a hundred. A row store keeps each row together, so the scan drags all sixteen columns through memory, a hundred and twenty-eight megabytes. A column store keeps each column together and reads only the two it needs, sixteen megabytes. In Part 35's measurement, the column scan took four milliseconds against fourteen. Rows suit fetching and updating whole records; columns suit scanning a few fields of very many.

Under the shape sits an engine, and it matters as much. A B-tree updates pages in place. In Part 34's simulation, with little of the tree cached, each byte the application wrote cost about forty bytes of disk writes, and still eighteen with over half the tree in memory. A log-structured merge tree buffers writes and merges sorted runs: about twelve with levelled compaction, about two with tiering. The price is paid on reads. Tiering leaves nineteen runs to probe for a key that is not there, until a Bloom filter of ten bits per key cuts that to a sixth of one. That is why write-heavy stores such as Cassandra and RocksDB are built on LSM trees.

Then index for the access patterns, with Part 35's B-trees. With four hundred keys to a node, a billion rows need only four levels, so a lookup is a handful of page reads. Where the rows sit matters too. In Part 35's word table, the range from whale to whales matched one thousand seven hundred and four rows. Through a secondary index they lay on nine hundred and sixty-six different pages; stored in index order, on eighteen. But every index is a bet. Each is one more structure to update on every insert, and more memory to keep warm. Index the questions you will ask, and no others.

8ShardingIndustry3 min

Sharding splits a dataset across machines, and the choice that matters most is the shard key. Range partitioning gives each shard a contiguous run of keys, as Bigtable does with its tablets. But if the key grows with time, every new row lands on the last shard, and one machine takes all the writes. Hash partitioning scatters keys by their hash, Part 17's trick, and spreads the writes evenly. The price is order. A range scan touches one shard of a range-partitioned table, but every shard of a hashed one. Many systems compromise: hash a prefix, such as the user, and keep rows sorted within it.

Even a perfect hash cannot split a single key. In Part 39's simulation, a million keys are hashed over a hundred shards, and requests follow Zipf's law. With uniform popularity, the busiest shard carries one point zero four times the mean. With a Zipf exponent of one, the hottest key alone takes seven percent of all requests, and its shard nearly eight times the mean; at one point two, almost twenty. That is the celebrity problem: one account, followed by millions. The fix is to split the hot keys themselves. Append one of twenty suffixes to each of the ten hottest, and merge the pieces on read. At exponent one, the busiest shard falls below twice the mean. Part 49's feeds meet the celebrity again.

Data grows, and shards must split or move. Hashing modulo the number of machines is the trap from chapter two. Going from ten machines to eleven moved ninety-one percent of the keys in Part 39's measurement, when the ideal is one in eleven; a ring moved under nine percent. Many systems instead create far more partitions than machines at the start, and move whole partitions: a new machine takes a few from each of the others, and no key ever changes partition. The move itself is a careful dance. Copy the partition, stream the writes made during the copy, switch the routing table, and only then delete the old copy.

Some queries span shards anyway. Choose the key so that the common ones do not: shard by customer, and keep each customer's users, orders and invoices together, so their joins stay on one machine. A transaction that must change two shards needs Part 39's two-phase commit. Every shard votes yes and locks its rows. In Part 39's run, the coordinator crashed just after deciding to commit, and every participant held its locks for thirty-one seconds, until the coordinator recovered. So design for one shard per operation, and treat the cross-shard path as the rare, slow, carefully guarded exception.

9Replication in practiceIndustry3 min

Part 39 gave the theory of replication; here is how it is used day to day. Most systems start with one leader that takes every write and appends it to a log. Followers replay that log. Reads, usually the bulk of the traffic, spread across the followers, so each new follower adds read capacity, and is a warm spare besides. The catch is that shipping the log takes time. A follower's copy is a little behind: by milliseconds normally, and by far more when it is overloaded.

That lag breaks a promise users take for granted: to see what they just wrote. In Part 39's simulation, followers apply each write a hundred milliseconds after the leader, on average, and the user's next read goes to any of three replicas. Reading at once, two reads in three miss the write. After a hundred milliseconds, about one in four; after half a second, one in two hundred. Two fixes are common. For a short while after a user writes, send that user's reads to the leader. Or have the write return its position in the log, and read only from a replica that has reached it.

When the leader dies, a follower must take over, and the first problem is knowing that it died. Followers expect a heartbeat, here every hundred milliseconds, and suspect the leader after a timeout. Part 39 measured the trade on a jittery network. A timeout of a hundred and fifty milliseconds notices a crash in about a tenth of a second, but raises two hundred and fifty false alarms an hour; three hundred milliseconds, about three; three seconds, none. Then the most up-to-date follower is promoted, and clients are redirected. With asynchronous replication, writes the old leader acknowledged but never shipped are simply gone. Semi-synchronous replication waits for one follower to confirm each write, and loses nothing acknowledged, at the cost of a round trip.

The dangerous failure is a leader that is not dead, only paused. Leader A holds a lease, numbered thirty-three, and writes under it. Then it stalls, perhaps in a long garbage collection, and its lease runs out. The lock service grants a new lease to B, numbered thirty-four, and B starts writing. Then A wakes, still believing it leads, and writes too: two leaders, split brain. Part 38's fencing tokens stop it. Every write carries its lease number, and the storage remembers the largest it has seen, so it rejects thirty-three after thirty-four. The check must live in the storage: a paused leader cannot be trusted to check its own clock.

10Unique IDsDegree4 min

Every record needs a name, and with many machines the obvious answer stops working. A single database counter hands out one, two, three. But then every insert in the system asks one machine: a bottleneck, and a single point of failure. Splitting the counter helps. Flickr, in 2010, ran two ticket servers, one handing out odd numbers and the other even. The other answer is to let each machine mint its own names, chosen so that they never collide, without asking anyone.

The simplest way to need no one is to choose at random. A version four UUID has a hundred and twenty-eight bits, six of them fixed to mark its version and variant, leaving a hundred and twenty-two random. Part 17's birthday bound gives the chance that any two of n such IDs collide: about one minus e to the minus n squared over two to the hundred and twenty-three. A billion IDs: about one chance in ten to the nineteen. A million million: one in ten to the thirteen. Even at a thousand million million, about one in ten million. Only near two point seven billion billion are the odds even. In practice, a broken random number generator is far likelier than bad luck.

Random IDs scatter; often we want them to sort by time. Twitter's Snowflake, from 2010, packs sixty-four bits: forty-one bits of milliseconds since a chosen epoch, ten bits naming the machine, and twelve bits counting within the millisecond. Here are three from machine seven: two in the same millisecond, where the sequence counts up, and one in the next, where the time field ticks and the sequence starts again at zero. Forty-one bits of milliseconds last about seventy years, and each machine can mint four thousand and ninety-six IDs a millisecond, with no coordination beyond handing out machine numbers. UUID version seven, standardised in RFC 9562 in 2024, does the same in a hundred and twenty-eight bits: forty-eight bits of Unix milliseconds first, then seventy-four random bits. They sort by creation time, with no machine numbers.

Time-ordered IDs inherit the troubles of Part 38's clocks. Suppose the time daemon steps a machine's clock back five milliseconds. The generator sees a millisecond it has already used, restarts its sequence at zero, and mints an ID it minted before. The fix is to remember the last timestamp issued and never go below it: keep counting within that millisecond, and wait when the sequence runs out. Across machines, clocks disagree as well, so IDs from different machines are ordered only to within the skew between them. Sort and page by them, but never use them to decide which of two writes came first.

Ordered IDs pay off in the index, Part 17's B-tree. Insert two hundred thousand keys into the leaf level of a B-plus tree, a hundred keys to a page. Random keys land all over the tree and split pages in half, leaving them sixty-nine percent full: two thousand eight hundred and eighty-nine pages. Time-ordered keys only ever touch the rightmost page, so every page fills completely: two thousand pages. The bigger difference is the working set. The last ten thousand random inserts touched two thousand seven hundred and thirty pages, all of which must stay in memory; ordered inserts touched a hundred and one. The price: the rightmost page, or chapter eight's last range shard, becomes the hot spot, and every ID reveals when it was made.

11Blobs and the edgeIndustry3 min

The Job takes books, and books are blobs: big, opaque, written once and read many times. In database rows, they would ride along in every backup, replica and cache. Instead the database keeps a small row describing the book: its hash, and a key. The bytes go to an object store, a flat map from keys to immutable objects, read and written whole over HTTP: Amazon's S3 since 2006, and its imitators. Two systems must now agree, so write the bytes first and the row second. A row never points at nothing; at worst a blob is orphaned, and a sweeper deletes it.

An object store's whole promise is that bytes are not lost. Three full copies survive two failed disks, for three times the space. Erasure coding does better. Cut the object into ten fragments and compute four more with a Reed-Solomon code, so that any ten of the fourteen rebuild it. Lose any four disks, and nothing is lost. Part 45's model, with two percent of disks failing a year and a day to repair, gives the chance of losing an object in a year. Three copies: about four in ten billion. Ten plus four: about four and a half in a hundred trillion, in less than half the space.

Who carries the bytes? Not the application servers, if we can help it. The client asks the API for permission to upload. The API holds a secret key, and returns a URL naming the object and an expiry time, signed with a keyed hash, an HMAC, of exactly those. The client sends the bytes straight to the store, which shares the key and checks the signature. Change the object or the expiry and it fails; after the expiry, the request is refused. Downloads work the same way. But the link is a capability: whoever holds it may use it, so keep expiries short.

Downloads go through the content delivery network of Parts 42 and 45, and an edge cache is only as good as its key. By default the key is the whole URL. Add a tracking parameter or a signature, and three requests for the same book are three keys and three misses at the origin. So normalise the key: drop parameters that do not change the bytes, and check signatures at the edge but leave them out of the key. One miss, two hits. A Vary header adds request headers to the key: by encoding, a few versions; by user agent, thousands. Better, put the content hash in the URL. Those bytes never change, so the edge may keep them for a year, and a new version is a new name.

12Maps as keysGraduate4 min

A map query is a box in two dimensions: every café within a kilometre. But Part 35's B-tree orders a single number. Index longitude alone, and the box returns a whole strip: twenty-three of Part 22's sixty points. Latitude alone returns twenty-two. The box holds eight. We want one key for every place, so that places near each other get keys near each other. Then an ordinary index will do.

The oldest answer interleaves the bits. Take the cell at x five, y three, write both in binary, and take one bit of y, then one of x, in turn: twenty-seven. Number every cell this way and the keys trace a Z at every scale, as Guy Morton described at IBM in 1966. Each pair of bits picks a quadrant, so a square on the map is a range of keys. The flaw is the jumps: cells fifteen and thirty-seven are side by side.

Geohash, published by Gustavo Niemeyer in 2008, is the Z-order on the globe. Halve longitude, then latitude, in turn, and spell every five bits as one of thirty-two characters: the first names one of these thirty-two cells. Each further character divides the cell by thirty-two: seven pin central London to about ninety-five metres by a hundred and fifty-three. New York shares no prefix with London. But London sits on the edge of cell g; east of the Greenwich meridian, addresses begin with u. So a search covers the cell and its eight neighbours.

David Hilbert's curve of 1891 removes the jumps. It visits the same quadrants, but rotates the pieces so that every step moves next door. Ask for this box of twelve cells. Along the Z it falls into seven runs of keys, seven range scans; along Hilbert, four. On a grid of two hundred and fifty-six squared, a sixteen by sixteen box needs about thirty ranges on the Z and fifteen on Hilbert. Some neighbours still land far apart on both: every curve must break somewhere. Google's S2 projects the Earth onto a cube, orders each face along a Hilbert curve, and names cells with sixty-four bit integers, thirty levels deep.

Geohash and S2 cut the map the same way everywhere. A quadtree cuts only where it must: split any square holding more than three points, and repeat, so cells are small in the city and large over the sea. Squares are awkward for movement: four neighbours share an edge, four only a corner, one point four one widths away. A hexagon's six neighbours are all equally far. Uber's H3, open-sourced in 2018, tiles the Earth with hexagons at sixteen resolutions, each cell about a seventh of its parent. The price: twelve pentagons at every resolution, and children that only roughly tile their parent.

The commonest map question is: what are the nearest three? Look in the query's cell, then in rings around it, until there are three candidates. That is not yet the answer: the circle through the third reaches cells not yet searched, where a closer point could hide. Search those too, then rank by exact distance. Part 22's kd-tree found one nearest neighbour among twenty thousand points by visiting about twenty-five of its forty thousand nodes. PostGIS answers such queries from its R-tree index, and Part 49's ride-hailing dispatcher asks them of hexagons.

13Real-time blocksIndustry3 min

Most of the web is a client asking and a server answering; real-time features need the server to speak first. The simplest trick is polling: ask every ten seconds. News waits for the next poll, and most answers are empty. Long polling, named Comet in 2006, sends a request the server holds until there is news, then asks again at once: plain HTTP, one round trip per message. A WebSocket, standardised in RFC 6455 in 2011, starts as an HTTP request and is upgraded into a two-way connection that stays open; each message is a frame with a few bytes of header. For one-way streams, Server-Sent Events keep one HTTP response open.

Open connections are state. Connection servers each hold many thousands of sockets. To reach a user, look up their server in a registry, and forward the message there. When a server dies, all its clients reconnect at once, to the others. Part 43 measured that shape: a service down for ten seconds, with clients retrying every second, was offered nine hundred and ninety requests a second against a capacity of a hundred, and recovered only at second a hundred and nineteen. With exponential backoff and jitter, the peak was three hundred and eighty-one, and recovery came at sixty-nine. So clients reconnect with jitter, and servers are drained before they stop.

Notifications reach people who are not looking. An event enters a notification service, which checks the user's preferences, applies chapter five's rate limits, and stamps an idempotency key. A queue feeds a worker per channel: push, email, text. Push goes through Apple's or Google's service, because a phone keeps one connection for all its apps. Apps that poll on their own keep waking the radio. In Part 42's model, ten requests twenty seconds apart cost about a hundred and thirty joules; the same ten together, sixteen and a half, nearly eight times less. Delivery is at least once, so the idempotency key lets the phone drop a repeat.

Presence, the green dot beside a name, is a failure detector. Each heartbeat renews a key that otherwise expires; when the heartbeats stop, the key expires, and the user is offline. The timeout is Part 39's trade-off. With heartbeats every tenth of a second, delayed at random, a timeout that notices a crash in about a hundred milliseconds raises hundreds of false alarms an hour; one that raises none takes three seconds. Phi accrual adapts to the delays it has seen. And every change is news for every friend, a fan-out like Part 49's feeds, so many apps fetch presence only for the people on screen.

14The Job as a serviceIndustry3 min

The Job, one more time, now as a service: upload a book, or name one, and get its twenty most common words. Requests arrive at a load balancer, which spreads them over stateless API servers. An API server first asks a result cache; on a miss, it puts the work on a queue, and one of 8 workers fetches the book from a blob store and counts it. Our model has 3,000 books, some far more popular than others, and a count takes 80 milliseconds on average. The napkin says the workers can handle 100 requests a second if they are never idle. Never idle is the problem.

So we load-tested the design in simulation, raising the rate of requests and measuring the median and the ninety-ninth percentile response time. Without a cache, the median sits near 55 milliseconds and the tail near 364, until the workers get busy. At 95 requests a second they are 95 percent busy, and the tail has grown to 607 milliseconds: Part 31's queueing curve again. Add a result cache of three hundred entries. Because popularity is so skewed, 63 percent of requests hit it and return in a millisecond, so the median collapses, and the workers see only the misses: the same tail now holds to about 200 requests a second, more than double. Notice that the median says little; the tail tells you where the knee is.

Why did three hundred entries do so much? Chapter three's formula answers it. For the Job's own catalogue, three thousand books with Zipf popularity, Che's formula predicts that three hundred entries catch 63 percent, which is what the service measured. In chapter three's catalogue of a hundred thousand, the same three hundred catch only 24 percent with LRU, as the bars show; an admission filter like TinyLFU catches 33, close to the best possible fixed set. A hit rate h multiplies capacity by one over one minus h, as long as the cache is cheap to ask, which is why caches appear in every design. The price is that answers can be stale when a book changes, and that a popular entry expiring can set off a stampede, the problems of chapter four.

15Frontier: design as a scienceResearch1 min

Can a design be predicted, and not just argued for? An index maps a key to a position. A B-tree does it with a hierarchy of sorted pages, knowing nothing about the keys. But the map from key to position is a function, and a function can be learned. Fit a few straight lines to it, each guaranteed to predict a position within a fixed error, and finish with a short binary search. On a million bursty timestamps, an error bound of 32 needs 380 segments, about 9 kilobytes, and seven comparisons; the B-tree's inner nodes take about 70 kilobytes and some 24 comparisons. Tim Kraska and colleagues made the case for learned indexes in 2018; the PGM-index of Paolo Ferragina and Giorgio Vinciguerra added worst-case guarantees. Learned structures for updates, multiple dimensions and shifting data remain open.

Recap, problems, and where this comes backAll tracks3 min

What we built in this part. A napkin that turns daily users into queries per second, terabytes and bandwidth. Load balancing by two random choices and Maglev's table, which barely moves anything when a server leaves. Caches whose hit rates Che's formula predicts, and an admission filter that beats LRU. Stampedes, and the probabilistic early refresh that removes them. Token buckets, and why a fixed window lets through twice its limit. Identifiers that sort by time, and why random keys scatter a B-tree. Curves that turn a map into keys. And the Job as a service, whose tail more than doubled its capacity with a small cache. One idea runs through it: estimate first, and let the numbers choose the blocks.

Where this comes back. Part 49 designs eight whole systems, from a URL shortener to a ride-hailing service, with these blocks. Part 50 keeps them running, with service-level objectives and capacity plans. Part 56 looks at load and expansion through the spectrum of a graph, Part 59 at the theory of the distributed algorithms underneath, and Part 60 at hardware that keeps changing the napkin's numbers.

In practice. Estimate the peak queries per second, the storage over years and the bandwidth, to within a factor of a few, before drawing a box. Balance with the less loaded of two random choices, and hash consistently where affinity matters. Measure your cache's hit rate, jitter its expiry times, coalesce identical requests and refresh popular entries early. Put token buckets at the edge, and use sliding windows rather than fixed ones. And choose time-ordered identifiers for B-trees, and shard keys that spread the hot data.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: add request coalescing to the Job service, so that each missing key is rebuilt once, and measure the tail while the cache is flushed. The last, marked with a star, is a research problem: an admission policy with a proof of how close it stays to the best cache when popularity drifts.

Next time, Part 49: system design case studies. Eight systems everyone uses, a URL shortener, a news feed, a chat service, a video platform, a ride-hailing dispatcher and more, each designed from the napkin up with this part's blocks, and stress-tested in simulation.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 49 designs eight whole systems with these blocks, from a URL shortener to a ride-hailing service. Part 50 keeps them running, with service-level objectives, retries and capacity plans, and returns to metastable failures. Part 56 looks at load and expansion through the spectrum of a graph, and Part 59 at the theory of the distributed algorithms underneath.

Key results

The part's results in one place, for revision.

Che's approximation\(\displaystyle \sum_i\bigl(1-e^{-p_iT}\bigr)=C,\qquad\allowbreak h=\sum_i p_i\bigl(1-e^{-p_iT}\bigr)\)
XFetch\(\displaystyle \text{refresh }\allowbreak \text{if } t-\Delta\beta\ln U\ \ge\ \text{expiry};\quad\allowbreak P(\text{trigger }\allowbreak \text{at } r)=e^{-r/\beta\Delta}\)
Token bucket envelope\(\displaystyle A(t,\,t+s)\ \le\ \sigma+\rho s\quad\allowbreak \text{for }\allowbreak \text{every } t \text{ and } s\ge 0\)
Birthday bound, UUIDv4\(\displaystyle P(\text{collision }\allowbreak \text{among } n)\approx 1-e^{-n^2/2^{123}}\)
Little's law\(\displaystyle L=\lambda W:\quad\allowbreak 210/\text{s}\times 0.5\ \text{s}=105 \text{ busy }\allowbreak \text{workers}\)
What a cache buys\(\displaystyle \text{capacity}\ \times\ \frac{1}{1-h}\quad\allowbreak \text{at }\allowbreak \text{hit }\allowbreak \text{rate } h\)

Try it

Lab 48 · Three blocks against their formulas: a cache, a rate limiter, an expiring key

Run the series' LRU cache on a Zipf trace and compare its hit rate with Che's approximation at five sizes, check every interval of a token bucket's output against the envelope sigma + rho s, and count the rebuilds of one hot key with and without probabilistic early expiration.

Figure produced by Lab 48: Three blocks against their formulas: a cache, a rate limiter, an expiring key
Produced by the lab below, seed 0, in 0.3 s.
python -m videos.cs.labs 48 needs numpy, scipy, matplotlib · download lab48.py · source on GitHub
cache of    30 entries: LRU hit rate       12.0%   Che 12.0%   best static set 26.6%
cache of   100 entries: LRU hit rate       22.2%   Che 22.2%   best static set 36.7%
cache of   300 entries: LRU hit rate       33.2%   Che 33.2%   best static set 47.2%
cache of 1,000 entries: LRU hit rate       47.6%   Che 47.6%   best static set 60.2%
cache of 3,000 entries: LRU hit rate       63.1%   Che 63.6%   best static set 73.4%
token bucket (sigma 20, rho 100 a minute)  admitted 786 of 1112; worst interval is 0.01 under sigma + rho s
hot key, 300 s: rebuilds                   1,603 without early expiration (about 200 x 2 = 400 per expiry), 6 with it; misses 1,603 against 0

A formula with one unknown, the characteristic time, predicts the LRU hit rate to within a point; the bucket's guarantee holds on every interval; a random early refresh replaces 400 rebuilds by one.
The code (98 lines; it asserts its own result)
"""Lab 48: predict an LRU cache's hit rate with Che's approximation, then check a token bucket's envelope and a stampede."""

from videos.coursekit import labs  # noqa: I001  (must stay first: it lets explainer.cs import without manim)

import numpy as np

from explainer.cs.design import blocks

TITLE = "Three blocks against their formulas: a cache, a rate limiter, an expiring key"
GOAL = ("Run the series' LRU cache on a Zipf trace and compare its hit rate with Che's approximation at five sizes, "
        "check every interval of a token bucket's output against the envelope sigma + rho s, and count the rebuilds "
        "of one hot key with and without probabilistic early expiration.")
TASKS = [
    "Change the Zipf exponent from 0.9 to 0.6 and to 1.2. Where does Che's formula stay within a point of the simulation, and how does the hit rate at 1,000 entries move?",
    "Replace blocks.lru_hits by blocks.tinylfu_hits in the first loop. At which sizes does admission by frequency beat Che's LRU prediction, and how close does it come to the best static set?",
    "Raise beta in blocks.stampede from 1 to 3 and count the rebuilds in 300 s. What does the earlier refresh cost, and what does it buy?",
]

ITEMS, REQUESTS, S = 20_000, 120_000, 0.9
SIZES = (30, 100, 300, 1000, 3000)
SIGMA, RHO = 20, 100 / 60.0


def bursty(rng, horizon=600.0):
    """Arrival times that alternate 30 s at four a second with 60 s at 0.8 a second."""
    t, out = 0.0, []
    while t < horizon:
        t += rng.exponential(1 / (4.0 if int(t / 30) % 3 == 0 else 0.8))
        out.append(float(t))
    return out


def worst_excess(allowed, rate, burst, longest=10.0):
    """Brute force: the largest count in any interval [t_i, t_j] of at most `longest` seconds, minus its allowance."""
    a = np.array(allowed)
    worst = -np.inf
    for i in range(len(a)):
        j = np.searchsorted(a, a[i] + longest, side="right")
        span = a[i:j] - a[i]
        worst = max(worst, float(np.max(np.arange(1, j - i + 1) - (burst + rate * span))))
    return worst


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    # 1. LRU on Zipf traffic against Che's approximation
    trace, p = blocks.zipf_trace(REQUESTS, ITEMS, S, seed)
    tr = trace.tolist()
    lru = [blocks.lru_hits(tr, c) for c in SIZES]
    che = [blocks.che(p, c) for c in SIZES]
    static = [float(np.sort(p)[::-1][:c].sum()) for c in SIZES]
    for c, a, b, st in zip(SIZES, lru, che, static):
        lab.row(f"cache of {c:>5,} entries: LRU hit rate", f"{a:.1%}   Che {b:.1%}   best static set {st:.1%}")
        assert abs(a - b) < 0.015, "Che's approximation is within 1.5 points of the simulated LRU"
        assert a < st, "no LRU beats the best static set under independent references"

    # 2. a token bucket never exceeds sigma + rho s, in any interval; fixed windows do exceed their limit
    arrivals = bursty(rng)
    allowed = blocks.token_bucket(arrivals, RHO, SIGMA)
    ok, _ = blocks.envelope_ok(allowed, RHO, SIGMA)
    excess = worst_excess(allowed, RHO, SIGMA)
    assert ok and excess <= 1e-9, "every interval of the bucket's output is under the envelope"
    assert worst_excess(arrivals, RHO, SIGMA) > 0, "the raw trace does break the envelope, so the check can fail"
    lab.row("token bucket (sigma 20, rho 100 a minute)", f"admitted {len(allowed)} of {len(arrivals)}; "
            f"worst interval is {-excess:.2f} under sigma + rho s")

    # 3. one hot key: a stampede at every expiry, against XFetch's early refresh
    plain = blocks.stampede(seed=seed + 3)
    early = blocks.stampede(seed=seed + 3, early=True)
    assert plain["recomputations"] > 100 * early["recomputations"] and early["misses"] == 0
    assert abs(plain["recomputations"] / plain["expiries"] - 400) < 60, "about rate x rebuild time = 400 per expiry"
    lab.row("hot key, 300 s: rebuilds", f"{plain['recomputations']:,} without early expiration "
            f"(about 200 x 2 = 400 per expiry), {early['recomputations']} with it; misses {plain['misses']:,} against {early['misses']}")
    lab.note = ("A formula with one unknown, the characteristic time, predicts the LRU hit rate to within a point; "
                "the bucket's guarantee holds on every interval; a random early refresh replaces 400 rebuilds by one.")

    fig, ax = labs.figure(2, size=(11, 4.3))
    grid = np.unique(np.round(np.geomspace(20, 5000, 24)).astype(int))
    ax[0].semilogx(grid, [blocks.che(p, int(c)) for c in grid], color=labs.GOLD, label="Che's approximation")
    ax[0].semilogx(grid, [float(np.sort(p)[::-1][:int(c)].sum()) for c in grid], color=labs.MUTED, ls="--",
                   label="best static set")
    ax[0].semilogx(SIZES, lru, "o", color=labs.BLUE, label="simulated LRU")
    ax[0].set(title=f"Hit rate on Zipf traffic (s = {S}, {ITEMS:,} items)", xlabel="cache size (entries)",
              ylabel="hit rate", ylim=(0, 0.85))
    ax[0].legend(loc="upper left")
    a = np.array(allowed)
    start = int(np.argmax([np.searchsorted(a, t + 10.0) - i for i, t in enumerate(a)]))  # the busiest ten seconds
    window = a[start:np.searchsorted(a, a[start] + 10.0)] - a[start]
    s = np.linspace(0, 10, 50)
    ax[1].plot(s, SIGMA + RHO * s, color=labs.RED, label="envelope: 20 + (100/60) s")
    ax[1].step(window, np.arange(1, len(window) + 1), where="post", color=labs.GREEN, label="admitted, busiest 10 s")
    ax[1].set(title="The token bucket's busiest ten seconds", xlabel="seconds since the interval began",
              ylabel="requests admitted", xlim=(0, 10), ylim=(0, 42))
    ax[1].legend(loc="lower right")
    lab.fig = fig
    return lab

Now change it

  1. Change the Zipf exponent from 0.9 to 0.6 and to 1.2. Where does Che's formula stay within a point of the simulation, and how does the hit rate at 1,000 entries move?
  2. Replace blocks.lru_hits by blocks.tinylfu_hits in the first loop. At which sizes does admission by frequency beat Che's LRU prediction, and how close does it come to the best static set?
  3. Raise beta in blocks.stampede from 1 to 3 and count the rebuilds in 300 s. What does the earlier refresh cost, and what does it buy?

Problems, with solutions

Try each problem before opening its solution.

  1. Consistent hashing. Show that removing one of n backends from a consistent-hash ring moves only the keys it owned, and compute the load imbalance with v virtual nodes.

    Solution

    Let P be the set of points on the ring (v for each backend) and send a key k to succ_P(h(k)), the first point of P clockwise from h(k). Removing backend b leaves P′ = P \ P_b. If succ_P(h(k)) = p belongs to another backend, then p ∈ P′, and no point of P′ lies strictly between h(k) and p, since P′ ⊂ P and no point of P did; so succ_P′(h(k)) = p and k stays. Only the keys whose successor was one of b's points move, each to the next surviving point clockwise, and with v points b's keys are spread over up to v different neighbours instead of landing on one. Our ring moved 0% of the other keys when one of 20 backends left (Maglev, which rebuilds its table, moved 0.34%). For the imbalance: the nv points are independent and uniform, and a backend owns the v arcs that end at its points. The nv arcs are uniform spacings, jointly Dirichlet(1, …, 1), so one backend's share is the sum of v of them, Beta(v, (n − 1)v): mean 1/n, variance (n − 1)/(n²(nv + 1)), a relative standard deviation √((n − 1)/(nv + 1)) ≈ 1/√v. The busiest of the n is then about 1 + z_n/√v times the mean, with z_n ≈ 1.87 the expected largest of 20 standard normals (about √(2 ln n) for large n): 1.18 for n = 20 and v = 100. For v = 1 the exact answer is the expected largest of n uniform spacings, H_n/n, so the busiest backend carries H_n times the mean, 3.60 for n = 20. Over 2,000 random rings of 20 backends the busiest carried, on average, 1.68 times the mean at v = 10, 1.19 at v = 100 and 1.06 at v = 1,000; the instrument's own ring (hashed with BLAKE2b) gave 3.81, 1.52, 1.17 and 1.05 at v = 1, 10, 100 and 1,000, and 1.13 after the removal shown in chapter 2. The 1/√v decay is slow: to bring the busiest within 1% of the mean takes v ≈ (1.87/0.01)² ≈ 35,000 points a backend, which is why Maglev fills a table instead (1.03 with 65,537 slots).

  2. Che's approximation. Derive Che's approximation for LRU under independent references, and check it against a simulation.

    Solution

    Under the independent reference model each request is for item i with probability p_i, independently of all others. An LRU cache of C entries holds exactly the C distinct items most recently requested, so item i is in the cache just before a request if and only if it was requested within the last τ_i requests, where τ_i is the number of most recent requests it takes to see C distinct items other than i. τ_i is random and depends on i; Che, Tung and Wang replace it by one constant T, the characteristic time. The justification is that τ_i is a sum over many items, so it concentrates, and removing one item from a large catalogue barely changes it (Fricker, Robert and Roberts explain why the approximation is so accurate). Then P(i cached) = 1 − (1 − p_i)^T ≈ 1 − e^(−p_i T) (exact for Poisson requests in continuous time). The cache holds C items, so the expected number cached is C: Σ_i (1 − e^(−p_i T)) = C. The left side rises continuously from 0 to N, the number of items, so for 0 < C < N it fixes a unique T, found by bisection; and since 1 − e^(−x) ≤ x, C ≤ Σ p_i T = T, so T ≥ C. A request is for i with probability p_i, independently of the cache's state, and hits exactly when i is cached: h = Σ_i p_i (1 − e^(−p_i T)). For our 100,000 items with Zipf exponent 0.9, T is 111, 363, 1,362, 4,746 and 20,172 requests for C = 100, 300, 1,000, 3,000 and 10,000, and the formula gives 15.6%, 23.7%, 34.2%, 45.5% and 60.5% against simulated LRU hit rates of 15.7%, 23.7%, 34.2%, 45.4% and 60.1% on 400,000 requests, within 0.5 percentage points everywhere; tests/test_cs48_design.py checks the same on a smaller trace. On the Job service's catalogue (3,000 books, exponent 1) the formula gives 63.0% at 300 entries, against the 63% measured in chapter 14.

  3. Early expiration. Show that XFetch's early-refresh rule makes the expected number of concurrent rebuilds at expiry O(1).

    Solution

    Requests arrive as a Poisson process of rate λ; the value expires at time E; a rebuild takes Δ, after which the new value and a new expiry are in place. A request at time E − r (r > 0) refreshes if −Δβ ln U ≥ r, with U uniform on (0, 1), and, as in the rule's plain form, any request may do so. Since −ln U is exponential with mean 1, it triggers with probability e^(−r/βΔ), independently of the others, so the triggers form a Poisson process whose intensity at remaining time r is λe^(−r/βΔ). Let R be the remaining time at the first trigger and X = λβΔ e^(−R/βΔ) = ∫R^∞ λe^(−u/βΔ) du, the intensity accumulated before it. Then P(R ≤ r) = P(no trigger at remaining times above r) = exp(−λβΔ e^(−r/βΔ)), so P(X ≥ x) = e^(−x): X is exponential with mean 1, as the accumulated intensity at a Poisson process's first event always is. The rebuilds concurrent with the first are the triggers in the next Δ seconds, at remaining times between R − Δ and R; given R their expected number is at most ∫(R−Δ)^R λe^(−r/βΔ) dr = X(e^(1/β) − 1). So the expected number of concurrent rebuilds is at most 1 + E[X](e^(1/β) − 1) = e^(1/β), whatever λ and Δ: 2.72 for β = 1. One case remains: if R < Δ the old value expires before the new one lands, and requests in between miss; P(R < Δ) = exp(−λβΔ e^(−1/β)), so the expected misses are at most λΔ exp(−λβΔ e^(−1/β)) ≤ e^(1/β − 1)/β, also a constant. In our experiment, λ = 200, Δ = 2 s and β = 1: λβΔ = 400, P(R < Δ) = e^(−147), and the refresh comes on average βΔ(ln λβΔ + γ) = 13.1 s before expiry (median 12.7 s; the scene's 12 s is where the expected count of earlier triggers is one). A Monte Carlo of 20,000 expiries without any lock gave 2.72 concurrent rebuilds on average, matching e. Without early refresh, every request in the Δ after expiry rebuilds, λΔ = 400 of them, and the instrument counted 1,603 in 4 expiries. The instrument also lets only one refresh run at a time, so it starts exactly one per cycle; each cycle is 62 − R seconds, about 48.9 on average, which is the 6 rebuilds in 300 s.

  4. Token bucket. Prove that a token bucket with rate ρ and depth σ admits at most σ + ρt requests in any interval of length t.

    Solution

    Let b(u) be the number of tokens at time u. Tokens accrue at rate ρ but never above σ, and an admitted request removes one token, which is only allowed when b ≥ 1, so b stays in [0, σ]. Take an interval [s, s + t] and let b₀ be the tokens just before its first admission. During the interval the tokens actually added, R, are at most ρt (capping at σ only discards some), and each of the A admissions spends one, so the tokens at the end are b₀ + R − A ≥ 0. Hence A ≤ b₀ + R ≤ σ + ρt. The bound is tight up to rounding: a sender that finds the bucket full and then sends whenever a token arrives is admitted σ + ⌊ρt⌋ in an interval of length t, the staircase drawn in chapter 5. With σ = 20 and ρ = 100 a minute, any minute admits at most 120 and any 10 s at most 36, and the check on every interval of up to 10 s of our trace found no violation; fixed windows with a limit of 100 admitted 138 in one minute, and up to 200 are possible. Since envelopes add, n such clients send a service at most nσ + nρt in any interval of length t, which is what makes the worst case something to size for.

  5. Build. Add request coalescing to the Job service (one rebuild per missing key) and measure p99 during a cache flush.

    Solution

    Solution sketch. First make the cache honest. keys.job_service puts a missed book into the cache the moment the request arrives, so a request for it during the 80 ms count already hits in 1 ms: as written, the model coalesces perfectly and for free. Keep instead a heap of (finish time, book), and before each arrival pop the counts that have finished and insert their books into the LRU. Then coalesce: a dictionary inflight from book to the finish time of its count; on a miss, if the book is in flight, the request waits for that count (its latency is the finish time minus now) and starts no work; otherwise it schedules a count on the earliest free worker, as now, and records it. For the flush, clear the cache at the 15,000th of 30,000 requests and take the 99th percentile of the requests in the following five seconds, with and without coalescing, at several rates. A sketch along these lines (seed 3, a 300-entry cache) gave, over the five seconds after the flush, 340 ms both ways at 100 requests a second, 362 against 340 ms at 150, and 659 against 431 ms at 200; over the whole run at 200, 444 against 331 ms, with 11,283 counts run against 11,131. The gain is modest because a count is short: at 200 requests a second about 16 arrive during one 80 ms count, and the most popular book is 1/H₃₀₀₀ ≈ 11.6% of them, so it is counted about twice over without coalescing. A complete answer sweeps the work time and the skew, where coalescing matters more, and reports how fast the hit rate recovers after the flush.

  6. ★ Research. A cache admission policy with a provable competitive ratio on drifting Zipf traffic.

    Discussion. Open. The classical analyses answer different questions. Against Belady's offline optimum, every deterministic online policy, LRU included, is at best C-competitive for a cache of C entries (Sleator and Tarjan), a worst case that says nothing about Zipf traffic. Against the best static set, stationary independent references are easy: exact frequency counts converge to the most popular items, which is the best static set. With drift the comparator has to move as well: the best static set over the whole trace is a weak target, while the best set within each window of W requests is a strong one, and online-learning formulations of caching that bound regret against a fixed cache are stated for fractional caches and adversarial sequences, not for an integral cache that can only admit or refuse a candidate against an LRU victim, as TinyLFU does, through a sketch that makes errors. A good partial answer would fix a drift model (for instance, ranks that swap with a neighbour at rate δ per request, or new items entering at the top at rate δ), take the best set in each window as the comparator, prove that a frequency filter which halves its counts every W requests (as our CountMin does every ten widths) keeps a hit rate within a stated additive term of it, with an error from sampling that falls as W grows and an error from drift that rises with δW, choose W to balance them, and show a lower bound for the same trade-off. It should be checked in our simulator against the moving optimum; on the stationary trace W-TinyLFU already trails the best static set by 3.9 points at 300 entries (33.3% against 37.2%) and 4.1 at 1,000 (43.3% against 47.4%).

Notes and sources

Glossary

  • back-of-the-envelope estimate, QPS, peak factor, latency numbers — a design's arithmetic before its boxes; requests a second; the peak against the mean; orders of magnitude to carry.
  • functional and non-functional requirements, service-level objective (SLO), error budget — what a system does and how well; a measurable target over a window; the failure it allows.
  • capacity model, data model, high-level design, deep dive, design document — the decisions of a design, in order, and where they are written down.
  • layer-4 and layer-7 load balancing, round robin, least connections, power of two choices — forwarding connections or requests; policies for choosing a server.
  • consistent hashing, virtual node, Maglev hashing, lookup table, disruption — mapping keys to servers so that few move when the set changes.
  • health check, outlier ejection — probing servers; removing the ones whose real traffic fails.
  • cache-aside, read-through, write-through, write-back — four ways to connect a cache to its store.
  • LRU, LFU, W-TinyLFU, admission, Count-Min sketch, ageing — what to evict; what to let in; counting popularity approximately, and forgetting it.
  • independent reference model, Che's approximation, characteristic time, best static set — a model of requests; a formula for LRU's hit rate; the most popular items as a yardstick.
  • invalidation, TTL, jitter — removing stale copies; a bound on their life; spreading expiries.
  • cache stampede (thundering herd), request coalescing (single flight), lease, probabilistic early expiration (XFetch) — a hot key's expiry aimed at the store; rebuilding once; a token for the right to fill; refreshing before expiry at random.
  • token bucket, (σ, ρ) envelope, leaky bucket, GCRA, theoretical arrival time — limiting rate with bursts; the guarantee it gives; shaping instead of policing; the same bucket as one timestamp.
  • fixed window, sliding log, sliding-window counter, 429, Retry-After — counting requests in time; refusing politely.
  • asynchronous work, 202 Accepted, worker pool, backpressure, delayed job, timing wheel, full jitter, dead-letter queue — work done after the answer; how it is scheduled, retried and given up on.
  • Little's law, Pollaczek–Khinchine formula, SRPT, Erlang's pooling — queueing results that size pools and order work.
  • row store, column store, B-tree, LSM tree, write amplification, Bloom filter — layouts and engines, and what they cost per write and per read.
  • normalisation, denormalisation, source of truth, secondary index, clustered order — where each fact lives, and how it is found.
  • shard key, range and hash partitioning, hot key, celebrity problem, salting — splitting data across machines; keys too popular to split; splitting them anyway.
  • resharding, fixed partitions, routing table, scatter–gather, local and global secondary indexes — moving data while it is used; queries over many shards.
  • leader, follower, replication lag, read-your-writes, failover, semi-synchronous replication — copies in practice, and what they cost when the leader fails.
  • split brain, fencing token, active–active, last writer wins, version vector — two leaders at once; numbering their authority; writes accepted everywhere and their conflicts.
  • UUIDv4, UUIDv7, Snowflake ID, ticket server, birthday bound — names minted without coordination, and the odds that two collide.
  • object store, blob, multipart upload, content addressing, content-defined chunking, erasure coding, Reed–Solomon — storing large immutable bytes cheaply and durably.
  • signed URL, HMAC, capability, cache key, Vary, immutable — handing out access to bytes; what an edge cache treats as the same request.
  • space-filling curve, Z-order (Morton), geohash, Hilbert curve, S2 cell, quadtree, H3 — turning places into keys that an ordinary index can range over.
  • nearest-neighbour query, kd-tree, R-tree — finding what is close.
  • long polling, WebSocket, Server-Sent Events, connection registry, push notification, presence, fan-out — letting the server speak first, and the state that costs.
  • learned index, PGM-index, queueing network, metastable failure — the frontier: indexes fitted to data, predicted systems, outages that sustain themselves.

Sources

  • M. Kleppmann, Designing Data-Intensive Applications (2017); A. Xu, System Design Interview: An Insider's Guide (2020), and A. Xu and S. Lam, volume 2 (2022); B. Burns, Designing Distributed Systems (2018); A. Petrov, Database Internals (2019); L. A. Barroso, U. Hölzle and P. Ranganathan, The Datacenter as a Computer (third edition, 2018).
  • D. Karger, E. Lehman, T. Leighton, R. Panigrahy, M. Levine and D. Lewin, "Consistent hashing and random trees", STOC 1997; M. Mitzenmacher, "The power of two choices in randomized load balancing", IEEE Trans. Parallel and Distributed Systems 2001; D. E. Eisenbud et al., "Maglev: a fast and reliable software network load balancer", NSDI 2016.
  • L. A. Belady, "A study of replacement algorithms for a virtual-storage computer", IBM Systems Journal 1966; D. Sleator and R. Tarjan, "Amortized efficiency of list update and paging rules", Comm. ACM 1985.
  • H. Che, Y. Tung and Z. Wang, "Hierarchical Web caching systems: modeling, design and experimental results", IEEE J. Selected Areas in Communications 2002; C. Fricker, P. Robert and J. Roberts, "A versatile and accurate approximation for LRU cache performance", ITC 2012; G. Einziger, R. Friedman and B. Manes, "TinyLFU: a highly efficient cache admission policy", ACM Trans. Storage 2017.
  • R. Nishtala et al., "Scaling Memcache at Facebook", NSDI 2013; A. Vattani, F. Chierichetti and K. Lowenstein, "Optimal probabilistic cache stampede prevention", PVLDB 2015.
  • R. L. Cruz, "A calculus for network delay, Part I: network elements in isolation", IEEE Trans. Information Theory 1991; Cloudflare, "How we built rate limiting capable of scaling to millions of domains" (2017).
  • J. D. C. Little, "A proof for the queuing formula L = λW", Operations Research 1961.
  • E. F. Codd, "A relational model of data for large shared data banks", Comm. ACM 1970; F. Chang et al., "Bigtable: a distributed storage system for structured data", OSDI 2006; G. DeCandia et al., "Dynamo: Amazon's highly available key-value store", SOSP 2007; J. C. Corbett et al., "Spanner: Google's globally-distributed database", OSDI 2012; M. Burrows, "The Chubby lock service for loosely-coupled distributed systems", OSDI 2006.
  • K. Davis, B. Peabody and P. Leach, RFC 9562, "Universally Unique IDentifiers (UUIDs)" (2024).
  • I. S. Reed and G. Solomon, "Polynomial codes over certain finite fields", J. SIAM 1960; A. Muthitacharoen, B. Chen and D. Mazières, "A low-bandwidth network file system", SOSP 2001.
  • D. Hilbert, "Über die stetige Abbildung einer Linie auf ein Flächenstück", Mathematische Annalen 1891; G. M. Morton, "A computer oriented geodetic data base and a new technique in file sequencing", IBM (1966); the S2 Geometry documentation (s2geometry.io) and the H3 documentation (h3geo.org).
  • I. Fette and A. Melnikov, RFC 6455, "The WebSocket Protocol" (2011).
  • T. Kraska, A. Beutel, E. H. Chi, J. Dean and N. Polyzotis, "The case for learned index structures", SIGMOD 2018; P. Ferragina and G. Vinciguerra, "The PGM-index: a fully-dynamic compressed learned index with provable worst-case bounds", PVLDB 2020; N. Bronson, A. Aghayev, A. Charapko and T. Zhu, "Metastable failures in distributed systems", HotOS 2021.
About this partfrom its README

Part 48 of a sixty-one-part course in computer science (see the series plan and the syllabus), the fourth part of Act IX, Systems at Scale, and the first of two parts on system design. A large system is assembled from a small set of blocks (load balancers, caches, rate limiters, queues, shards, replicas, identifiers, blob stores and indexes for maps), chosen under numbers estimated on a napkin, and each block has mathematics of its own: hashing that rebalances gracefully, caches whose hit rate a formula predicts and that survive their own expiry, rate limiters that are token buckets in disguise, identifiers that sort by time without coordination, and curves that turn a map into keys. We build and measure each block, and load-test the Job as a service made from them.

The instruments are in explainer/cs/design/ (tested in tests/test_cs48_design.py), with load balancing from Part 43's explainer/cs/api/; several chapters reuse the cached results of Parts 22, 31, 34, 35, 39, 41, 42, 43, 45 and 47:

  • blocks.py: Maglev's table fill (an offset and a skip from two hashes of each backend's name, 65,537 slots) against a hash ring with virtual nodes, measuring the keys moved needlessly and the load spread when a backend leaves; LRU, in-cache LFU and a simplified W-TinyLFU (a 1% LRU window, admission to the main LRU by a Count-Min sketch that is halved periodically) on Zipf traces, Che's approximation with its characteristic time found by bisection, the best static set, and a one-off scan of cold keys; one hot key's stampede with and without XFetch's probabilistic early refresh; a token bucket with a checker for its (σ, ρ) envelope, fixed windows, and the sliding-window counter against an exact sliding log.
  • keys.py: the birthday bound for UUIDv4; Snowflake and UUIDv7 encoders; the leaf level of a B+ tree under random and time-ordered inserts (pages, fill, pages touched); Morton (Z-order) and Hilbert curves, their locality, and the key ranges a 16 × 16 box needs on a 256 × 256 grid; geohash; the napkin worksheet; the Job as a service (Zipf requests over 3,000 books, eight workers on one queue, an optional LRU result cache); a learned index (the PGM-index's shrinking-cone segmentation with a bounded error) against a B+ tree's inner nodes.
  • explainer/cs/api/services.py (Part 43): balancing, random assignment, round robin, two random choices and the least loaded of all over 50 servers at 90% load.
Chapter notes
  • Hook. The napkin, for an illustrative service: 10 million users a day × 20 actions = 200 million requests a day; ÷ 86,400 ≈ 2,315 a second on average; × 3 at the evening peak ≈ 6,944; one write in eleven ≈ 210 writes a second; 2 kB each, kept 5 years in 3 copies ≈ 199 TB; the reads at the peak move about 13 MB/s. The latency numbers to carry, as orders of magnitude after Jeff Dean's and Peter Norvig's lists (memory ~100 ns, SSD random read ~100 μs, datacentre round trip ~500 μs, disk seek ~10 ms, across a continent 50–100 ms), 2¹⁰ ≈ 10³, a day ≈ 10⁵ s, a year ≈ π × 10⁷ s. Nine blocks, and what this part will do with them.
  • 1. How a design is made. Eight decisions in order (requirements, capacity model, data model, API, high-level design, deep dives, trade-offs, design document), revised when a deep dive breaks an estimate, followed through on a pastebin. Functional and non-functional requirements; the latter turned into service-level objectives (99% of reads within 200 ms; 99.9% of requests succeeding over 30 days, an error budget of about 43 minutes, 3% of a single day). The capacity model from the napkin: 6,944 requests a second at 1,000 a server kept half busy (Part 31) is 14 servers; 210 writes a second, 631 at the peak, is one primary with read replicas; 10 reads per write call for a cache; 199 TB means sharding the records and putting the texts in a blob store; 12.6 MB/s is 101 Mbit/s, a tenth of one 1 Gbit/s link. The data model and API (an idempotency key on create, 410 Gone against 404, a cursor rather than a page number); the high-level design and the question each box hides; trade-offs written down; the design document's sections.
  • 2. Load balancing. Layer 4 (Maglev, IPVS) against layer 7 (NGINX, Envoy, HAProxy). Policies simulated on 50 servers at 90% load, time in the system in mean service times (mean, 99th percentile): random 10.1 and 48.8; round robin 4.8 and 21.0; two random choices 2.6 and 9.1; the least loaded of all 1.2 and 5.2, which needs fresh counts and herds when many balancers have stale ones. Hash modulo N against the ring with virtual nodes (illustrative: removing a server moves only its keys). Maglev's table filled step by step for 3 backends and 7 slots; then 20 backends and 65,537 slots, each owning 3,276 or 3,277: removing one (5% of keys must move), Maglev also moved 0.34% of the others and the ring (100 virtual nodes each) 0%, but Maglev's busiest backend carried 1.03 times the mean against the ring's 1.13. Active health checks, passive outlier ejection, a cap on the share ejected, and slow servers worse than dead ones.
  • 3. Caching: where, and what to keep. Caches at every hop: browser, CDN edge, reverse proxy, application (Redis, Memcached), the database's buffer pool. Cache-aside, read-through, write-through and write-back. LRU, LFU and W-TinyLFU's admission by a Count-Min sketch (Part 20); a one-off scan of 20,000 cold keys takes LRU from 39.1% to 32.5% and TinyLFU from 46.8% to 38.5%, nearly all of both drops the scan's own misses. Che's approximation derived: the characteristic time T, P(i cached) ≈ 1 − e^(−p_i T), Σ(1 − e^(−p_i T)) = C, h = Σ p_i(1 − e^(−p_i T)); at 1,000 entries simulated LRU 34.2%, the formula 34.2%. Hit rate against size for 100,000 items with Zipf popularity (s = 0.9) and 400,000 requests: LRU 16% at 100 entries, 34% at 1,000, 60% at 10,000; Che within 0.5 percentage points at every size; at 1,000 entries TinyLFU 43% and LFU 44%, against 47% for the best fixed set. One percent of the catalogue serves over a third of the requests.
  • 4. Caching: staleness and stampedes. Update the database, then delete the cached copy; the race in which a reader's stale set lands after the delete; a TTL bounds staleness whatever invalidation misses; jitter spreads keys filled together. A stampede simulated: one key requested 200 times a second, a 60-second TTL, 2 seconds to rebuild; in 300 s, 4 expiries cause 1,603 rebuilds (about 401 per expiry), at worst 223 in one second, all on the database. Request coalescing (single flight) and memcache's leases at Facebook (a token at most once every 10 seconds per key, voided by a delete; a reported cut in peak database queries from 17,000 to 1,300 a second). XFetch derived (Vattani, Chierichetti and Lowenstein): refresh if t − Δβ ln U ≥ expiry; −ln U is exponential, so a request r seconds before expiry triggers with probability e^(−r/βΔ), and the expected number of triggers reaches one at r* = βΔ ln(λβΔ) ≈ 12 s; in the same experiment, 6 rebuilds against 1,603, no misses against 1,603, never more than 1 in a second.
  • 5. Rate limiting. A token bucket (σ = 20, ρ = 100 a minute, refusals answered with 429): on a bursty trace of 1,088 requests in 600 s it admitted 766. The envelope A(t, t + s) ≤ σ + ρs derived, the greediest admitted sender drawn, and every interval of up to 10 s of the trace checked: none above the line. Cruz's network calculus (1991); the leaky bucket shapes where the token bucket polices. GCRA keeps one theoretical arrival time, and with τ = (σ − 1)T admits exactly what the bucket admits. Fixed windows let up to twice the limit through across a boundary: with a limit of 100, our worst minute admitted 138. The sliding-window counter, 80 × 0.6 + 30 = 78, against an exact sliding log on our bursty trace: mean error 15%, worst 126%; Cloudflare reported three wrong decisions in a hundred thousand on real traffic (2017). One limit across many servers: a central counter, a local split, or approximate sharing (a Count-Min sketch errs only towards refusing); 429 with Retry-After.
  • 6. Queues and asynchrony. A web tier that answers 202 and a queue that absorbs a burst: a rate problem turned into a delay problem, which works only if the workers keep up on average. Why latency explodes near full load, from Part 31's M/M/1 simulation: a mean of 2 service times at half load, 10 at 0.9, 21 at 0.95, and a 99th percentile of 48 at 0.9; at 0.8, 3, 5 or 22 service times as job sizes vary more (Pollaczek–Khinchine). Priorities, weights and ageing against starvation; heavy-tailed jobs at load 0.8: FCFS 25.7 service times, processor sharing 4.4, shortest remaining first 2.0. Delayed jobs on a sorted set or a timing wheel; retries with doubling delays and full jitter; a dead-letter queue; idempotent jobs. Sizing a pool by Little's law: the napkin's 210 writes a second, each a half-second job, keep 105 workers busy; at a 70% target, 150 workers; Erlang's pooling; scaling on the age of the oldest job; bounded queues.
  • 7. Choosing storage. Six shapes: relational, key–value, document, wide-column, graph, time-series. Access patterns decide, from Part 35: summing one column under a filter on another over 1,000,000 rows of 16 columns, a row store reads 128 MB and a column store 16 MB, 13.9 ms against 4.1 ms. The engine underneath, from Part 34: a B-tree writes 40.6 bytes to disk per byte written with 1% of it cached and 17.6 with 57% cached, a levelled LSM tree 11.9, a tiered one 2.2; a lookup of a missing key probes 2.0 runs (levelled) or 19.0 (tiered), 0.016 and 0.16 with a Bloom filter of 10 bits a key. Normalised against denormalised data, and the copy a rename misses. Indexes: with 400 keys a node, 10³ rows need 2 levels, 10⁶ 3, 10⁹ 4, 10¹² 5; in Part 35's word table the range from whale to whales, 1,704 rows, lay on 966 pages through a secondary index and on 18 stored in index order; every index is a bet.
  • 8. Sharding. Range against hash partitioning: time-ordered keys put every write on the last range shard, hashed keys spread writes but scatter range scans; the compromise key (user, time). Hot keys, from Part 39's 1,000,000 keys over 100 shards: the busiest shard carries 1.04 times the mean with uniform popularity, 2.3 at Zipf exponent 0.8, 7.8 at 1.0 (where the hottest key alone is 7% of requests) and 19.6 at 1.2; salting the 10 hottest keys 20 ways brings these to 1.2, 1.8 and 2.8. Resharding from 10 machines to 11: hash mod N moved 90.9% of keys, a ring 8.6%, against the ideal 9.1%; fixed partitions moved whole; copy, stream, switch, delete; a routing table in ZooKeeper or etcd. Local against global secondary indexes: with each shard slow one time in 100, a query to 1, 10 or 100 shards is slow 1.0%, 9.7% or 64.0% of the time; a global index asks one shard but is updated asynchronously. Across shards: co-locate by customer; a two-phase commit whose coordinator crashes after deciding holds every participant's locks for 31.0 s.
  • 9. Replication in practice. One leader and its log; followers for reads and as warm spares. Reading your own writes, from Part 39 (followers apply a write 100 ms after the leader on average, reads go to any of 3 replicas): a read at once misses the write 67% of the time, after 100 ms 24%, after 500 ms 0.5%; two fixes. Failover: heartbeats every 100 ms on a jittery network, 10 simulated hours; a timeout of 150 ms raises 250.5 false alarms an hour and detects a crash in 102 ms; 200 ms, 30.3 and 152 ms; 300 ms, 3.4 and 252 ms; 1,000 ms, 2.6 and 952 ms; 3,000 ms, 0.0 and 2,952 ms. Asynchronous replication loses the unshipped tail on promotion; semi-synchronous loses nothing acknowledged. Split brain, and fencing tokens 33 and 34 checked by the storage (Part 38). Active–active across regions, from Part 39 (two regions 50 ms apart, each writing one key 5 times a second): 19.3% of writes concurrent; last writer wins loses 9.7% with perfect clocks, 15.7% with 100 ms of skew, 22.7% with 250 ms; version vectors lose 0%.
  • 10. Unique IDs. One counter is a bottleneck; Flickr's two ticket servers (2010) split it. UUIDv4: 128 bits, 6 fixed, 122 random; the birthday bound 1 − e^(−n²/2¹²³) gives 9.4 × 10⁻²⁰ for 10⁹ IDs, 9.4 × 10⁻¹⁴ for 10¹², 9.4 × 10⁻⁸ for 10¹⁵, and 49.9% at 2.7 × 10¹⁸. Snowflake (Twitter, 2010): a sign bit, 41 bits of milliseconds since an epoch (2⁴¹ ms ≈ 69.7 years), 10 bits of machine (1,024 machines), 12 of sequence (4,096 IDs a millisecond); three generated examples on machine 7. UUIDv7 (RFC 9562, 2024): 48 bits of Unix milliseconds, the version, 74 random bits; sorted as strings, in creation order. A clock stepped back 5 ms mints an ID twice; the fix never goes below the last timestamp issued; across machines, IDs are ordered only to within the skew. Index locality, 200,000 inserts at 100 keys a page: random keys leave 2,889 leaf pages 69% full, time-ordered ones 2,000 pages 100% full; the last 10,000 inserts touch 2,730 pages against 101.
  • 11. Blobs and the edge. Metadata in a row, bytes in an object store (Amazon S3, 2006); write the bytes first and the row second, and sweep orphans. Durability from Part 45's model (2% of disks failing a year, a day to repair): one copy, 1.0× the space and a 2.0 × 10⁻² chance of losing the object in a year; three copies, 3.0× and 3.7 × 10⁻¹⁰; Reed–Solomon with 10 data and 4 parity fragments, 1.4× and 4.5 × 10⁻¹⁴. Multipart uploads; chunks named by their hashes (Part 41's git and real git agree on the README's hash); fixed-size against content-defined chunking (LBFS, 2001), illustrative. Signed URLs: an HMAC over the object and the expiry, a capability to keep short-lived. Cache keys at the edge: normalise the URL, check signatures but leave them out of the key, Vary by encoding, and the content hash in the name with a year's max-age and immutable.
  • 12. Maps as keys. A box query on Part 22's 60 points: a longitude index returns 23, a latitude index 22, the box holds 8. Morton's bit interleaving (IBM, 1966): x = 5, y = 3 is key 27; cells 15 and 37 are side by side. Geohash (Niemeyer, 2008): London gcpvj0e, New York dr5regw, no shared prefix; London's prefixes, at its latitude, from 3,115 km × 5,004 km (g) to 95 m × 153 m (gcpvj0e); the Greenwich meridian at the edge of g, so a search covers a cell and its eight neighbours. Hilbert's curve (1891): a 12-cell box is 7 key ranges along the Z and 4 along Hilbert; on a 256 × 256 grid a 16 × 16 box needs 29.9 ranges on average on Z-order against 15.4 on Hilbert (worst of 300 boxes 46 against 26), while neighbouring cells sit a median 3 apart along both curves and 2,731 apart at the 99th percentile on both; S2's cube faces and 64-bit cells. An adaptive quadtree over Part 22's points; square neighbours at 1 and 1.41 cell widths against a hexagon's six at one; H3 (Uber, 2018): 16 resolutions, each cell about a seventh of its parent, 12 pentagons at each. Nearest three neighbours by rings of cells and the circle through the third candidate; Part 22's kd-tree finds one nearest neighbour among 20,000 points visiting about 25 of its 39,999 nodes; PostGIS's R-tree.
  • 13. Real-time blocks. Polling every 10 s, long polling ("Comet", 2006), WebSocket (RFC 6455, 2011) and Server-Sent Events on an illustrative minute. Connections are state: a registry from user to connection server; a server's death reconnects its clients at once; Part 43's ten-second outage against a capacity of 100 requests a second: retrying at once offered a peak of 990 a second and recovered at 119 s, backoff with jitter 381 and 69 s. Notifications: preferences, rate limits and an idempotency key, a queue per channel, APNs and FCM; from Part 42, ten requests 20 s apart cost 130 J of radio energy against 16.5 J together, 7.9× less (a radio tail of 11.6 s). Presence as a failure detector: an expiring key renewed by heartbeats, and Part 39's fixed timeouts against φ accrual. Search as a block: a change log feeding an indexer, eventual consistency, and type-ahead: eliz completes to elizabeth, eliza, elizabeth's, eliza's and elizabethan in the thirty novels (Part 47).
  • 14. The Job as a service. "Upload a book, get its top words": a load balancer, API servers, a result cache, a work queue, 8 workers and a blob store; 3,000 books requested with Zipf popularity, 80 ms of a worker per count on average, so 8 × 1000 / 80 = 100 requests a second at 100% busy. The load test: without a cache the median sits near 55 ms and the 99th percentile near 364 ms at 5 requests a second, and at 95 a second (95% busy) the tail is 607 ms; with a 300-entry cache 63% of requests hit and return in a millisecond, the median falls to 1 ms, and the same tail holds to about 200 requests a second (310 ms there, 894 ms at 250). What a cache buys, with chapter 3's numbers at 300 entries (LRU 23.7%, Che 23.7%, W-TinyLFU 33.3%, the best static set 37.2%): capacity multiplied by 1/(1 − h), paid for in staleness and stampedes.
  • 15. Frontier: design as a science. A learned index on 1,000,000 bursty timestamps: with a maximum error of 8, 5,218 segments (125.2 kB) and 5 comparisons; 32, 380 segments (9.1 kB) and 7; 128, 40 (1.0 kB) and 9; 512, 30 (0.7 kB) and 11; against a B+ tree's 17 inner nodes (70 kB) and 24 comparisons (Kraska et al.; the PGM-index of Ferragina and Vinciguerra). Predicting a system before building it: queueing networks, simulation, learned performance models. Metastable failures (Bronson et al., 2021), and Part 43's retry storm as one. 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
  1. Hook: the napkin. Back-of-the-envelope estimation: QPS from daily users and peak factors, storage per year, bandwidth; powers of two; the latency numbers (callback to Part 39).
  2. The method: functional and non-functional requirements; SLOs (Part 50); the capacity model; the data model; the API (callback to Part 43); the high-level design; deep dives; trade-offs; the design doc.
  3. Load balancing:
    • L4 against L7;
    • round robin, least connections, power of two choices (callback to Part 20);
    • consistent hashing and Maglev hashing (Eisenbud et al. 2016; disruption computed);
    • health checks and outlier ejection.
  4. Caching I:
    • where caches sit (client, CDN, proxy, application, database);
    • cache-aside, read-through, write-through, write-back;
    • eviction: LRU, LFU, W-TinyLFU's Count-Min admission (callback to Part 20);
    • hit rate against size on Zipf traffic, with Che's approximation derived.
  5. Caching II: invalidation; TTLs; thundering herds; request coalescing; probabilistic early expiration (Vattani et al. 2015, derived); leases (memcache at Facebook, Nishtala et al. 2013).
  6. Rate limiting: token bucket as a (σ, ρ) envelope (derived); leaky bucket; fixed and sliding windows (the approximation's error computed); GCRA; distributed limits with approximate counters.
  7. Queues and asynchrony (callback to Part 43): absorbing bursts; why latency explodes as utilization nears 1 (callback to Part 31); priorities; delayed jobs; worker pools.
  8. Choosing storage: relational, key–value, document, wide-column, graph, time-series; access patterns decide; denormalization; indexes (callback to Part 35).
  9. Sharding (callback to Part 39): shard keys; hot keys and the celebrity problem; resharding; local against global secondary indexes; cross-shard queries.
  10. Replication in practice: read replicas and lag; failover; split brain and fencing tokens (callback to Part 39); active–active across regions and conflict resolution.
  11. Unique IDs: UUIDv4 collisions by the birthday bound (callback to Part 17); UUIDv7 and Snowflake IDs; clock skew (callback to Part 38); index locality of time-ordered keys (B-trees, callback to Part 17).
  12. Blobs and CDNs (callback to Part 45): chunking, content addressing, signed URLs, cache keys at the edge.
  13. Geospatial indexes: geohash and Morton (Z-order) bit interleaving; quadtrees; S2's Hilbert-curve cells (with locality preservation measured); H3 hexagons; nearest-neighbour queries (callback to Part 22).
  14. Real-time blocks: WebSockets against long polling; notifications; presence; search as a block (callback to Part 47).
  15. The Job as a service ("upload a book, get its top words"): estimated, designed, then load-tested in simulation, with p50 and p99 against QPS, with and without the cache. Outro.

Computed: estimation worksheets; two choices against random and round-robin assignment on uneven servers; Maglev against ring disruption; LRU and TinyLFU hit rates on Zipf traces against Che's approximation; stampedes with and without early expiration; token-bucket conformance; sliding-window error; ID collision probabilities; Hilbert against Z-order locality; the Job service's load test. Visuals: a napkin turning into a capacity table; requests flowing through a load balancer into queues; hit-rate curves; a stampede at expiry, smoothed; a token bucket filling and draining; space-filling curves drawing across a map. In practice: the system design interview; NGINX, Envoy, HAProxy; Redis and Memcached; CDNs; Snowflake IDs; PostGIS, S2, H3; backend and infrastructure design reviews. Reading: Kleppmann; Xu, System Design Interview vols. 1–2; Burns, Designing Distributed Systems; Petrov, Database Internals; Nishtala et al. 2013; Eisenbud et al. 2016; Einziger, Friedman & Manes 2017; Che, Tung & Wang 2002; Vattani, Chierichetti & Lowenstein 2015; Mitzenmacher 2001; Cruz 1991; RFC 9562 (UUIDs); the S2 and H3 documentation.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 一致性哈希。 证明从一致性哈希环上移除 n 个后端中的一个,只会移动它原来拥有的键,并计算 v 个虚拟节点时的负载不均衡。

    解答

    设 P 为环上所有点的集合(每个后端 v 个),键 k 交给 succ_P(h(k)),即从 h(k) 起顺时针遇到的第一个 P 中的点。移除后端 b 后剩下 P′ = P \ P_b。若 succ_P(h(k)) = p 属于别的后端,则 p ∈ P′,并且 h(k) 与 p 之间严格没有 P′ 的点,因为 P′ ⊂ P,而 P 在那里 本来就没有点;所以 succ_P′(h(k)) = p,k 不动。只有后继点属于 b 的键会移动,每个移到顺时针方向下一个幸存的点;有了 v 个点,b 的键 分散到至多 v 个不同的邻居,而不是全压到一个上。20 个后端中去掉一个时,我们的环对其他键的移动是 0%(重建整张表的 Maglev 是 0.34%)。关于不均衡:nv 个点独立且均匀,一个后端拥有终止于它的各点的 v 段弧。nv 段弧是均匀间隔,联合服从 Dirichlet(1, …, 1),所以 一个后端的份额是其中 v 段之和,服从 Beta(v, (n − 1)v):均值 1/n,方差 (n − 1)/(n²(nv + 1)),相对标准差 √((n − 1)/(nv + 1)) ≈ 1/√v。 于是 n 个中最忙的约为均值的 1 + z_n/√v 倍,其中 z_n ≈ 1.87 是 20 个标准正态变量最大值的期望(n 大时约为 √(2 ln n)):n = 20、 v = 100 时为 1.18。v = 1 时精确答案是 n 个均匀间隔中最大者的期望 H_n/n,所以最忙的后端承担均值的 H_n 倍,n = 20 时为 3.60。在 2,000 个随机生成的 20 后端哈希环上,最忙者平均为均值的 1.68 倍(v = 10)、1.19 倍(v = 100)和 1.06 倍(v = 1,000);工具里用 BLAKE2b 哈希的环在 v = 1、10、100、1,000 时给出 3.81、1.52、1.17 和 1.05,第2章那次移除之后为 1.13。1/√v 衰减得很慢:要让最忙者 与均值相差不到 1%,每个后端需要 v ≈ (1.87/0.01)² ≈ 35,000 个点,所以 Maglev 改为填一张表(65,537 个槽位时为 1.03)。

  2. Che 近似。 在独立引用模型下推导 LRU 的 Che 近似,并用模拟检验它。

    解答

    在独立引用模型中,每个请求以概率 p_i 请求第 i 项,与其他请求独立。容量为 C 的 LRU 缓存恰好保存最近被请求的 C 个不同的 项,所以第 i 项在某次请求之前位于缓存中,当且仅当它在最近 τ_i 次请求之内被请求过,其中 τ_i 是往回数、看到 C 个除 i 以外的不同项 所需的请求数。τ_i 是随机的,并且依赖于 i;Che、Tung 和 Wang 把它换成一个常数 T,即特征时间。理由是 τ_i 是对许多项的求和,因而 高度集中,而从很大的目录中去掉一项几乎不改变它(Fricker、Robert 和 Roberts 解释了这个近似为何如此准确)。于是 P(i 在缓存中) = 1 − (1 − p_i)^T ≈ 1 − e^(−p_i T)(对连续时间的泊松请求是精确的)。缓存装着 C 项,所以在缓存中的项数的期望为 C: Σ_i (1 − e^(−p_i T)) = C。左边从 0 连续增长到项的总数 N,所以 0 < C < N 时它确定唯一的 T,可用二分法求出;又因为 1 − e^(−x) ≤ x, C ≤ Σ p_i T = T,所以 T ≥ C。一个请求以概率 p_i 请求 i,与缓存的状态无关,并且恰在 i 在缓存中时命中: h = Σ_i p_i (1 − e^(−p_i T))。对我们 Zipf 指数为 0.9 的 100,000 项,C = 100、300、1,000、3,000、10,000 时 T 为 111、363、1,362、 4,746 和 20,172 次请求,公式给出 15.6%、23.7%、34.2%、45.5% 和 60.5%,40 万次请求上模拟的 LRU 命中率为 15.7%、23.7%、34.2%、 45.4% 和 60.1%,处处相差不到 0.5 个百分点;tests/test_cs48_design.py 在一条较短的轨迹上做同样的检查。在那项任务的服务的目录上 (3,000 本书,指数为 1),公式在 300 个条目时给出 63.0%,第14章测得 63%。

  3. 提前过期。 证明 XFetch 的提前刷新规则使过期时并发重建的期望次数为 O(1)。

    解答

    请求是速率为 λ 的泊松过程;值在时刻 E 过期;一次重建需要 Δ,之后新值和新的过期时间就位。时刻 E − r(r > 0)的请求在 −Δβ ln U ≥ r 时刷新,U 在 (0, 1) 上均匀;按这条规则的原始形式,任何请求都可以这样做。由于 −ln U 服从均值为 1 的指数分布,它以概率 e^(−r/βΔ) 触发,与其他请求独立,所以触发构成一个泊松过程,在剩余时间 r 处的强度为 λe^(−r/βΔ)。设 R 为第一次触发时的剩余时间, X = λβΔ e^(−R/βΔ) = ∫R^∞ λe^(−u/βΔ) du,即在它之前累积的强度。于是 P(R ≤ r) = P(剩余时间大于 r 时没有触发) = exp(−λβΔ e^(−r/βΔ)),所以 P(X ≥ x) = e^(−x):X 服从均值为 1 的指数分布,泊松过程在第一个事件处累积的强度总是如此。与第一次重建并发的, 是接下来 Δ 秒内、剩余时间在 R − Δ 与 R 之间的触发;给定 R,它们的期望个数至多为 ∫(R−Δ)^R λe^(−r/βΔ) dr = X(e^(1/β) − 1)。所以并发 重建的期望次数至多为 1 + E[X](e^(1/β) − 1) = e^(1/β),与 λ 和 Δ 无关:β = 1 时为 2.72。还剩一种情形:若 R < Δ,旧值在新值就位之前 过期,其间的请求未命中;P(R < Δ) = exp(−λβΔ e^(−1/β)),所以未命中的期望至多为 λΔ exp(−λβΔ e^(−1/β)) ≤ e^(1/β − 1)/β,也是常数。在 我们的实验中 λ = 200、Δ = 2 秒、β = 1:λβΔ = 400,P(R < Δ) = e^(−147),刷新平均在过期前 βΔ(ln λβΔ + γ) = 13.1 秒发生(中位数 12.7 秒;画面上的 12 秒是更早触发的期望次数达到一的位置)。不加任何锁、对 20,000 次过期做的蒙特卡罗模拟,平均有 2.72 次并发重建,与 e 吻合。没有提前刷新时,过期后 Δ 之内的每个请求都去重建,共 λΔ = 400 个,工具在 4 次过期中数到 1,603 次。工具还只允许同时进行一次 刷新,所以每个周期恰好开始一次;每个周期长 62 − R 秒,平均约 48.9 秒,这就是 300 秒中的 6 次重建。

  4. 令牌桶。 证明速率为 ρ、深度为 σ 的令牌桶在任何长度为 t 的区间内至多放行 σ + ρt 个请求。

    解答

    设 b(u) 为时刻 u 的令牌数。令牌以速率 ρ 累积,但从不超过 σ;放行一个请求取走一个令牌,而且只在 b ≥ 1 时才允许,所以 b 始终在 [0, σ] 之内。取区间 [s, s + t],设 b₀ 为区间内第一次放行之前的令牌数。区间内实际加入的令牌 R 至多为 ρt(在 σ 处截断只会丢掉 一些),A 次放行各花掉一个,所以区间末的令牌数为 b₀ + R − A ≥ 0。因此 A ≤ b₀ + R ≤ σ + ρt。除了取整,这个界是紧的:一个发现桶是满的、 之后每来一个令牌就发一个请求的发送者,在长度为 t 的区间内被放行 σ + ⌊ρt⌋ 个,就是第5章画的那条阶梯。σ = 20、ρ = 每分钟 100 时, 任何一分钟至多放行 120 个,任何 10 秒至多 36 个;对我们轨迹中长度不超过 10 秒的每个区间的检查没有发现违例;而限额为 100 的固定 窗口在一分钟内放行了 138 个,最多可能放行 200 个。由于包络可以相加,n 个这样的客户端在任何长度为 t 的区间内至多给服务发送 nσ + nρt,这使最坏情况成为可以据以确定规模的东西。

  5. 动手。 给那项任务的服务加上请求合并(每个缺失的键只重建一次),并测量缓存清空期间的 p99。

    解答

    解答要点。 先让缓存诚实。keys.job_service 在请求到达的那一刻就把未命中的书放进缓存,于是在 80 毫秒的计数期间到来的请求已经能以 1 毫秒命中:照现在的写法,这个模型免费地做到了完美的合并。改为维护一个(完成时间,书)的堆,每次到达之前弹出已完成的计数,并把它们 的书插入 LRU。然后做合并:一个从书到其计数完成时间的字典 inflight;未命中时,若这本书正在计算,请求就等待那次计数(延迟为完成时间 减去当前时间),不开始新的工作;否则像现在一样把计数排到最早空闲的工作机上,并记录下来。清空:在 30,000 个请求中的第 15,000 个时清空 缓存,取之后五秒内请求的第 99 百分位数,分别在有、无合并时、在几种速率下测量。按这个思路写的草稿(种子 3,300 个条目的缓存)在清空 之后的五秒内给出:每秒 100 个请求时两种都是 340 毫秒,150 时 362 对 340 毫秒,200 时 659 对 431 毫秒;200 时整次运行为 444 对 331 毫秒,运行的计数为 11,283 对 11,131 次。收益不大,是因为一次计数很短:每秒 200 个请求时,一次 80 毫秒的计数期间约到达 16 个请求, 最热门的书占其中的 1/H₃₀₀₀ ≈ 11.6%,所以没有合并时它大约被重复计算两次。完整的答案应扫过不同的工作时间和偏斜程度(在那里合并更 重要),并报告清空后命中率恢复得多快。

  6. ★ 研究。 一个在漂移的 Zipf 流量上具有可证明竞争比的缓存准入策略。

    讨论。 尚未解决。经典的分析回答的是别的问题。与 Belady 的离线最优相比,任何确定性的在线策略(包括 LRU)对容量为 C 的缓存至多是 C-竞争的(Sleator 和 Tarjan),这个最坏情形对 Zipf 流量什么也没说。与最佳静态集合相比,平稳的独立引用很容易:精确的频率计数会收敛到 最热门的那些项,也就是最佳静态集合。有了漂移,比较的对象也必须移动:整条轨迹上的最佳静态集合是个弱目标,每个 W 次请求的窗口内的 最佳集合是个强目标;而把缓存表述为在线学习、相对固定缓存给出遗憾界的工作,针对的是分数缓存和对抗性序列,而不是像 TinyLFU 那样只能 通过一个会出错的草图、拿候选项与 LRU 的牺牲者比较而决定接纳或拒绝的整数缓存。好的部分答案应固定一个漂移模型(例如名次以每个请求 δ 的速率与相邻者交换,或者新项以速率 δ 从顶端进入),以每个窗口内的最佳集合为比较对象,证明每 W 个请求把计数减半的频率过滤器(我们 的 CountMin 每十倍宽度减半一次)的命中率与它相差不超过一个给定的加性项,其中抽样误差随 W 增大而减小,漂移误差随 δW 增大而增大, 选择 W 使二者平衡,并给出同一权衡的下界。它应在我们的模拟器中对照移动的最优者来检验;在平稳的轨迹上,W-TinyLFU 已经在 300 个条目时 落后最佳静态集合 3.9 个百分点(33.3% 对 37.2%),在 1,000 个条目时落后 4.1 个(43.3% 对 47.4%)。

Build the film

python -m videos.cs.cs48.compute        # the part's numbers, into .cache/cs48
python tools/build.py cs48                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs48 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs48. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs48.compute
python -m unittest tests.test_cs48_design
python tools/build.py cs48