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.9 How do you count clicks without slowing redirects?
3 min read+10 XP
Writing a counter to the database on every redirect would add a write to the hottest path. Instead:
- The app server publishes a small click event (
code,time) to a queue and returns the redirect immediately (Chapter 22). - Analytics workers read events in batches and add them up per code per hour.
- They write the totals to an analytics store. The stats API reads from there.
Counts lag by seconds or minutes, which the requirements allow. Most queues deliver at least once, so after a worker crash a few events may be counted twice. For "nice to have" counts that's acceptable; if counts were billed, each event would carry an ID and workers would ignore duplicates (Chapter 22, idempotent consumers).
Memory code: "Redirect now, count later."