ealeng

Episode 24 of 55 · Capstone: a URL shortener

Redirect codes, replica lag and random codes: one 301 hid 3,800 of 4,000 clicks

Ten simulated browsers clicked 20 links 20 times each, 4,000 clicks in all. Behind a 302 redirect, the shortener counted every one; behind a 301, the browsers remembered the redirect for a year and only 200 reached the server. The same capstone measures a brand-new link that 404s when its read goes to a lagging replica (3 of 1,031 without a fix), whether the replica was worth having at the target load, and the collisions of random 6-character codes (9.0 per million, against 8.8 predicted).

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

0:00Cold open

0:01

My URL shortener counts every click on every link. Four thousand test clicks, four thousand counted.

0:09

Then I changed one number in its reply: three oh two, to three oh one. Both tell the browser “the page is over there”.

0:18

Same four thousand clicks. Two hundred were counted. Three thousand eight hundred never reached us, so we never counted them.

0:28

Nothing failed. Every redirect worked. Two good ideas just clashed: a redirect browsers remember, and a server that counts clicks. Here are four clashes and one safety net, and the fixes we measured.

0:43Intro

0:45

Hands-on system design, part twenty-four.

0:48

Today: where the pieces of a URL shortener clash, and how to tell before your users do.

0:55Meet Lucía

0:57

I’m Lucía, a platform engineer. This is the URL shortener we built last time, all real, in Docker on one laptop.

1:06

HAProxy, the load balancer, spreads requests over two app processes. A Redis cache holds popular links. Postgres keeps them: every create goes to the primary, and a cache miss reads from a replica, a copy.

1:22

Every design choice is a switch. Turn one off, keep the rest the same, and measure what breaks.

1:29

Think of a cloakroom. The short code is your ticket. The long address is your coat. The cache is the rack by the desk. And the replica is a copy of the ledger, kept a moment behind.

1:4301 · What you need

1:44

To run it yourself: Python, and Docker for the databases, Redis, the app processes and the load balancer. The quick tests need no Docker, and there’s nothing to pay for.

1:5802 · A brand-new link

1:59

First, three other clashes; the 301 comes back at the end. Clash one: a brand-new link. You make a short link, and open it right away. Thirty-five creates a second, each read back at once, while three thousand four hundred and seventy-two redirects a second hit the service, the target from part twenty-three. Thirty seconds per setting: one thousand and thirty-one new links.

2:23

The create goes to the primary. But the read, on a cache miss, goes to the replica, and a replica runs a moment behind. In the cloakroom: the copy of the ledger hasn’t got your ticket yet. So the design does two things: the create also puts the link on the rack, the cache. That’s called write-through. And if the replica says “no such link”, ask the primary.

2:46

With both: zero of one thousand and thirty-one new links said “not found”, in this run. With only the fallback to the primary: also zero. In that run the replica said “no such link” three times, and the primary had all three. Write-through on its own wasn’t tested.

3:04

And with neither? How many new links would say “not found”?

3:10

Three of one thousand and thirty-one. About three in a thousand. Rare, but each one is a user who opens the link they just made, and gets “not found”.

3:2303 · In code

3:24

Here it is in the app. A cache miss reads the link from the replica.

3:30

If the replica has nothing, it asks the primary, which always has the latest.

3:36

And on create, the new link goes straight into the cache, so its first read is answered from the cache: in the design run, the primary never had to step in.

3:4804 · Was the replica worth it?

3:49

Clash two: the replica takes reads off the primary. But the cache already takes most of them. So I sent the cache misses to the primary instead, two rounds, both settings in each.

4:02

One surprise first. Between settings I reset the counters, not the cache. So the second run found its links cached, and read the database almost never. Only each round’s first run tests the database: the fairest test we have.

4:18

With misses on the replica: five hundred and sixty-one reads a second, sixteen percent of the redirects, so the cache answered eighty-four. The slowest request in every hundred: two point three one milliseconds. On the primary: four hundred and sixty-six reads a second, about a sixth fewer misses to serve, and two point one six milliseconds. They’re zero point one five apart. The two cached second runs, with no database reads at all, were zero point four five apart. So zero point one five is noise. Either database used about six percent of a CPU.

4:56

