ealeng

Episode 23 of 55 · Capstone: a URL shortener

A URL shortener, designed then measured: ten of eleven predictions held, and the knee came early

Eleven predictions written down and sealed before any code, then a URL shortener built on one laptop and loaded to its target: 3,472 redirects and 35 new links a second. Redirects held a p99 of 4.3 ms, and no new link ever 404'd. It broke at 8,000 redirects a second, not the 10,000 the design predicted, because each redirect made two cache calls, not the one the borrowed number assumed. The cache hit ratio was right for the wrong reason. This chapter walks the estimate, the sealed design, the load test, the knee and what the measurements say to change for ten times the load.

Capstone A · A URL Shortener, Proven11 min read
Video transcript10:07

0:00Cold open

0:01

Before I wrote any code for my URL shortener, I wrote down eleven predictions. And I sealed them, so I couldn’t change them later.

0:11

Then I built it and loaded it. Ten of the eleven held.

0:16

One was off: I said it would break at about ten thousand redirects a second. It failed at eight thousand.

0:24

And one was right, for the wrong reason.

0:29

So what does a design on paper get right, and what does it miss?

0:35Intro

0:36

Hands-on system design, part twenty-three.

0:40

Today: a URL shortener, designed on paper first, then built and measured against its own predictions.

0:48Meet Lucía

0:49

I’m Lucía, a platform engineer.

0:52

A URL shortener does two things. You give it a long link, and it gives you a short code. Then anyone who opens the short link gets redirected to the long one, and it counts the click.

1:05

First, the estimate. Two million users a day. Each creates half a link and follows fifty. And the busiest hour is three times the average.

1:16

Fifty links times two million, over the eighty-six thousand four hundred seconds in a day: eleven hundred and fifty-seven redirects a second. Times three at the peak: three thousand four hundred seventy-two. And thirty-five new links a second.

1:33The design

1:35

The design uses pieces from earlier in this series: a load balancer, two app processes so one can fail, a Redis cache, and Postgres with a replica, a read-only copy of the database, for reads.

1:49

I committed the design and its predictions first. The report checks the file’s fingerprint, a short code computed from the file: change one letter, and it changes. If the design changed, the report refuses to build.

2:05

Think of a weather forecast, sealed in an envelope. Then the weather comes. Some forecasts are right. And sometimes it rains, but not from the cloud you named.

2:1701 · What you need

2:18

To run it yourself: Docker for the two Postgres databases, Redis, the two app processes and the load balancer. The quick tests run in a couple of seconds, without Docker.

2:30

And the design’s numbers come from one script, run before anything was built.

2:36

Including the cache prediction, the hit ratio: with room for a hundred thousand of the million links, seventy-seven of every hundred redirects should find their link in the cache.

2:4902 · The predictions

2:51

Here are the eleven. Each one is checked by code against a measured table, so “held” isn’t a matter of wording.

2:59

Today, the first five: how fast, how many cache hits, how much database work, and where it breaks. The other six, next time.

3:09

And here’s how they came out.

3:1303 · At the target

3:14

The real test: three thousand four hundred seventy-two redirects and thirty-five new links a second, for two rounds of a minute, all in Docker on one laptop, load generator included. Popular links get most of the redirects. My notes say the first run missed badly, at over a hundred milliseconds, while the laptop was overloaded. These are the reruns, on a quieter laptop.

3:38

Take the slowest redirect in every hundred. Predicted: under ten milliseconds. Measured: four point three, in both rounds. Typical: about half a millisecond.

3:51

One second in each round was slow, over fifty milliseconds. The other fifty-nine weren’t. So it’s a short stall, not a slow system.

4:00

Creating a link, at the slowest one in a hundred: under eight milliseconds, against a prediction of twenty. And nothing failed.

4:10

The hit ratio: seventy-four point four and seventy-four point five percent, close to the seventy-seven predicted. So about twenty-six percent of about three and a half thousand redirects missed the cache: about nine hundred database reads a second, all on the replica. Predicted: twenty-three percent, about eight hundred.

