What it is
A URL shortener maps a short code to a long URL. POST /links with a long URL returns https://sho.rt/aZ3kQ9x; GET /aZ3kQ9x answers with an HTTP redirect whose Location header is the long URL. Signed-in users can usually pick a custom alias, set an expiry and see click counts.
The design is small enough to finish in an interview and still touches most of the core ideas: estimating, id generation, a read-heavy key-value data path, caching in layers, edges and analytics. This lesson builds the design in the 3D scene and runs its hard parts in the simulation. The full interview version, with API, data model and deep dives, is at /system-design/interviews/url-shortener.
Why it exists
Long URLs break in chat messages, printed material and character-limited posts, and they reveal tracking parameters. A short link is easy to share, can be changed or disabled after it was published, and tells its owner how often it was opened. Those last two properties (control and counting) are what shape the redirect design.
How it works
Requirements and estimates. The interview assumes 100 million new links per month and a 100:1 read-to-write ratio:
| Quantity | Arithmetic | Result |
|---|---|---|
| Creates, average | 100M ÷ (30 × 86,400 s) | ≈ 40 /s |
| Redirects, average | 40 × 100 | ≈ 4,000 /s |
| Links over 5 years | 100M × 60 | 6 billion |
| Storage | 6B × ~500 B per row | ≈ 3 TB (plus replicas) |
| Code space, 7 base62 characters | 62⁷ | ≈ 3.5 × 10¹² |
Three terabytes fits a small partitioned key-value store. Thousands of reads per second, with spikes when a link goes viral, is the actual problem.
Short codes. Base62 (a–z, A–Z, 0–9) packs about 5.95 bits per character, so 7 characters give 3.5 trillion codes. The two common sources of uniqueness:
- Hash the long URL and keep 7 characters. No coordination, but collisions become more frequent as the space fills, so every create needs check-then-insert and a re-hash on collision, and identical URLs map to the same code unless you salt per owner.
- Counter ranges. Each API instance leases a block of ids (say 1,000) from an allocator in one atomic update, then hands ids out from memory. One allocator call per thousand links, and blocks never overlap. Base62 of a raw counter is sequential and therefore enumerable, so the interview design passes the id through a keyed permutation before encoding. That is obfuscation, not security. Either way, the store inserts conditionally (
if not exists), so uniqueness is enforced by the database, not by trusting the generator.
The redirect path. One lookup by primary key: code → long URL, status, expiry. No joins, no range scans. A partitioned key-value or wide-column store fits. In front of it sits a cache (cache aside: read the cache, on a miss read the store and fill the cache). Links are written once and rarely change, and popularity is heavily skewed, so a cache holding a small fraction of links answers most clicks. In the simulation, Redis holds 10% of the links and answers about two thirds of clicks.
Spikes and the edge. A cache moves the bottleneck: in the simulation the redirect servers saturate next, because each request holds a worker for its cache round trip. A CDN in front can absorb spikes by caching redirect responses briefly (for example Cache-Control: max-age=60 on the 302). Repeat clicks are answered at the edge, faster and without reaching the origin. One side effect shows up in the simulation: the shared cache behind the edge now sees only the long tail and its hit ratio collapses, so every edge miss becomes a store read. Size the store for the edge's misses, not for what is left after two caches.
Analytics. Each redirect emits a click event to a queue or log; an aggregator rolls events into per-link, per-day counters. The redirect never waits for analytics. Only requests that reach the origin produce events, so anything answered from a cache in front (CDN or browser) is invisible unless you import its logs.
301 or 302. A 301 is permanent: browsers cache it, often with no expiry, and later clicks go directly to the destination. A 302 (or 307) is temporary and requested each time. The interview design uses 302 and does not cache redirects at the edge by default, so every click is counted and deleting or blocking a link takes effect immediately. Edge caching of 302s stays available as an emergency lever.
Failure: the cache. If the shared cache dies, cache aside falls back to the store, which was sized for misses only. A small in-process LRU in every redirect server (a few thousand hottest links) keeps most clicks off the store while the shared cache is down, and replicas let the shared cache fail over in seconds.
When to use it
Use this shape (write-once small records, read many times by key, skewed popularity) for short links, invite codes, QR-code targets, deep links, feature-flag lookups and any public resolver of identifiers. The same layering (local cache, shared cache, store, optional edge) applies to most read-heavy lookup services.
When not to
- If you do not need control or counts, a 301 or a static redirect file served by a CDN or object storage is simpler and has no servers on the read path.
- For internal links at low volume, a single relational table with an index is enough; the caching tiers are only worth running at scale.
- If codes must be unguessable (private document links), use long random tokens (128 bits or more) instead of 7-character codes; the short code space is easy to scan.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| 302 instead of 301 | Every click counted; deletes and expiry work at once | Every click reaches you: more traffic and cost |
| No edge caching of redirects | Accurate analytics, instant invalidation | The origin must carry the peak |
| Edge caching of 302s (short TTL) | Spikes absorbed close to users | Deletes take up to the TTL; counts need CDN logs |
| Leased counter blocks | No collision loop, one allocator call per block | An allocator to run; gaps when instances die with unused ids |
| Hashing the URL | No coordination at all | Collision checks, dedup semantics, growing retries |
| Asynchronous click analytics | Redirects never wait on analytics | Counts lag by minutes and can be approximate |
| In-process LRU | No network hop; survives a shared-cache outage | Staleness per server; must purge or use short TTLs for blocked links |
Alternatives
- Random codes with a conditional insert: no allocator, occasional retry; fine at moderate volume.
- Snowflake-style ids (time + machine + sequence) encoded in base62: no allocator call, but 64-bit ids need about 11 characters, not 7.
- Edge-only redirects: links replicated into a CDN key-value store and resolved by edge functions; lowest latency, vendor-specific, analytics from edge logs.
- A relational database instead of a key-value store: perfectly workable with an index at small and medium scale.
Failure modes
- Cache outage: the store receives every read and saturates (simulated in the lesson). Mitigate with layered caches, cache replicas and store headroom.
- Cold cache after restart: a recovered cache is empty, so misses spike until it refills; request coalescing keeps many concurrent misses for one hot link down to one store read.
- Viral spike on one link: one hot key concentrates on one cache shard. In-process caches and the edge spread it.
- Allocator restored from an old backup: hands out used ranges; the conditional insert catches every collision, and a conflict-rate alert should fire.
- Abuse: phishing and malware links, and scanners walking the code space. Check destinations against threat feeds, rate-limit creates per account and IP, cache negative lookups briefly, and be able to block a link instantly (purging the caches you control).
In production
Measure redirect latency at the server, hit ratios per cache tier, store read rate, and 404 rate (sudden growth means scanning). Cache TTLs should be capped at each link's expiry. Purge caches when a link is deleted or blocked, and keep in-process TTLs short enough that a blocked link stops redirecting within an acceptable window. Keep raw click events in cheap storage so counters can be recomputed. Rate-limit creation at the gateway (Rate Limiter).
Common misconceptions
- "It is a storage problem." Billions of links are only terabytes. The challenge is read throughput and spikes.
- "Hash the URL and you are done." You still need collision handling, and hashing gives identical codes for identical URLs, which may leak that someone else shortened the same URL.
- "301 is better because it is faster." It is fewer requests, but you lose counts and the ability to change or delete the link for browsers that cached it.
- "With a cache, the database no longer matters." The cache carries load; when it fails, the database gets everything (step 10 of the lesson).
Interview angle
State the read-to-write ratio early, estimate QPS and storage, then spend your time on the redirect path. Expect questions on id generation (and why sequential codes are a problem), the cache and its failure, 301 vs 302 and its effect on analytics, hot links, and abuse. A strong answer names what each cache hides and what happens when it fails. Work the full problem at /system-design/interviews/url-shortener; the Pastebin case study is the same shape with real payloads.
Model assumptions
The simulation is a simplified model, not a benchmark, at roughly a tenth of the interview's scale. Clicks arrive as a Poisson process over 20,000 links with a Zipf(1) popularity. Each redirect server has 8 workers (16 from the 301 vs 302 step onwards), about 3 ms of its own work (lognormal, cv 0.3) and holds a worker while it waits for the cache and the store. The link store has 10 connections, a 15 ms mean read (about 650 reads/s) and fails a query that waits more than 150 ms for a connection. Redis is an LRU of 2,000 links; each in-process LRU holds 2,000 links. The CDN edge cache is an LRU of 4,000 redirects with a 60-second TTL that stores every answer coming back from the origin; its hit ratio (about three quarters) emerges from the popularity skew, and it starts cold in each step. Click events are enqueued synchronously in about a millisecond; in production they are buffered and sent asynchronously. Link creation, id leasing and the browser's handling of a 301 are scripted illustrations (packets drawn on a fixed schedule), not simulated. Network hops take a fixed 0–30 ms. Numbers show behaviour and orders of magnitude only.