09. Whole Systems / Lesson 2 of 4
Design a URL Shortener
Turn long links into short codes, and redirect billions of clicks fast.
- 14 min
- Intermediate
- 12 steps
- Redirect time—
- Store lookups/s—
- Short codes—
- Links kept—
- Request
- Response
- Cache hit
- Cache miss
- Write
- Health check
- Abuse
- Failed request
Step 1 of 12: Make long links short
Read every step as text
Step 1: Make long links short
Someone pastes
https://example.com/products/shoes/running?color=blue&size=42and gets backsho.rt/4c92. When anyone opens the short link, they land on the long one.Two operations only: create a short link, and redirect one. Reads (redirects) will far outnumber writes. We ask: how many links, how fast, how long are they kept?
Requirements: unique short codes, fast redirects, links never silently change, and click counts.
Step 2: Napkin math: users to servers
Say 100,000,000 new links a month. A month is 2,592,000 seconds, so that is about 39 writes a second. If each link is opened 100 times, reads are 3,900 a second, and a peak of 3 times is 11,700 a second.
Keep links 5 years: 100,000,000 × 12 × 5 = 6 billion rows. At 500 bytes a row that is 3 TB. One database handles about 5,000 simple reads a second, so the peak is already more than twice what it can do.
The read peak, not the storage, is the first problem.
Step 3: The simplest version: one service, one table
One service and one table:
links(code, long_url). Create inserts a row; redirect looks the code up and answers with the long URL.A redirect costs 10 ms of work plus 5 ms for the read: 15.0 ms. That is fine. But at the peak, 11,700 lookups a second hit a database that handles 5,000.
It works on a laptop and fails at the first busy hour.
Step 4: Idea one: hash the long URL
A hash such as MD5 turns any URL into a fixed string. Keep the first 7 hex characters as the code. The same URL always gives the same code, which is neat. But 7 hex characters give only 16^7 = 268,435,456 codes, fewer than the 6 billion links we need.
Worse, two URLs can get the same code (a collision). By the birthday effect, the first collision is likely after only about 21,000 links. Each insert would need a check and a retry.
A truncated hash is short, but it is not unique. Collisions arrive much sooner than people expect.
Step 5: Idea two: a counter written in base62
Give every new link the next number, then write the number in base62 (digits, a–z and A–Z). Number 1,000,000 becomes
4c92. No collisions are possible: every number is used once.With 7 characters there are 62^7 = 3.5 trillion codes, and we need 6 billion: about 0.17% of them. For many servers, a counter service hands each server a block of numbers (see the unique ID lesson).
7 characters is short, never collides, and has room for a thousand times more links.
Step 6: A counter is easy to guess
If the codes go
4c92,4c93,4c94, a stranger can try the next one and read everyone's links, including private ones. The order also tells people how many links you have.Fix: mix the number with a reversible scramble (a secret permutation or a block cipher) before base62, so the codes look random yet stay unique. Or draw a random code and retry if it already exists, which is rare while only 0.17% of the space is used.
Unique is not the same as unguessable. Do not depend on a secret code alone for private data.
Step 7: Cache the popular links
A few links are opened millions of times; most almost never. A cache in front of the store answers popular codes from memory. At a 90% hit rate only 9.999999999999998% of lookups reach the store: 11,700 × 0.1 = 1,170 a second, under the 5,000 limit.
Redirects get faster too: 10 + 0.9 × 1 + 0.1 × (1 + 5) = 11.5 ms. A link's long URL almost never changes, so cached copies can live long.
Read-heavy and rarely changed is the best case for a cache.
Step 8: 301 or 302: who remembers the redirect?
A 301 (moved permanently) lets the browser remember the answer, so repeat visits skip us. That is fast and cheap, but we never see those clicks. A 302 (found, temporary) makes every click come to us, so we can count it, and change where a link points later.
Most shorteners use 302 (or 307) because click counts are worth the extra traffic. If you only want speed and never count, 301 saves load.
Browsers may cache a 301 for a very long time, so a wrong target is hard to fix later.
Step 9: Storing 6 billion links
3 TB is too much for one comfortable machine, and it is only ever looked up by code, with no joins. So split the rows over shards by the code (see sharding and consistent hashing). Here, 3 shards hold about 1 TB each.
The lookups spread out too: 1,170 a second over 3 shards is about 390 each. A key-value store is a natural fit: the code is the key, the long URL the value. Each shard also keeps replicas for safety.
Shard by the code: a random code spreads the rows evenly.
Step 10: Count clicks without slowing the redirect
Every redirect makes a click event. Updating a counter row for each click would put 3,900 extra writes a second on the store. Instead the service drops an event on a queue and answers at once; a worker adds them up in batches and writes totals to a click log.
The redirect never waits for counting. If the worker is slow or down, events wait in the queue, and the numbers catch up later.
Move work that the user does not wait for out of the request, onto a queue.
Step 11: Spam, malware and floods
A short link hides where it goes, so it is a favourite of spammers. Check each new long URL against a list of bad sites (a link checker), and rate limit creation per person so a script cannot make a million links.
Also validate the input (only http and https, a length limit) and let people report bad links, which you can switch off quickly. The redirect path stays untouched and fast.
Abuse protection belongs on the create path, which has only about 39 writes a second, not on the busy read path.
Step 12: The URL shortener in one picture
100,000,000 links a month means 39 writes and 11,700 reads a second at peak. A scrambled base62 counter gives 3.5 trillion unique codes; a cache cuts store lookups to 1,170 a second and redirects to 11.5 ms.
Shards hold the 3 TB, a queue counts clicks off the hot path, and a checker and rate limit stop abuse.