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.8 How do you keep redirects fast at 12,000 a second?
3 min read+10 XP
Cache-aside in Redis (Chapter 12), with these details:
- Key: the code. Value: the long URL. TTL: hours, since links almost never change; delete the key if a link is disabled.
- Size: about 33 GB for the hottest 20% (31.2), so one Redis node fits it; add a replica so a restart doesn't empty everything at once.
- Codes that don't exist: bots try random codes. Each miss would hit the database (cache penetration, Chapter 13). Cache "not found" for a short time too.
- A viral link: one key gets most of the traffic (hot key, Chapter 13). Add a tiny in-process cache on each app server for the top few hundred codes, with a short TTL.
Interviewer pushback:
- "Could a CDN serve redirects?" → Yes. A CDN can cache the redirect response at the edge if we allow it, which is fastest for users worldwide. The trade-off is the same as 301: cached redirects at the edge aren't counted by us unless the CDN reports them.
Memory code: "Cache the hits, cache the misses, guard the hot ones."