The design predicted less than two milliseconds of difference, and that held. At this load, with a warm cache, the replica wasn’t needed: the primary alone took the misses at about six percent of a CPU. It may still be worth having for a cold cache, or if the primary fails. This test didn’t try either.

5:1805 · Random codes collide

5:19

Clash three: the codes. Each is six random characters, from sixty-two: lower case, upper case and digits. That’s fifty-six point eight billion codes. Pick a million at random, and about eight point eight times, two will match: a million squared, over twice fifty-six point eight billion.

5:38

Measured, offline, ten times over: nine point zero on average, from four to fifteen. As predicted.

5:47

Then the real service, with codes cut to four characters, so collisions happen often. Twenty thousand one hundred forty-two links created. Twenty collisions, every one retried with a new code. None failed. About fourteen were expected; twenty or more happens by chance about one time in fifteen.

6:0906 · Numbered links

6:10

Why not number the links in order: a numbered code, a Snowflake ID from part nineteen? Time, machine and a counter: no collisions, no check. In the cloakroom: ticket forty-one tells you ticket forty-two exists.

6:26

Computed offline, at thirty-five creates a second: from one known ID, I guessed the next hundred milliseconds. Thirty-five a second is about three and a half links in any hundred milliseconds, which is why some guesses hit. Five of a hundred were real links: they would have been other people’s.

6:45

A random six-character guess finds one of a million stored links with a chance of zero point zero zero one eight percent. Numbered guesses were about two thousand eight hundred times likelier, in this sample.

7:0107 · 301 or 302?

7:02

Clash four, from the start of the video. The service is real, and the browsers are simulated: a script that, like a browser, remembers a 301 for as long as the reply says, and follows it without asking again.

7:17

Ten browsers, twenty links, twenty clicks each: four thousand clicks. A 302 means “go there, this time”. All four thousand reached us.

7:28

A 301 means “go there, from now on”, and this one said “remember it for a year”: thirty-one million five hundred thirty-six thousand seconds. Two hundred reached us.

7:40

Ten browsers times twenty links: two hundred first clicks. Every later click went from the browser’s memory, straight to the long address. In the cloakroom, it’s like telling each guest: your coat’s on hook twelve, go straight there from now on. They stop showing the ticket, so the desk stops counting.

8:0008 · The same create twice

8:02

One more: a phone loses its connection mid-create and sends it again. Each create carries an idempotency key, a name the client picks, so a retry can be recognised. I sent three hundred pairs with the same key, at the same moment, through the load balancer, so often to different app copies.

8:21

Three hundred of three hundred pairs got the same code, every time. And the code makes sure only one link is kept.

8:30

In each pair, one answer said two oh one, Created, and the other said two hundred, OK, with the same code. The second request found the first one’s key, and got its code back.

8:4409 · The key in code

8:45

Here’s how. The key goes in with the link, in the same transaction, and only if it’s new.

8:52

If another request already stored that key, this one undoes its own link, and answers with the other’s code.

9:01Back to Lucía

9:03

So, four lessons, each found the same way: switch one piece off, and measure.

9:09

A brand-new link: put it in the cache, and fall back to the primary. Without either, three in a thousand said “not found”.

9:17

Random codes, retried on a collision. Numbered IDs would let a guesser find other people’s links: five in a hundred guesses, offline.

9:28

Count clicks with a 302. A 301 is remembered, and most clicks never reach you.

9:35

And measure before you add a part. With a warm cache, the replica wasn’t needed. And the safety net held: every retried pair got the same code.

9:46

Next time, a new part of the series: moving work off the request path, with queues and event logs like Kafka.

9:54

For today: switch it off, and measure.Lucía: Switch it off, measure.

9:58Summary

9:59

Cache new links and fall back to the primary, use random codes, count with 302, and measure every part.

