Course contents

17. Real-World System Design Lesson 1 of 20

URL Shortener

Design a URL shortener end to end: estimates, base62 ids from leased counter blocks, cached redirects, a CDN for viral spikes, 301 vs 302 and a cache outage.

20 minAdvanced12 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Reads outnumber writes about 100:1 and the data is small: this is a caching problem, not a storage problem.
  • Leased id blocks + a permutation + base62 give short, unique, non-sequential codes without a hot counter.
  • Cache aside in front of a key-value store absorbs skewed redirect traffic with a small cache.
  • Each cache moves the bottleneck to the next tier; the edge can absorb spikes but hides clicks.
  • 302 keeps every click visible and deletes effective; 301 trades both for fewer requests.
  • Layer caches (in-process, shared, edge) so one cache failure does not land on the database.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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.

The lesson as textEvery step of the simulation, written out.
  1. 1. Two operations, very different volumes

    A URL shortener does two things. Create: POST /links stores code → long URL and returns sho.rt/aZ3kQ9x. Redirect: GET /aZ3kQ9x looks the code up and answers with a redirect to the long URL.

    Watch one of each (a scripted walk-through; no simulated traffic yet). The create writes one row. The click reads it. A link is created once and clicked many times, often in a sudden burst after it is shared, so the redirect is the path to design for.

    The full interview version, with API and data model, is at /system-design/interviews/url-shortener.

    Scene: Scripted: the link creator sends one create request through the load balancer to Redirect API 1, which writes to the link store and answers. Then a clicker sends a redirect request through API 2, which reads the link and returns a 302.

    Key idea: Find the hot path first: here it is a single key lookup, repeated millions of times.

  2. 2. Turn the requirements into numbers

    The interview assumes 100 million new links a month and 100 reads per write. That is about 40 creates per second and 4,000 redirects per second on average, several times more at peak. Over 5 years: 6 billion links × ~500 bytes ≈ 3 TB. Storage is easy; read throughput is the problem.

    The simulation runs at roughly a tenth of that scale. Clickers now send 200 redirects per second, each a database read. The link store (10 connections, ~15 ms per read, about 650 reads/s) is about a third busy and every redirect succeeds.

    Scene: Clickers send 200 redirects per second. Each is a read on the link store, which is about a third busy; nothing fails.

    Key idea: Reads dominate by two orders of magnitude, and the data fits on a few machines: this is a caching problem, not a storage problem.

  3. 3. Generating unique 7-character codes

    Codes use base62 (a–z A–Z 0–9): 62⁷ ≈ 3.5 trillion codes, enough for 6 billion links. Two common ways to get them:

    Hash the long URL (first 7 base62 characters of SHA-256). No coordination, but collisions grow with volume, so every create must check and re-hash. Counter ranges (shown, scripted): each API instance leases a block of, say, 1,000 ids from an allocator in one atomic update, then hands ids out from memory. One allocator call per thousand links, no collisions between instances. Base62 of a raw counter is guessable, so the id is permuted before encoding. The store still inserts conditionally (if not exists) as a safety net.

    Scene: Scripted: API 1 and API 2 each lease one block of ids from the ID allocator, then insert three links each into the link store without calling the allocator again. Redirect traffic keeps running in the background.

    Key idea: Lease id blocks so the counter is not on the hot path; let the database enforce uniqueness anyway.

  4. 4. Clicks outgrow the link store

    Traffic grows to 800 redirects per second. Every one is a read on the link store, which can do about 650 per second. Reads queue for connections and the redirect servers hold a worker for every read they are waiting on. Their workers run out, their queues fill, and they start rejecting requests (503).

    Most of those reads are for the same popular links. The store is answering the same question over and over.

    Scene: At 800 redirects per second the link store is saturated: reads wait for connections, the redirect servers fill up with waiting requests and reject some; latency climbs.

    Key idea: A key lookup is cheap, but not free: at read-heavy scale the database becomes the bottleneck.

  5. 5. Cache code → URL in Redis

    The redirect servers now look the code up in a shared Redis cache first and read the store only on a miss, then put the link into the cache (cache aside). Links almost never change, so entries can live for hours.

    Redis holds only 2,000 of the 20,000 links, yet about two thirds of clicks hit it, because popularity is skewed. The store sees only the misses, the errors stop and median latency drops.

    Scene: Redirect servers ask Redis first and read the link store only on a miss. About two thirds of clicks are cache hits; the store is no longer saturated and nothing fails.

    Key idea: Immutable, skewed data is the best case for a cache: a small cache absorbs most reads.

  6. 6. A link goes viral

    One second in, a link is shared widely and traffic jumps to 1,600 redirects per second. The cache still answers most clicks, but now the redirect servers run out of workers: every request holds a worker for the cache round trip, and misses hold it for the store read too. Their queues fill and they reject requests.

    We could add servers. But viral traffic is spiky and global: the cheaper place to absorb it is closer to the users.

    Scene: Traffic doubles to 1,600 redirects per second. Both redirect servers become overloaded with full queues and reject some requests; the cache keeps its hit ratio.

    Key idea: A cache moves the bottleneck, it does not remove it: the next tier saturates at the next traffic level.

  7. 7. Let the edge answer repeat clicks

    Clickers now reach a CDN. We let it cache our 302 responses for a short time (say 60 seconds), so a repeat click on a popular link is answered at the edge, close to the user, without reaching our servers.

    The edge cache keeps the last 4,000 redirects it passed on and answers about three quarters of clicks. The origin sees only the rest, under 400 per second, so the rejections stop, and the median redirect gets faster because the edge is nearer than the origin.

    Watch Redis: it now almost never hits. The edge already holds the popular links, so what gets through is the long tail, which Redis does not have either. Every edge miss becomes a store read; that is fine at this volume, but caches stacked in front of each other share one head of popularity, not two. The price of the edge: deleting or blocking a link takes up to 60 seconds to take effect there.

    Scene: Clickers go through a CDN edge that answers about three quarters of redirects from its cache. Only the misses reach the load balancer and nothing fails; Redis behind the edge now almost never hits, so each miss becomes a link store read.

    Key idea: Edge caching absorbs spikes for free, at the cost of slower invalidation. A cache behind it only sees the tail, so its hit ratio collapses.

  8. 8. Counting clicks you never see

    Owners want click counts. Each redirect server now drops a click event on a queue (about a millisecond, the redirect does not wait for analytics) and a worker aggregates them into per-day counters.

    But only clicks that reach the origin produce an event. With the edge answering about three quarters of clicks, the pipeline counts about one click in four. To count the rest you would need the CDN’s logs, which arrive late and in another format.

    Scene: Redirect servers emit a click event to a queue, consumed by a click aggregator. Because the CDN edge answers about three quarters of clicks, only about one in four clicks produces an event.

    Key idea: Every cache in front of you hides requests from you: analytics and caching pull in opposite directions.

  9. 9. 301 or 302?

    A 301 (permanent) tells the browser to remember the redirect. In the scripted walk-through, the second click goes straight from the browser to the destination: no edge, no origin, no count, and deleting or expiring the link no longer works for that browser.

    A 302 (temporary) is asked for every time. The interview design picks 302 and does not cache redirects at the edge, so every click is counted and deletes take effect at once. The CDN still terminates TLS near users and forwards everything. All 1,600 clicks per second now reach the origin again, and every one produces a click event.

    Scene: Scripted: a browser follows a 301 once through the CDN, then goes straight to the destination site on the second click. Meanwhile the edge stops caching 302s, the redirect servers are scaled to 16 workers, all 1,600 clicks per second reach the origin and each one produces a click event.

    Key idea: 301 trades control and analytics for fewer requests; 302 keeps every click visible. Edge caching of 302s is a lever to pull only when the origin struggles.

  10. 10. The cache goes down

    One second in, Redis crashes. The redirect servers treat that as a miss and read the link store, which is correct for cache aside, but the store was sized for misses only. It suddenly gets every click, saturates, and redirects start failing.

    This is the failure that matters most for this design: the cache is carrying most of the read capacity.

    Scene: Redis goes offline. Every click falls through to the link store, which saturates; redirects slow down and some fail.

    Key idea: If the cache carries load, losing it is a capacity event, not just a latency blip.

  11. 11. A small cache inside every server

    Each redirect server gets a tiny in-process LRU of the 2,000 hottest links, checked before Redis. It costs no network hop and keeps working when Redis does not.

    Redis is still down, but the local caches answer about two thirds of all clicks. The link store gets the rest, about 500 reads per second, which it can handle: the errors stop. In production you would also run Redis with replicas so a failover takes seconds, and keep enough store headroom for a cold cache.

    Scene: Each redirect server checks its own in-process LRU before Redis. Redis is still offline, but the local caches answer about two thirds of the clicks and the link store keeps up; nothing fails.

    Key idea: Layer caches so no single cache failure sends all traffic to the database.

  12. 12. The design, and what it trades

    Redis is back (empty, filling up again). The final design: leased id blocks + base62 for creates; a key-value store; in-process LRU, then Redis, then the store for redirects; a CDN in front; click events on a queue; 302 redirects.

    The trade-offs you chose: 302 over 301 (every click counted, deletes work, more traffic); no edge caching of redirects (accurate analytics, origin must carry the peak, edge caching kept as an emergency lever); counter blocks over hashing (no collision loop, but an allocator to run); async analytics (redirects never wait, counts lag by minutes).

    Scene: The full design runs at 1,600 clicks per second: CDN pass-through, two redirect servers with local LRUs, Redis, the link store and the click pipeline. Nothing fails.

    Key idea: A URL shortener is a read-heavy key-value lookup: estimate, cache in layers, and decide explicitly what you give up for analytics.