4:3204 · Where it breaks

4:33

Then I raised the load, twenty seconds at each rate, until it broke. Broken here means the slowest one in a hundred passes fifty milliseconds, or any request fails. The design said about ten thousand redirects a second. Where did it break?

4:51

At eight thousand. Two hundred seventy-six of about a hundred and sixty thousand failed, under a fifth of a percent. And the slowest one in a hundred took three seconds. This sweep ran while the laptop was a little busier than for the target runs, so part of that may be the machine.

5:09

And the design pointed at the right bottleneck. The busiest pieces of the service were the two app processes, at ninety-six and ninety-two percent of a CPU. The load balancer was at forty, Redis at thirty. The load generator, on the same laptop, was near its limit too.

5:29

At six thousand, nothing failed. I didn’t test seven, so the true breaking point is somewhere in between. From one to six thousand, the slowest one in a hundred bounced between seven and twenty-one milliseconds. My guess: at a thousand a second for twenty seconds, the slowest one in a hundred is just two hundred requests, fewer than one second holds. So one stalled second sets it on its own.

5:5405 · Why it broke early

5:56

Why eight and not ten? The ten thousand was borrowed: one process broke at about six thousand requests a second, measured earlier in this series. Two processes make twelve thousand; I rounded down to about ten.

6:11

But that earlier test did one Redis call per request. Here, a redirect does two: one to find the link, one to count the click.

6:21

And a cache miss does more: it takes a lock, so only one request reads the database for that link, then reads it, and fills the cache. And here about one redirect in four missed; in that earlier test, about one in twenty.

6:36

So each redirect was heavier than the number assumed: two Redis calls, and more misses. The bottleneck was the one the design named. The cost per request was not.

6:5006 · The wrong reason

6:51

Now the one that was right for the wrong reason. The design predicted seventy-seven percent hits, because the cache only has room for a hundred thousand links. But the cache never filled up: Redis evicted nothing during the test. So what set the seventy-four?

7:08

So I ran a new stream of clicks with the same shape through a cache simulator, offline, at three sizes. With the cache running for thirty seconds before the measured minute, as in the test: seventy-four point three percent. For a hundred thousand links, a hundred and ninety thousand, or no limit at all.

7:29

The size didn’t matter. In those ninety seconds, only about ninety-two thousand different links were clicked, fewer than the hundred thousand the cache had room for. So nearly every miss was the first click on a link. No cache, however big, can already hold a link it has never seen.

7:48

Size only mattered after minutes. After five minutes, a full hundred-thousand-link cache reaches seventy-eight percent: the design’s seventy-seven. The test never ran that long. So the database’s load depends on how long the cache has been running, not just on its size.

8:0807 · For ten times the load

8:10

So what would I change for ten times the load? These are worked out from the measurements, not tested at that load.

8:18

First, cut the work per redirect: count clicks in the app, and send them to Redis once a second. Then a cached redirect is one Redis call, not two.

8:29

Then add app processes: about twelve at today’s cost. With one call, if that gets each process back to the earlier six thousand, about six to eight.

8:40

Split the cache: one Redis was at thirty percent at eight thousand a second. Ten times the target is about a hundred and thirty percent at today’s two calls. Even at one call, it’s close to the limit.

8:54

And size the database for a cold cache. Right after a Redis restart, nearly every redirect misses: up to three and a half thousand reads a second today, thirty-five thousand at ten times. Not tested.

9:10Back to Lucía

9:11

So, three lessons.

9:14

Seal your predictions before you measure. Otherwise it’s too easy to “fix” a prediction after you see the number.

9:23

A number borrowed from another test needs the same work per request. Two Redis calls are not one.

9:31

And a cache’s hit ratio depends on how long it has been running. In a short test, the size barely matters.

9:39

