Design a URL shortener
Map billions of long URLs to short codes and redirect in under 50ms, with reads vastly outnumbering writes.
Open the interactive version → diagrams, practice & moreThe problem
Map billions of long URLs to short codes and redirect in under 50ms, with reads vastly outnumbering writes.
The idea
A tiny write path (generate a unique code, store the mapping) plus a heavily-cached read path for redirects.
How it works
Generate codes via a counter→base62 or hashing (handle collisions). Store code→URL in a key-value/SQL store. Reads: app → cache → DB; the cache absorbs the 100:1 read skew. Click analytics fire-and-forget to a queue + workers so logging never slows redirects. CDN optional for landing pages.
The tradeoff
Counter-based IDs are dense but need coordination; hashing risks collisions. Cache staleness is fine (URLs rarely change).
In the wild
TinyURL, bit.ly. A favorite warm-up interview question.
Interview deep dive
Flow
- Create short code, store code to long URL mapping durably.
- Redirect path checks cache first, then database on miss.
- Return HTTP redirect without waiting for analytics.
- Analytics events go to a queue and workers aggregate later.
Watch for
- Do not put analytics on the redirect critical path.
- Hash collisions need a retry story.
- Custom aliases need uniqueness and abuse controls.
Interviewer trap
Lead with read/write ratio and latency target; that justifies cache-first redirects.