Key takeaways

  • ✓A 301 redirect tells every browser to remember the new address for a year (max-age=31536000 seconds). In the test, 10 browsers clicking 20 links 20 times each made 4,000 clicks: the 302 version counted all 4,000, while the 301 version let only 200 reach the server, so 3,800 clicks (95%) were never counted.
  • ✓A read that misses the cache goes to a replica, a copy of the database that can be a moment behind. With neither of the two fixes (writing the new link into the cache, or asking the primary when the replica says 'not found'), 3 of 1,031 new links returned 'not found' on their first read, 0.29%. The primary fallback alone removed all 3.
  • ✓At 3,472 redirects a second, the cache answered 84% of reads, so the database took the misses. Sending them to the replica or the primary gave a p99 of 2.31 ms against 2.16 ms in each setting's first run, and the 0.15 ms gap is smaller than the 0.45 ms gap between two runs that never missed the cache: the replica was there for availability, not speed.
  • ✓Random 6-character codes, drawn from 62 characters, give 56.8 billion possible codes. A million of them collided 9.0 times on average over 10 trials (4 to 15), against a birthday-problem prediction of 8.8, and the live service retried every collision: 20,142 creates with 4-character codes, 20 collisions, 0 failed.
  • ✓Numbered IDs would avoid the collision check but let people guess other links: at 35 creates a second, 5 of the 100 guesses made in the 100 ms after one known ID were real links, against 0.0018% for a random 6-character guess, about 2,800 times fewer.

Ten simulated browsers clicked 20 links 20 times each: 4,000 clicks. Behind a 302 redirect, the shortener counted all 4,000. Behind a 301, the browsers remembered the redirect and only 200 clicks reached the server. Nothing failed, and the page looked fine: the counter was simply never told about most of the clicks. This chapter is about the choices that make that happen, and it takes the rest of the same capstone with it: a brand-new link that returns "not found" because its read went to a copy of the database that was a moment behind, whether that copy was worth having at the target load, and the collisions of random short codes.

The examples come from Capstone A (A URL Shortener, Proven) of the system design labs. The shortener is real: HAProxy, two app processes, Redis as the cache and click counter, and a Postgres primary and replica, all in Docker on one laptop (an Apple M4 Max, Docker Desktop with 16 virtual CPUs, Postgres 18.6, Redis 7.4.2, HAProxy 3.2). Only the browsers are simulated, and the offline parts (the collision counts and the guessing test) are computed by scripts. The capstone's 388 tests run without Docker, and they include rules that stop the report from being built if a claim has no table behind it. This chapter is the second of the two for the capstone; the first covers the design written before the build and the target load.

The workflow

The capstone's measurements are scripts, run in order against the same stack:

Script What it does Time
00_setup.py Creates the tables and 1,000,000 existing links, and the redirect workload about 1 minute
01_target_load.py The design's target: 3,472 redirects a second and 35 creates a second, each new link read back at once, 2 rounds of 60 s after 30 s of warm-up about 4 minutes
02_knee.py Redirects from 1,000 to 8,000 a second, with each container's CPU, to find where it breaks about 3 minutes
03_clashes.py The four clashes in this chapter, plus the idempotency test about 6 minutes
04_cache_check.py The first run's traffic replayed through a cache simulator at several cache sizes and warm-up times seconds

Each clash in 03_clashes.py is tested the same way: switch one design choice off in the running service, keep everything else the same, and measure what breaks. The service's choices (write-through on create, the primary fallback, the redirect code) can each be turned off through its admin configuration. The video's closing line sums up the method: switch one piece off, and measure.

301 vs 302: what browsers cache, and what a click counter loses

A short link answers with a redirect: "the long address is over there." The status code says how long the answer may be kept.

  • 302 (found) means "go there, this time." Browsers don't keep it, so every click asks the shortener, and the shortener can count it.
  • 301 (moved permanently) means "go there, from now on." The shortener in the lab sent Cache-Control: public, max-age=31536000 with it, which says "keep this for 31,536,000 seconds, a year." A browser that has it goes straight to the long address on later clicks and never asks the shortener again, so the click never reaches the counter.

The test used 10 browsers, each clicking 20 links 20 times. The browsers are a script that follows a cached 301 without asking again, as a browser does:

Try it · Who counts the clicks?Lab 11 capstone A · 03_clashes.py Exercise 4 · simulated browsers

10 browsers, each clicking 20 links 20 times: 400 clicks each

browser 1browser 2browser 3browser 4browser 5browser 6browser 7browser 8browser 9browser 10
Reached the server (and was counted) Served from the browser's memory
Clicks made
4,000
Reached us
4,000
Counted
4,000
Clicks not counted
0