On paper I got the speed and the bottleneck right. I missed the cost per request, and the cache’s age. Next time: where the pieces clashed. A new link that 404s, guessable codes, and the redirect that loses clicks.

9:55

For today: seal it first.Lucía: Seal it first.

9:58Summary

10:00

Seal predictions first, check borrowed numbers, and give the cache time.

Key takeaways

  • ✓A URL shortener's load comes from users per day: 2 million users who each follow 50 links and create half a link a day give 1,157 redirects a second on average, 3,472 at the peak (three times the average), and 35 new links a second at the peak, about 1.8 TB after five years with every byte stored twice.
  • ✓Writing the design down before the test means the predictions can't be edited after the numbers arrive. The lab's DESIGN.md has eleven numbered predictions (P1 to P11) and a SHA-256 fingerprint, and the report refuses to build if the file has changed since it was written.
  • ✓At the target, redirects had a p99 of 4.3 ms in both rounds against a predicted 10 ms, creates had a p99 of at most 7.9 ms against 20 ms, nothing failed, and none of the 4,205 new links returned a 404 on its first read.
  • ✓The knee came at 8,000 redirects a second, not 10,000: 276 of 160,107 requests failed and the p99 reached 3.0 seconds, with the two app processes at 96% and 92% of a CPU. The 6,000 a second borrowed from an earlier test assumed one Redis call per request, and a redirect here makes two.
  • ✓The cache hit ratio was 74.4% and 74.5% against a predicted 77%, but the cache's size didn't set it: replayed through a simulator, the same 90-second run gives 74.3% for a 100,000-link cache, a 190,000-link one or an unlimited one, because most misses were first reads of links the cache had never seen.
  • ✓For ten times the load (350 creates and 35,000 redirects a second), the lab's report recommends cutting Redis round trips per redirect from two to one, adding about twelve app processes at today's cost, sharding the cache, and sizing the database for a cold cache. None of the ten-times numbers were tested.

Two million users a day, a short link for each, and a load test to see whether the design holds at its target. This chapter follows one URL shortener from its back-of-envelope estimate to a written design, a load test on one laptop, and a list of where the design was right and where it was wrong. The design is written before any code and is checked afterwards, so the predictions can't drift toward the measurements.

The examples come from the first capstone of the system design labs, Capstone A (A URL Shortener, Proven): the design file DESIGN.md, the scripts 00_setup.py through 04_cache_check.py (setup, the target run, the knee sweep, the four clashes, and the cache replay), the result files in results/, and the report report/REPORT.md, which build_report.py rebuilds from the committed results. The test machine was an Apple M4 Max running Docker Desktop with 16 virtual CPUs. Other work kept the laptop busy, with a load average near 11 during the target runs and near 13 during the knee sweep, so the latency shapes matter more than the last digit. The lab's 388 tests run offline in a few seconds and check the report's rules too.

The estimate

Lucía, the platform engineer in this chapter, starts with users, not servers. Each of the 2 million daily users follows 50 links and creates half a link a day:

redirects:  2,000,000 × 50 ÷ 86,400 s  = 1,157/s average  ×3 at peak = 3,472/s
creates:    2,000,000 × 0.5  ÷ 86,400 s = 11.6/s average   ×3 at peak =    35/s
storage:    1.8 billion links in 5 years × 500 bytes × 2 copies = 1.8 TB

The design's numbers come from design_estimates.py, which reuses the estimate script from Lab 01 (the first chapter, estimate then measure). The peak is what sizes the system, not the average. With a 100 : 1 ratio of reads to writes, the redirect path is the one to design around.

The design, sealed

