A redirect path that serves 100k reads per second
Build lnk.example's redirect path step by step: pick 302 or 301 from RFC 9110 and set cache headers on purpose, layer an in-process cache, a shared cache and replicas, turn hit ratios into store load, and predict what happens in cold-cache, viral-link and scanning miss storms.
Contentsand lesson path
On this page
- The problem
- Step 1: 301 or 302, and the cache headers
- Step 2: The layers of the path
- Step 3: Hit ratio decides the store's load
- Step 4: Predict, then run: an L1 in every server
- Step 5: Miss storms
- Check your understanding
- Apply it
- Review prompt
Lessons of URL Shortener Design
- Scoping and estimating a link shortener Worked example · 20 min
- Code generation and the data model Worked example · 25 min
- A redirect path that serves 100k reads per second Worked example · 25 min
- Abuse, expiry and analytics without slowing redirects Concept · 15 min
- Shortener design check Knowledge check · 6 questions
What you will learn
- Scale the redirect path with caching and replicas, and move click analytics and abuse checks off the critical path.
Prerequisites: Requirements & Estimation, Caching Strategies, Unique ID Generation
01. The problem
Lesson 1 set the target for lnk.example: 100,000 redirects a second at the worst peak, 99% answered within 25 ms inside our servers. Every click must reach us to be counted, a disabled or edited link must change for everyone within 5 minutes, and a new link must work at once. Lesson 2 gave the record that one read by code returns.
This lesson decides what the redirect says, which caches sit in front of the store, how much load reaches the store, and what happens when caching stops helping. It applies hit-ratio arithmetic and stampede defences. You need Python 3.10 or newer and curl.
02. Step 1: 301 or 302, and the cache headers
Of the redirect codes in RFC 9110 (300 to 308), two pairs matter for a shortener. 301 (Moved Permanently) and 308 (Permanent Redirect) say that the resource has a new permanent address and that future references ought to use it. 302 (Found) and 307 (Temporary Redirect) say it is temporarily elsewhere, so the client ought to keep using the original address. 307 and 308 also forbid changing the method, say from POST to GET; for clicked links, which are GET requests, each pair behaves alike.
The difference that matters is caching. RFC 9110 lists 301 and 308 as heuristically cacheable: a browser or CDN may reuse them without any cache header, for a lifetime it picks, since RFC 9111 gives no formula. While a browser's copy of a 301 stays fresh, its clicks do not reach you: no count, and no way to apply a disable or an edit. 302 and 307 are not heuristically cacheable, so caches keep them only if headers allow it. Headers win both ways: a 302 with Cache-Control: max-age=86400 may be kept for a day, and a 301 with no-store is not kept at all.
Decision: lnk.example answers with 302 and Cache-Control: no-store, also on its 404 responses. Every click reaches the service, and a disable reaches visitors as soon as our own caches drop the old entry. A 301, with an explicit max-age, suits a link that is permanent, never edited and not counted. Start this server with python3 redirect_server.py in one terminal and run curl in another; if curl prints only the == lines, the server is not listening yet (Ctrl+C stops it):
"""A minimal redirect endpoint, to read status codes and cache headers."""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
LINKS = { # code: (target, status)
"aZ3kP9q": ("https://shop.example/spring", 302), # a normal short link
"old-docs": ("https://docs.example/v2/", 301), # a page that moved for good
}
class Redirect(BaseHTTPRequestHandler):
def do_GET(self) -> None:
target, status = LINKS.get(self.path.lstrip("/"), (None, 404))
self.send_response(status)
if target:
self.send_header("Location", target)
if status == 301: # permanent: let every cache keep it for a day
self.send_header("Cache-Control", "public, max-age=86400")
else: # every click and every "not found" must reach us
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", "0")
self.end_headers()
def log_message(self, *args) -> None: # keep the terminal quiet
pass
if __name__ == "__main__":
ThreadingHTTPServer(("127.0.0.1", 18630), Redirect).serve_forever()for code in aZ3kP9q old-docs nope123; do
echo "== /$code"
curl -s -o /dev/null -D - "http://127.0.0.1:18630/$code" \
| tr -d '\r' | grep -iE '^(HTTP|location|cache-control)'
done== /aZ3kP9q
HTTP/1.0 302 Found
Location: https://shop.example/spring
Cache-Control: no-store
== /old-docs
HTTP/1.0 301 Moved Permanently
Location: https://docs.example/v2/
Cache-Control: public, max-age=86400
== /nope123
HTTP/1.0 404 Not Found
Cache-Control: no-store03. Step 2: The layers of the path
Each layer below exists for a reason you can name:
browser -> CDN edge (TLS ends near the user; redirects are not cached here)
-> load balancer -> 20+ redirect servers, each with an L1 cache (TTL 30 s)
| miss
v
L2: shared cache cluster (TTL 4 min, replicated)
| miss
v
link store: key-value, 3 copies of every linkThe CDN does not cache redirects, but it ends the TLS handshake near the user (see the CDN request path). The redirect servers keep no state, so more can be added at peak. L1 is a small in-process cache in each server; L2 is a shared cluster, replicated so that losing one node does not empty it.
The TTLs follow from the freshness target. When a link is disabled or edited, the writer puts the new record, with its higher version, into L2 and broadcasts an invalidation to the servers' L1s. L2 accepts a fill only if its version is newer than the one it holds, so a slow reader cannot put the old record back (see stampedes and hot keys). Messages can still be lost, so the TTLs bound the worst case: 30 seconds in L1 on top of 4 minutes in L2, plus the lag of the store copy that refilled L2. We assume that lag stays under 30 seconds, keeping a stale redirect within the 5-minute target; measure it. A 1-minute target would need shorter TTLs.
The store keeps three copies of each link, and reads can go to any copy, which adds read capacity and survives losing a machine (see leaders and replicas). A copy that has not yet received a new link would answer not found to its creator's first click, so creation also writes the link into L2, and a not found from a copy is retried once with the store's strongest read.
On a hit, latency is rarely the problem: an in-zone round trip is a fraction of a millisecond (see the latency ladder). The risk to the 25 ms p99 is queueing in an overloaded layer.
04. Step 3: Hit ratio decides the store's load
The store sees only the misses: store reads per second = 100,000 × (1 − hit ratio), so each point of hit ratio is 1,000 store reads a second. cache_sim.py replays a stream of codes through LRU caches, which evict the least recently used entry. Its stream is a simplified model: 200,000 links instead of billions, popularity following a Zipf law with exponent s (higher s bunches clicks on fewer links), no TTLs and no daily rhythm. It shows shapes, not a forecast.
"""Replay a click stream through LRU caches (standard library only).
stream() is a model: KEYS links whose popularity follows a Zipf law with
exponent s. Real traffic also has time locality (new links are hot), so size a
real cache by passing replay() the codes from your access log, in order.
"""
import random
from collections import OrderedDict
from itertools import accumulate
KEYS, REQUESTS = 200_000, 1_000_000
class LRU:
def __init__(self, capacity: int) -> None:
self.capacity, self.items = capacity, OrderedDict()
def get(self, key) -> bool:
if key in self.items:
self.items.move_to_end(key)
return True
return False
def put(self, key) -> None:
self.items[key] = True
self.items.move_to_end(key)
if len(self.items) > self.capacity:
self.items.popitem(last=False) # evict the least recently used
def stream(s: float, seed: int = 2026) -> list[int]:
rng = random.Random(seed)
cum = list(accumulate(1 / rank**s for rank in range(1, KEYS + 1)))
return rng.choices(range(KEYS), cum_weights=cum, k=REQUESTS)
def replay(reqs, l2_size: int, l1_size: int = 0, instances: int = 20,
scan_every: int = 0, cache_misses: bool = False) -> dict:
"""Count reads at each layer. reqs holds one code per request: ints from
stream() or strings from a log. Every scan_every-th request becomes a
scanner's code that does not exist; cache_misses stores "not found" in L2."""
l1s = [LRU(l1_size) for _ in range(instances)]
l2, n = LRU(l2_size), {"requests": 0, "l2_reads": 0, "store_reads": 0}
scan = random.Random(7)
for i, key in enumerate(reqs):
if scan_every and i % scan_every == 0:
key = ("scan", scan.randrange(10**12)) # a code nobody created
n["requests"] += 1
l1 = l1s[i % instances] # the load balancer spreads requests evenly
if l1_size and l1.get(key):
continue
n["l2_reads"] += 1
if not l2.get(key):
n["store_reads"] += 1
if not isinstance(key, tuple) or cache_misses:
l2.put(key)
if l1_size:
l1.put(key)
return npython3 - <<'PY'
from cache_sim import KEYS, replay, stream
shares = (1, 5, 10, 20, 100) # L2 size as a % of the 200,000 links
print("skew s " + "".join(f"{p:>7}%" for p in shares) + " store reads/s, 10% L2")
for s in (0.8, 1.0, 1.2):
reqs = stream(s)
hits = [1 - replay(reqs, KEYS * p // 100)["store_reads"] / len(reqs)
for p in shares]
row = "".join(f"{h:8.1%}" for h in hits)
print(f"{s:6} {row} {100_000 * (1 - hits[2]):>21,.0f}")
PYskew s 1% 5% 10% 20% 100% store reads/s, 10% L2
0.8 21.5% 37.7% 47.3% 58.8% 83.0% 52,720
1.0 53.3% 68.2% 74.7% 81.1% 87.9% 25,266
1.2 82.4% 90.0% 92.4% 93.9% 94.2% 7,642With an L2 holding 10% of the links, the store sees about 7,600 to 53,000 reads a second, depending on the skew. The 100% column never evicts, yet still misses each link's first click: a cache filled on misses cannot hold a link nobody has opened. Until real logs exist, plan the store's capacity for the pessimistic end; then pass replay a day's codes from the access log, one string per request, in order, as this run does:
python3 - <<'PY'
import random
import string
from cache_sim import KEYS, replay, stream
# Turn the model into a log of real-looking codes: one 7-character code per link.
abc = string.digits + string.ascii_uppercase + string.ascii_lowercase
rng = random.Random(1)
names = {}
for link in range(KEYS):
names[link] = "".join(rng.choices(abc, k=7))
log = [names[link] for link in stream(1.0)] # strings, as an access log holds
print(log[:4], f"... {len(log):,} requests")
print(replay(log, KEYS // 10))
PY['RiEwt11', 'p6m9imw', 'LhrYHMX', 'Zn0LyBc'] ... 1,000,000 requests
{'requests': 1000000, 'l2_reads': 1000000, 'store_reads': 252660}The misses match the integer run: replay only needs codes that are equal when the link is the same. Writing campaign links into L2 at creation removes their first-click miss, at the cost of memory for links that may never be opened.
05. Step 4: Predict, then run: an L1 in every server
Before running the next command, predict: if each of 20 servers adds a 1,000-entry L1 that answers about half of all requests, what happens to reads on the store?
python3 - <<'PY'
from cache_sim import KEYS, replay, stream
reqs = stream(1.0)
for l1 in (0, 1_000): # entries in each of the 20 redirect servers
n = replay(reqs, KEYS // 10, l1_size=l1)
print(f"L1 {l1:>5} per server: L2 reads {n['l2_reads']:>9,}"
f" store reads {n['store_reads']:>7,}")
PYL1 0 per server: L2 reads 1,000,000 store reads 252,660
L1 1000 per server: L2 reads 531,887 store reads 253,013L2 reads fell by 47%, but store reads hardly moved. The links an L1 keeps are the most clicked ones, and L2 was already answering those, so the misses that reach the store are the same tail as before. An L1 still earns its place: it saves a network hop for the hottest links and shields the L2 node that owns a viral key. It does not shrink the store tier, and it adds staleness.
06. Step 5: Miss storms
Three events can push the store far above 100,000 × (1 − hit ratio).
A cold cache at peak. If L2 is lost or replaced empty, nearly every redirect misses. Suppose the store serves 25,000 reads a second. Refilling all 56 million hot links of lesson 1's worst case takes at least 2,240 seconds, but the overload lasts until the miss rate falls below 25,000 a second: sooner when the hottest links return first, later if misses on one key are not coalesced. Keep L2 replicated, warm a new cluster with the last hour's most-clicked links before moving traffic, and shed load rather than let queues grow.
A viral link that is not cached yet. A link mailed to 2 million people a minute after it was created gets thousands of concurrent misses on one key. Coalescing lets one request per server fetch it while the others wait; writing campaign links into L2 at creation avoids the miss.
A scan of codes that do not exist. Every request misses, because there is nothing to cache. Predict before running: will storing not found answers in L2 help?
python3 - <<'PY'
from cache_sim import KEYS, replay, stream
reqs = stream(1.0) # one request in six now comes from a scanner
for negative in (False, True):
n = replay(reqs, KEYS // 10, scan_every=6, cache_misses=negative)
print(f"cache 'not found': {negative!s:5} store reads {n['store_reads']:,}")
PYcache 'not found': False store reads 377,815
cache 'not found': True store reads 411,620It made things worse. Random codes almost never repeat, so the cached not found entries are never read again, and they push real links out of the LRU. Negative caching helps when the same missing code is asked for again and again, such as a typo printed on a flyer; then keep those entries few, short-lived and deleted when the code is created. Scans are slowed by limiting unknown-code answers per client (lesson 4).
07. Check your understanding
08. Apply it
Write the redirect-path section of your design doc for 100 million new links a month:
- Status code and Cache-Control for active, unknown and disabled links, with reasons.
- Your layers and TTLs, with arithmetic showing they meet your freshness target.
- Store read capacity at your peak for a pessimistic and an optimistic hit ratio.
- What happens when each component fails: CDN, load balancer, servers, L1, L2, store.
09. Review prompt
Without looking back: what do 301, 302, 307 and 308 promise, and which may a cache store with no headers? Why does lnk.example send 302 with no-store? How does a hit ratio become store reads, and why does an L1 not change them? How do the TTLs follow from the freshness target? Name three miss storms and a defence for each.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.