A 302 is not cached, so every click asks the server, and the server counts it. The 301 said max-age=31,536,000 (a year). This is a simulation of browser caching: the counts are the lab's recorded results, and real browsers' rules for caching a 301 differ.

Redirect Clicks made Reached the server Counted Lost
302 4,000 4,000 4,000 0
301 4,000 200 200 3,800 (95%)

The 200 are one per browser per link: the first click, before the browser had the 301. This is the redirect-code choice in the design: the lab kept a 302, so every click is counted. The trade-off is that each click costs one request to the shortener. A 301 costs less traffic, and it fits permanent moves of your own pages. Shorteners that sell click analytics use a 302 (or a 307).

The lab's counts are only as good as its browser model. Real browsers differ in how long and when they keep a 301, and private windows and cleared caches keep no memory at all. The point holds either way: any click a browser answers from its own memory is a click the counter never sees.

Replica lag: what a redirect reads

The redirect path reads from the cache first. On a miss, it reads the replica, and if the replica has no such link, it asks the primary. A create writes to the primary and also puts the new link into the cache, so its first read is a cache hit.

The problem is the gap between the create and the replica. A replica copies the primary's changes a moment later, so a link created a few milliseconds ago may not be on it yet. The cache hides that lag for most reads, but not for a brand-new link read by a cache miss, which is exactly the link someone has just made.

03_clashes.py Exercise 1 creates 35 links a second under 3,472 redirects a second, reads each new link back at once, and runs 30 seconds per setting:

Design New links that returned "not found" on the first read
Write-through to the cache, plus the primary fallback (the design) 0 of 1,031 (0.00%)
No write-through, primary fallback 0 of 1,031. The replica said "not found" 3 times, and the primary answered all 3
No write-through, replica only 3 of 1,031 (0.29%, 95% CI 0.10–0.85%)

Write-through on its own was not tested. The target run (01_target_load.py) also read back 2,077 and 2,128 new links in its two rounds, and none returned "not found". Over the 418,119 redirects in those rounds, none failed.

The fallback costs nothing on the common path, because it only runs when the replica says "not found". In the lab's run without write-through, that happened 3 times in 1,031 creates.

Was the replica worth it?

The replica exists to take reads off the primary, but the cache had already taken most of them: at the target, 74% of redirects were cache hits. So 03_clashes.py Exercise 2 sent the cache misses to the replica in one setting and to the primary in the other, with the same traffic, for 30 seconds in each of two rounds.

Between settings, the script resets the counters but not the cache. The second run of a round therefore finds its links already cached and reads the database almost never. The first run of each round is the one that actually missed, so those are the runs to compare:

Misses go to Database reads a second (the run that missed) Share of redirects that missed p99, first run of each round p99, cached run (no database reads)
Replica 561 16% 2.31 ms 2.17 ms
Primary 466 13% 2.16 ms 1.72 ms

The two cached runs, with no database reads at all, were 0.45 ms apart at p99, so the 0.15 ms gap between the two first runs is inside the noise. The database that took the misses used about 6% of a CPU in either setting. The capstone's report gives the difference as 0.3 ms: it averages the two rounds, which mixes in the cached runs. Either way the design's prediction held (under 2 ms of difference), and the replica added availability, not capacity, at this load. The lab didn't test a cold cache or a failed primary, which are the cases the replica is for.

Random codes and collisions

The code has six characters from 62 (lower case, upper case and digits), so there are 62⁶ = 56.8 billion codes. Pick a million at random and two will match about 8.8 times on average. The reason is that pairs are what collide: a million codes make about half a trillion pairs, and each pair has a 1 in 56.8 billion chance to match.

The measurement follows the prediction. Offline, a million random codes were drawn 10 times: the collisions were 12, 7, 9, 4, 10, 15, 8, 12, 8 and 5, a mean of 9.0. The service has to check each new code and retry on a match, and it did.

To see the live path, the service was run with 4-character codes, where collisions are common. It created 20,142 links with 20 collisions, every one retried with a new code, and no create failed. The birthday prediction for that run was about 13.7 collisions; 20 or more happens by chance about one time in fifteen, so it fits the model. Plan for the check: the design estimates a 3.2% chance per insert once 1.8 billion links exist, and says to move to 7 characters before year 5.