The design uses pieces from earlier in the track: a load balancer (HAProxy, which spreads requests across the app processes, chapter 12), two app processes so one can fail, a Redis cache in front of the database, and a Postgres primary with a read-only replica. A few decisions are worth naming, because the test checks each one:

  • Codes: six random base62 characters (letters and digits), which gives 56.8 billion codes. Collisions get a retry. Snowflake IDs, the time-ordered IDs from chapter 19, would never collide, but a code could then be guessed from the one before it.
  • Create: an Idempotency-Key header, which the client sends so a retried create returns the same code. The key is stored with a unique constraint, so two copies arriving together make one link (retries and idempotency).
  • Read: a cache-aside Redis, meaning the app fills it on a miss, with an LRU (least-recently-used) eviction policy, sized for 100,000 of the test's 1,000,000 links. On a miss, a short lock lets one request fill the cache while others wait (the stampede protection from chapter 14).
  • Write-through: a create also puts the new link into the cache, so its first read is a cache hit rather than a replica read that might lag (replication lag).
  • 302, not 301: a 301 is cached by browsers for good, so later clicks never reach the server and never count.

DESIGN.md also holds eleven numbered predictions, P1 to P11, each a number the test could check. Before any code, the file's SHA-256 fingerprint was recorded in results/design_sha256.txt (it starts 43cbd31c). Change one letter and the fingerprint changes, and build_report.py refuses to build the report. The video compares it to a weather forecast sealed in an envelope: the weather arrives afterwards, and the envelope can't be reopened to fit it.

Try it · Predicted, then measuredRecorded results; the checks are in the lab's report
Held
10 of 11
Partly
1
Knee
8,000/s
  • P1PredictedRedirect p50 about 1 ms, p99 under 10 ms, at 3,472/sMeasuredp50 0.54 and 0.53 ms; p99 4.34 and 4.29 msheld
  • P2PredictedCache hit ratio about 77%Measured74.4% and 74.5%Right number, wrong reason: the cache size didn't set it.held
  • P3PredictedAbout 800 database reads/s, all on the replicaMeasured901 and 897 on the replica, 0 on the primaryheld
  • P4PredictedCreate p99 under 20 msMeasured7.9 and 5.7 msheld
  • P5PredictedThe knee at about 10,000 redirects/s, set by the app processesMeasuredFirst failing rate 8,000/s; app CPU 92% and 96%The bottleneck was right; the rate was not.partly
  • P6PredictedNo link 404s right after its create returnsMeasured0 of 4,205 at the targetheld
  • P7PredictedWithout write-through or the primary fallback, some new links 404Measured3 of 1,031 (0.29%)held
  • P8PredictedAbout 9 code collisions per million creates, all retriedMeasured9.0 per million over 10 trials; every retry succeededheld
  • P9PredictedTwo concurrent creates with the same Idempotency-Key make one linkMeasured300 of 300 pairs got the same codeheld
  • P10PredictedThe replica isn't needed: sending misses to the primary moves p99 under 2 msMeasuredp99 changed by 0.30 msTrue for a warm cache only.held
  • P11PredictedA 301 lets browsers skip the server; a 302 counts every clickMeasured301: 200 of 4,000 clicks reached us; 302: all 4,000held

P5 is the one that missed: the knee came at 8,000 redirects/s, not about 10,000. The rest of the table is in the chapter text.

The target: two rounds of a minute

The target run, 01_target_load.py, sent 3,472 redirects and 35 creates a second for two rounds of 60 seconds, after 30 seconds of warm-up. Each create was read back right away. The load generator ran on the same laptop, and the first attempt failed: redirect p99 was 128 to 190 ms at a load average of 15 to 18. The lab's README blames the laptop: the same load with and without creates gave similar slow spikes. The reported runs are the reruns, at a load average near 11, and the script now reports the p99 of each second so that a few stalled seconds can't pass for a slow system.

Round Redirects ok p50 p99 Creates p99 Links 404 on first read Cache hit ratio DB reads/s (replica / primary)
1 208,884 of 208,884 0.54 ms 4.34 ms 7.9 ms 0 of 2,077 74.4% 901 / 0
2 209,235 of 209,235 0.53 ms 4.29 ms 5.7 ms 0 of 2,128 74.5% 897 / 0

