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.7 301 or 302?
3 min read+10 XP
Both send the browser to the long URL. The difference is what happens on the second click.
Figure: with a 301 the browser may skip us next time. With a 302 every click comes through us.
| 301 Moved Permanently | 302 Found | |
|---|---|---|
| Browser may cache it by default | Yes | No (only if headers say so) |
| Second click comes to us | Often not | Yes |
| We can count every click | No | Yes |
| We can change or disable the link later | Hard (browsers remember) | Yes |
| Load on our servers | Lower | Higher |
Our pick: 302, because the requirements include click counts, and because we may need to disable a link later (for example, if it turns out to point to malware). If analytics weren't needed, 301 would cut our load.
Interviewer pushback:
- "What about 307 and 308?" → They're the same as 302 and 301 but promise the browser keeps the same method (a POST stays a POST). For simple link clicks, which are GETs, 302 and 301 are fine.
Memory code: "301 is remembered, 302 is reported."