Design a URL shortener
Model answer
Requirements. Create a short link for a long URL, redirect quickly, optionally allow custom aliases and expiry. Reads far outnumber writes, so assume a heavy read ratio, such as 100 to 1.
API. POST /links with the long URL returns a short code. GET /{code} responds with an HTTP 301 or 302 redirect. A 302 lets you count every click, while a 301 can be cached by browsers.
Generating codes. Use a base62 string of 7 characters, which gives about 3.5 trillion combinations. Options: encode a unique counter or ID from a distributed generator (no collisions, but codes are guessable unless shuffled), or hash plus collision check.
Storage. A key-value store keyed by code, with the long URL, owner, created time and expiry. It scales horizontally by sharding on the code.
Read path. Put a cache (for example Redis) and a CDN in front, since hot links dominate the traffic.
Extras. Rate limiting, abuse and malware checks, and an asynchronous analytics pipeline for click counts.
Key points
- Read-heavy workload: cache and CDN on the redirect path
- Base62 codes of 7 characters give about 3.5 trillion combinations
- Key-value store sharded by code
- 301 vs 302 trades caching for click analytics
Likely follow-ups
- How do you generate unique codes across many servers without collisions?
- How would you handle expired links and abuse?
Common mistakes
- Using a truncated hash without checking collisions
- Ignoring the read-heavy pattern and not caching