Design a URL Shortener
Designing a URL shortener like bit.ly is the most common first system design question. It covers ID generation, a read-heavy cache, database choice, redirects and analytics in one small problem.
What you will learn
- Generate short, unique codes
- Design for a 100:1 read-to-write ratio
- Choose 301 vs 302 redirects
- Add click analytics without slowing redirects
Key concepts
Base62 code
Encode a unique number with [0-9a-zA-Z]. 7 characters give 62^7 ≈ 3.5 trillion codes.
ID generation
Options: a database sequence encoded in base62 (simple, predictable), ranges of ids handed to each server (no coordination per request), Snowflake-style ids, or random codes with a uniqueness check.
301 vs 302
301 is permanent, so browsers cache it and later clicks never reach you: fast, but no analytics. 302/307 is temporary, every click hits you, so you can count it.
Step by step
Design
- API: POST /links { url, customAlias?, expiresAt? } → { code }; GET /{code} → 302
- Table links(code PK, url, user_id, created_at, expires_at)
- Redirect path: CDN/edge → cache (Redis, code → url) → database on a miss
- Clicks: push an event to a queue, aggregate asynchronously into a stats store
- Scale: key-value or sharded SQL by code; replicas for reads; cache hit rate above 90%
Examples
Base62 encoding
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
export function toBase62(n) {
let s = ''
do { s = ALPHABET[n % 62n] + s; n /= 62n } while (n > 0n)
return s
}
toBase62(125000000000n) // '2crtgcg'Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Handle custom aliases and collisions.
- Add expiry and explain how to clean up expired links.
- Explain how to stop the service being used for phishing links.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
Why not just hash the URL?
A truncated hash (MD5 → 7 chars) can collide, so you still need a uniqueness check and retry, and the same URL always gets the same code, which may not be wanted per user. A counter or pre-allocated id ranges avoid collisions entirely.
How do you keep redirects fast globally?
Cache code → URL at the CDN edge or in a regional Redis, keep the redirect handler tiny, send analytics asynchronously, and replicate the read store to several regions.
Summary
Unique numeric ids encoded in base62, a cache-first redirect path, 302 when you need analytics, analytics through a queue, and sharding by code when data grows.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus