Skip to content
SD-1 · Back to the write-up

Design a URL Shortener

Hand out unique 7-character keys, store key → URL, and serve the flood of redirects from a cache.

Follow a request

Clients
Edge
Services
Data
UserBrowser or app
Load balancerSpreads traffic
App serversStateless, many
Key serviceID blocks
Click queueAsync events
CacheHot keys, Redis
Database16 shards × 3
AnalyticsClick counts
1user → lb · GET /x7Kp2QaSomeone opens the short link.1 / 7

The numbers, at a glance

For every link created……it is opened about 100 times
1 write ≈ 40/s99 reads ≈ 4,000/s
Storage grows slowly6 billion links × 500 bytes
7 characters is plenty62⁷ ≈ 3.5 trillion possible keys
That thin line is everything we will ever need.

A redirect, in order

Cache miss shown. On a hit, step 4 returns the long URL and steps 5 to 7 disappear.

User
Load balancer
App server
Cache
Database
Click queue
1 GET /x7Kp2Qa
2 route
3 GET key
4 miss
5 SELECT by key
6 long URL
7 SET key
8 click event
9 302
10 302 → long URL
RequestResponseAsync, does not block

Three ways to make keys

The decision interviewers care about most.

Hash the URL
Workable
https://very.long/url…
md5 → a9f3K2x8…
take 7 → a9f3K2x
exists? retry
+ No coordination needed.− Collisions mean a check and retry on every write.
One global counter
Too fragile
server Aserver Bserver C
counter++ bottleneck
125000001 → 8sud3
+ Simple; never collides.− Every write waits on one machine; keys are guessable.
Pre-allocated ID blocks
Our pick
Key service
A: 1000–1999B: 2000–2999
1042 → shuffle → base62
"x7Kp2Qa"
+ No collisions and no per-request coordination.− A crashed server wastes its unused block. Harmless.

How it grows

Add a box only when a number forces you to. Highlighted boxes are new at each stage.

Stage 1 · ~4,000 req/sMake it work
User
App server
SQL database
One server and one database cope with the average, but not the peak.
Stage 2 · ~40,000 req/sScale out
User
Load balancer
Key serviceApp × 6Click queue
CacheDB + 2 replicasAnalytics
Spread the peak over many servers, give them collision-free ID blocks, cache hot keys and move click counting to a queue.
Stage 3 · 400,000 req/sScale to billions
User
Load balancer
Key serviceApp × 58Click queue
Cache × 516 shards × 3Analytics
Shard the database by key and grow the cache to 5 nodes.
Was this walkthrough useful?Your vote tells us what to improve next.