Predicted: p50 about 1 ms, p99 under 10 ms; creates under 20 ms; a hit ratio near 77%; about 800 database reads a second, all on the replica. Measured: all four held. In each round one second out of 60 went over 50 ms, so the stall was one second, not the whole minute. The design's zero-404 promise held as well: no new link failed its first read.

Where it broke: the knee

Next, 02_knee.py raised the redirect rate in steps of 20 seconds, from 1,000 to 8,000 a second, to find where the system broke. The lab calls a point broken when its p99 passes 50 ms or any request fails.

Try it · Where it brokeRecorded: 20 s per rate, warm cache, 2 app processes
110501001,00010,000broken above 50 ms1,0002,0003,0004,0005,0006,0007,0008,00010,000not testedpredicted knee3,004 ms, 276 failed
p99 redirect latency

Hover or tap a point to read its run.

The load generator ran on the same laptop and reached about 394% CPU at 8,000/s (not plotted). 7,000/s was not tested, so the true break is somewhere between 6,000 and 8,000. The predicted 10,000 is off this scale.

Up to 6,000 a second nothing failed and the p99 stayed between 7.5 and 21 ms, though it bounced around, and at 1,000 a second 20 seconds is only 200 slow requests, so one stalled second sets the p99 by itself. At 8,000 a second, 276 of 160,107 requests failed and the p99 was 3.0 seconds. The design named the right bottleneck: the two app processes were at 96% and 92% of a CPU, against 40% for HAProxy and 30% for Redis. The load generator was at about 394% of the laptop, close to its own limit. The rate 7,000 was not tested, so the true break lies between 6,000 and 8,000.

Why it broke early

The prediction of 10,000 was borrowed. Lab 08 had found that one Python process with Redis broke at about 6,000 requests a second, and two processes make 12,000; the design rounded down to about 10,000. But that earlier request did one Redis call. A redirect here does two: one to find the link and one to count the click. And a cache miss does more again: it takes the lock, reads the replica and fills the cache. About one redirect in four missed here, against about one in twenty in the earlier test.

So the bottleneck was the one the design named, and the cost per request was not the one it assumed. The lab's report puts it as the lesson of the chapter: the estimate was right about the load and wrong about the work each request does.

Right for the wrong reason

The 77% hit-ratio prediction came out at 74.4% and 74.5%, close enough to count as held, but the reason was wrong. The design sized the cache for 100,000 links. Redis reported 189,892 keys in its 24 MB, and evictions didn't change during the rounds, so the cache never filled up and eviction didn't set the ratio.

To find out what did, the lab replayed the same clicks through its LRU simulator, offline, at three sizes:

Cache running before the measured minute 100,000 links 190,000 links Unlimited
30 s 74.3% 74.3% 74.3%
5 min 77.9% 83.8% 85.9%

Recorded simulator output (Lab 08's LRU simulator replaying the test's 90 seconds). Not a live measurement.

In the 90 seconds of the run, only about 92,000 different links were clicked, fewer than the cache had room for. So nearly every miss was the first click on a link, and no cache can hold a link it has never seen. Size starts to matter after minutes: after five, the 100,000-link cache reaches 77.9%, the design's 77%. The short test never ran long enough for size to matter, so the database's load depends on how long the cache has been running, not just on its size.

For ten times the load

The report's decision section gives what to change at 35,000 redirects and 350 creates a second. None of these were tested at that load; they're worked out from the measurements.

  1. Cut the work per redirect. Count clicks in the app and flush them to Redis once a second, so a cached redirect is one round trip, not two.
  2. Add app processes. At today's cost per request, about 12 processes would be needed; with one round trip, about half that.
  3. Shard the cache. One Redis was at 30% at 8,000 a second. At ten times the target it would need about 130% of a CPU at today's two calls, so split it by code, as chapter 18 describes.
  4. Size the database for a cold cache. At the target, the replica carried about 900 reads a second, but right after a Redis restart nearly every redirect misses: up to 3,472 reads a second today, and 35,000 at ten times.