Numbered IDs (the time-based Snowflake IDs from Chapter 19) never collide, but they are predictable. 03_clashes.py Exercise 3 computed this offline with a simulated clock: with 35 creates a second, the 100 milliseconds after one known ID hold about 3.5 links, and the 100 guesses for those 100 milliseconds found 5 real links, which would have been other people's. A random 6-character guess hits one of a million stored links with a chance of 0.0018% per guess, about 2,800 times less likely. Random codes cost a retry on collision, and the numbered version would let anyone with one link walk to its neighbours.

The same create, twice

A phone that loses its connection mid-create will send it again. 03_clashes.py Exercise 5 sends 300 pairs of creates with the same Idempotency-Key header (a key the client picks, so a retry can be recognized), at the same moment, through HAProxy to both app processes. Every pair got the same code, and the key was stored with the link in the same transaction, so only one link was kept. One answer in each pair was 201 (created) and the other 200 (a replay of the first). The mechanism is the one from Chapter 10.

Caveats

  • One run per setting. The 0.29% in Exercise 1 is 3 links out of 1,031, and its interval runs from 0.10% to 0.85%. The latency numbers are single runs on a laptop that was busy (a load average of 5 to 18 across the capstone). The first target run missed its latency targets for that reason and was run again.
  • Simulated browsers. The 301 result is a model of browser caching. The lab's browser follows the cache header exactly, which real browsers don't always do.
  • Write-through alone was not tested. The lab shows the fallback is enough by itself, and the fix that puts the link into the cache is in the design, but its separate effect is not measured.
  • Offline collision and guessing numbers. The 6-character collisions and the Snowflake guessing are computed from the formulas and a simulated clock. The live service only ran the 4-character case.
  • The cache hit ratio depends on age. In a 30 s run the simulator gives 74.3% for any cache size, but after 300 s it gives 77.9% to 85.9%, depending on the cache size (04_cache_check.py). A 90 s run never reaches steady state, so the 74% is not a production number.
  • Click counts live in Redis. A Redis restart loses the counts, and flushing them to the database is one of the capstone's recommendations, not something it built.
  • Not tested: the primary failing over, a dead app process under load, spam or enumeration, and TLS.

Check your understanding

Try each question before opening its answer.

Ten browsers click 20 links 20 times each. Why does a 302 count all 4,000 clicks and a 301 count 200?

A 302 means "go there, this time," so no browser keeps it and every click asks the shortener. A 301 with max-age=31536000 is kept for a year: after the first click on each link, the browser goes straight to the long address and never asks again. The 200 that arrived were the first click of each browser on each of the 20 links, and 3,800 clicks (95%) were never counted.

A brand-new link returns "not found" on its first read. Where did the read go, and what did the primary fallback change?

On a cache miss the read goes to the replica, which can be a moment behind the primary where the link was just written. Without the fallback, the replica's "not found" was the answer, and 3 of 1,031 new links failed that way (0.29%). With the fallback, a "not found" from the replica is checked against the primary, which had all three, so none failed (0 of 1,031).

At the target load, was the read replica needed to keep redirects fast?

Not for speed at this load. Sending the cache misses to the primary instead of the replica gave the same p99 within the noise: 2.31 ms against 2.16 ms in each setting's first run, while two runs that never missed the cache were 0.45 ms apart. The replica is there for availability, which this test did not try.

A million random 6-character codes collide about 9 times. Why, and what does the service do about it?

The collisions come from pairs. A million codes make about half a trillion pairs, and each pair matches with a chance of 1 in 56.8 billion, so about 8.8 pairs match by chance. The measured mean was 9.0 over 10 trials. The service checks each new code and retries on a match, and in the live test with 4-character codes every one of 20 collisions was retried with no failed create.

Why not use numbered IDs, which never collide?

They are guessable. From one known Snowflake ID, the next 100 milliseconds at 35 creates a second held 5 real links, so a guesser who has one link can find others. A random 6-character guess finds one of a million links with a chance of 0.0018%, about 2,800 times less likely. The cost of random codes is the collision check and the retry.

The next chapter in the track, Chapter 25, moves work off the request path with queues and event logs like Kafka.

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.