Lesson 6.1 · 25 min
URL shortener
Size a shortener from three sliders, generate codes four ways and see the collision math, then cache a Zipf-skewed read path and choose 301 or 302.
The idea in plain words
A URL shortener swaps a long web address for a short code, like a coat-check ticket: hand in the ticket and you get the coat back. The service mostly answers “which link is this code?”, billions of times.
The problem it solves
Long links are awkward to share. A shortener gives each one a short code and redirects anyone who opens it, billions of times, quickly and without ever sending people to the wrong place.
How it works
- To create: generate a unique short code and store code → long URL.
- To open: look up the code and reply with a redirect to the long URL.
- Reads vastly outnumber writes, so cache popular codes in memory.
- Generate codes so two links can never get the same one: counters, or random codes inserted only if unused.
Example
7 characters from a–z, A–Z and 0–9 give 62⁷ ≈ 3.5 trillion codes. At 100 million new links a month that lasts thousands of years. With 100 clicks per link, the redirect path handles about 4,000 requests per second, mostly from cache.
Key terms
- Short code
- The few characters after the domain, such as aZ3k9Qx.
- Redirect
- The server telling the browser to go to the long URL instead.
- 301 vs 302
- 301 means moved permanently (browsers may cache it); 302 means temporary (every click comes back to you).
- Base62
- Writing numbers with 0–9, a–z and A–Z, so 7 characters give about 3.5 trillion codes.
- Collision
- Two different links getting the same code.
In this lesson you'll learn
- How to turn requirements into numbers: rates, storage and code length.
- How counters, random codes and hashes generate unique short codes, with the collision math.
- How caching and 301 vs 302 shape the redirect path, and how to defend the whole design.
Sections
- Requirements and numbers
- API and data
- Architecture
- Short codes
- Read path
- Design review
Cheat sheet
| Code length | smallest L with 62^L ≫ links |
|---|---|
| Unique codes | leased counter ranges |
| Random codes | put-if-absent; collide n/N |
| Hot links | Zipf: tiny cache, high hit ratio |
| 302 vs 301 | analytics/edits vs offload |
The interactive simulations and the scored design review load with JavaScript.