System Design Interview Question: Design a URL Shortener
A classic warm-up question that touches ID generation, read-heavy scaling and caching.
Requirements
- Create a short URL for a long URL; optionally a custom alias and expiry.
- Redirect quickly (under ~50 ms), very high availability.
- Scale: ~100M new links per month, reads ~100x writes.
Generating short codes
Base62 (a-z, A-Z, 0-9) with 7 characters gives 62^7 ≈ 3.5 trillion codes, which is plenty.
- Counter + base62: take a unique number and encode it. No collisions. To avoid one global counter, give each server a block of IDs (range allocation) or use a Snowflake-style ID generator. Codes are guessable; add an offset or shuffle if that matters.
- Random codes: generate 7 random characters and insert with a unique constraint; retry on the rare collision.
- Hash of the URL (truncated): same URL gives the same code, but collisions must be handled.
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function toBase62(n) {
let s = '';
do { s = ALPHABET[n % 62] + s; n = Math.floor(n / 62); } while (n > 0);
return s;
}
Storage
A simple key-value access pattern: short_code -> long_url. A relational database works at moderate scale; a distributed key-value store (DynamoDB, Cassandra) scales writes and storage horizontally. Shard by short code if needed.
The redirect path
GET /aZ3kP9xhits a stateless service behind a load balancer.- Check a cache (Redis): popular links are served from memory.
- On a miss, read the database and populate the cache.
- Respond with a redirect.
301 vs 302: 301 (permanent) lets browsers cache the redirect, reducing load but hiding repeat clicks from analytics. 302 keeps every click visible to you.
Extras worth mentioning
- Analytics: publish click events to a queue and aggregate asynchronously, so redirects stay fast.
- Abuse: scan long URLs against malware/phishing lists; rate-limit creation.
- Expiry: TTL in the cache and a background cleanup job.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.