The report also says what to keep: write-through (no new link returned a 404), 302 redirects (every click counted), the idempotency key (one link per key under concurrency) and random codes, with a move to 7 characters before the code space fills.

The workflow, and what each result is

  • Estimate: design_estimates.py writes results/design_estimates.json, before the system existed.
  • Setup: 00_setup.py loads 1,000,000 links and sets up the primary and replica.
  • Target: 01_target_load.py (the two rounds above).
  • Knee: 02_knee.py (the sweep).
  • Clashes: 03_clashes.py runs the four clashes below.
  • Cache replay: 04_cache_check.py (the simulator table).
  • Report: build_report.py writes report/REPORT.md. Each claim in claims.json cites one or more numbered tables (T1 to T9 in the report), and the build fails if a claim cites no table, a missing one, or if DESIGN.md has changed.

The clashes, where the pieces disagreed, were measured separately. Without write-through or the primary fallback, 3 of 1,031 new links 404'd on the first read (0.29%): the replica hadn't replayed them yet. Either fix alone removed them. Random 6-character codes collided 9.0 times per million creates, against a birthday bound of 8.8, and every retry succeeded. With a 301, browsers sent 200 of 4,000 clicks to the server, while a 302 sent all 4,000. And 300 pairs of creates with the same key, sent at the same moment through HAProxy, all got the same code: one answered 201 and the other 200 as a replay.

Caveats

  • One laptop, one run per setting. The knee's rates were each 20 seconds, the target was two rounds of a minute, and the machine was busy. The first target run failed for that reason, and the reruns are the ones reported.
  • A short test. The cache never reached steady state, so the hit ratio at steady state (84% to 96%, depending on size) is from the simulator, not the live system.
  • The cache's key count. The lab's report and checklist call the 189,892 keys Redis reported "190,000 links". Each cached link keeps a second key, the click counter, so the count is closer to 95,000 links. Either way, the simulator's flat 74.3% doesn't depend on which is right.
  • Not tested: a failed primary, a dead app process under load, a cold cache after a restart, abuse (spam links or guessing codes at scale), TLS, 7,000 a second, and any of the ten-times numbers.
  • Click counts live in Redis. A Redis restart loses them. The lab's decision list flushes them to the database, but that was not tested.

Check your understanding

Try each question before opening its answer.

The design predicted about 10,000 redirects a second, and the knee came at 8,000. What was wrong, and what was right?

The bottleneck was right: the two app processes ran out of CPU first, at 96% and 92%. The number was wrong, because it was borrowed from a test where one process made one Redis call per request. A redirect here makes two (a read to find the link, and an increment to count the click), and the 1 in 4 misses also take a lock, read the replica and fill the cache.

Why did the hit ratio match the prediction without the cache's size being the reason?

The cache never filled up, and in the 90 seconds of the run only about 92,000 different links were clicked. Most misses were the first click on a link, which no cache can serve, so the simulator gives 74.3% for a 100,000-link cache, a 190,000-link one and an unlimited one. Size matters once the cache has run for minutes: after five, 77.9% for the smaller cache and 85.9% for the unlimited one.

Why was the replica judged unnecessary at the target, and when does that stop being true?

Sending cache misses to the primary instead moved the p99 by 0.30 ms, so at this load the replica added availability, not capacity. That holds for a warm cache. After a Redis restart nearly every redirect misses, so the database would get up to 3,472 reads a second at the target, and 35,000 at ten times the load.

Why are new links safe to read right after creation, even though reads go to a replica?

The create writes the link into the cache too (write-through), so the first read is a cache hit. If the replica still says 404, the app asks the primary before answering. Without both, 3 of 1,031 new links 404'd on their first read; with either fix, none did.

Next up: Chapter 24, redirect codes and random codes. The design's pieces clashed in four places: a new link that 404s, guessable codes, collisions, and the 301 that loses clicks. Next: how each clash was measured, and why the fix for each one costs something.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.