31. Design a URL Shortener
1
The interview prompt2
31.1 What do you ask first?3
31.2 How big is this, really?4
31.3 What are the doors?5
31.4 What do we store?6
31.5 What does the whole system look like?7
31.6 How do you generate the short code?8
31.7 301 or 302?9
31.8 How do you keep redirects fast at 12,000 a second?10
31.9 How do you count clicks without slowing redirects?11
31.10 What would you say in the last five minutes?12
Score yourself13
Variations to practise14
Sources15
Code lab31. Design a URL Shortener
31.2 How big is this, really?
3 min read+10 XP
Step 2: Estimates (5 minutes)
Using Chapter 2's moves (times, divide, times) on the agreed numbers. Assume about 500 bytes per stored link and 5 years of links.
| What | Working | Result |
|---|---|---|
| New links a second | 100 million ÷ 2.6 million seconds in a month | ≈ 40 a second |
| Redirects a second | 40 × 100 | ≈ 4,000 a second average |
| Peak redirects | 4,000 × 3 (assumed peak factor) | ≈ 12,000 a second |
| Links in 5 years | 100 million × 12 × 5 | 6 billion |
| Storage | 6 billion × 500 bytes | ≈ 3 TB |
| Code length | base62: 62⁶ ≈ 56.8 billion > 6 billion | 6 characters is enough; 7 gives room to spare (3.5 trillion) |
| Cache for hot links | redirects a day ≈ 333 million × 500 bytes × 20% hot | ≈ 33 GB, fits in one Redis node's memory |
What the numbers say, out loud:
- "40 writes a second is small. One database handles that. Writes aren't the hard part."
- "12,000 reads a second at peak is where the effort goes: caching."
- "3 TB fits comfortably on one database server, with replicas for safety. No sharding needed on day one."
Interviewer pushback:
- "What if a link goes viral and gets a million clicks in a minute?" → That's a hot key (Chapter 13). The cache handles most of it; for extreme cases I'd add a small in-memory cache on each app server, or let a CDN cache the redirect.
- "Why 7 characters if 6 is enough?" → Headroom. If our estimate is off or the product grows, 7 characters gives about 60 times more codes for one extra character.
Memory code: "Writes are tiny, reads are the job." The numbers tell you where to spend the next 30 minutes.