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=31536000with 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:
10 browsers, each clicking 20 links 20 times: 400 clicks each
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.