Design a URL shortener at scale
Company tags are compiled from public interview reports and are signals, not guarantees.
What interviewers are testing
Interviewers want to see structured estimation before design: pinning requirements, deriving a 100:1 read:write ratio, and letting those numbers pick the architecture. The shortener also forces a real decision — ID generation strategy and 301 versus 302 — where every answer has a visible consequence for scale and analytics.
Mental model
URL shortening is a write-once, read-forever lookup: a key generator — a secret counter, a Snowflake, or random bytes encoded in base62 — produces the key, a key-value store is the source of truth, and caches at the edge absorb the 100:1 read traffic. Random keys are unguessable; counter and Snowflake keys are unpredictable only while the sequence state stays secret, and sequential values leak volume and ordering. The redirect status code is a product decision: 301 maximizes cacheability, 302 keeps every click visible to analytics.
Step-by-step solution
Step 1: Requirements and back-of-envelope math
Start by pinning requirements: shorten a long URL into a small one, redirect with minimal latency, and optionally support custom aliases, expiry, and click analytics. Then do the math out loud. Suppose 100 million new links per day; that is about 1,160 writes per second. Because a link is clicked roughly 100 times for every one created, reads land near 116,000 per second, a 100:1 read-to-write ratio. Seven base62 characters give 62^7, about 3.5 trillion keys, so a workload at this scale lasts decades. The estimate drives every later decision: the system is read-dominated, so caches, replicas, and CDN edges matter far more than write throughput, and the storage footprint stays trivial once you store only the mapping and a little metadata. Watch the animation as the request walks from the client through the stateless API tier while the read:write math sets the design priorities.
Step 2: Generate unique base62 keys
Generating the key is the only genuinely hard part. Three families exist. A global counter encoded in base62 is simple, collision-free, and predictable, but sequential keys are guessable and one counter is a bottleneck — allocate disjoint counter ranges to app servers to scale it horizontally. Hashing the long URL and taking the first seven base62 characters is idempotent, so the same URL can return the same short link, but collisions and hot-URL skew need handling with a conditional put and retry. Snowflake-style IDs combine a timestamp, a machine id, and a per-machine sequence to produce unique keys across nodes without coordination; a raw 64-bit Snowflake takes 11 base62 characters, so short codes either encode a truncated slice (for example the low 41 timestamp-ish bits, which fits in seven) or accept the longer key. Most production designs pick counter ranges or Snowflake and reserve hashing for deduplication. Whatever the generator, uniqueness must be enforced at write time by a conditional put, never assumed. Watch the animation as the counter is consumed, encoded, and committed exactly once.
Step 3: 301 versus 302 redirects
Redirect semantics decide both caching and analytics. A 301 Moved Permanently tells the browser to cache the redirect, so the second click never reaches your servers — superb for scale and latency, terrible for counting clicks because the origin is bypassed. A 302 Found or 307 Temporary Redirect is temporary, so browsers must ask again every time: every click hits your edge and API, exactly what click analytics and per-link counters need, at the cost of extra traffic. Most link shorteners choose 302 and reclaim the cost with an aggressive edge cache. If analytics do not matter, 301 plus a long Cache-Control turns the browser itself into your CDN. Watch the animation: with 301 the browser cache answers alone and no origin sees the click; with 302 the request returns to the origin and an analytics counter increments on every hop. Pick the status code from the product requirement, not by habit.
Step 4: Write path end to end
Now walk the write path end to end. The client POSTs the long URL to /shorten. The API service normalizes it — adding a missing scheme, rejecting javascript: and data: URLs, optionally stripping tracking parameters — then checks the custom alias, per-key rate limits, and abuse rules. It asks the ID generator for the next key, and the generator returns a base62 string from a pre-allocated counter range or a Snowflake ID. The service writes key to long URL plus metadata such as owner, creation time, and expiry into the KV store using a conditional put, so a race can never overwrite an existing mapping. Only after the store acknowledges does the API return 201 Created with the short link. The cache is deliberately left cold: it fills on first read, avoiding pollution from links that may never be clicked. The write path stays small — no joins, no fan-out, one durable put — which keeps a 100M-per-day workload affordable.
Step 5: Read path through cache
Reads dominate, so the read path decides the latency users feel. A click first hits the CDN or edge cache keyed by the short code; a hit returns a 302 immediately, with no origin traffic and sub-millisecond latency. On a miss the request reaches the API service, which checks a shared in-process or Redis cache before the KV store. Only a second miss reaches the store, and the value is written back into the cache with a TTL and LRU eviction so hot links stay resident. Caches in front of a KV store routinely absorb 95 percent or more of read traffic; the store then handles only cold keys and the long tail. Watch the animation trace the hit branch and the miss branch side by side: on a hit the store is never touched, and on a miss the backfill makes the next click cheap. Expired links should be cached negatively for a short TTL so attackers cannot hammer the store with dead keys.
Edge cases & traps
- Hash collisions in a hash-based generator silently overwrite a mapping: conditional-put the candidate key and retry with a salted input on conflict.
- Sequential base62 keys are guessable: shuffle the encoding alphabet, mix in a random salt, or add entropy — a plain Snowflake is time-ordered and unpredictable only while its sequence state stays secret.
- 301 responses bypass analytics entirely: use 302 or 307 when clicks must be counted, and reserve 301 for immutable links.
- Cache stampede on a viral link: add jittered TTLs and single-flight request coalescing so one miss cannot flood the KV store.
- Custom aliases and reserved words collide with generated keys: keep aliases in the same keyspace and reject reserved paths such as api, admin, and favicon.