Design a URL shortener
medium 45 minTurn a long URL into a short code and redirect anyone who opens it.
See it run
Every flow of the design, one hop at a time: creating a link, following it, making codes, caching and counting clicks.
Operations
Create a link (write path)
Designed for correctness over speed: validate, get a unique ID, encode it, store it only if absent, warm the cache.
Step 1 of 13
Client sends the URL
input
example.com/long/path
POST /api/v1/urls with the long URL and an optional alias and expiry. Why: it captures what the user wants before any work.
Step 1: Client sends the URL
def create(req): limiter.check(req.client) # 429 if over validate(req.long_url) # scheme, host, length safety.check(req.long_url) # blocklist, Safe Browsing n = ids.next() # from the local range code = req.alias or base62(scramble(n)) db.put_if_absent(code, req.long_url) # 409 if taken cache.set(code, req.long_url, ttl=DAY) return 201, f"https://sho.rt/{code}"- Latency
- 100-200 ms
- Load
- 1,150/s
- Peak (3x)
- 3,500/s
- Share of traffic
- about 1%
The conditional write is the only place uniqueness is enforced. Any earlier check is a hint for the user.
In the real world
The same url shortener doing real jobs. Pick one and step through it.
50,000 clicks a second on one code, at the moment its edge copy expires.
Step 1 of 4
All from the edge
origin
1 request a minute
The hot link is cached at the CDN and origin sees almost nothing.
Step 1: All from the edge
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Cache-Control: private on a response you want the CDN to cache
criticalprivateforbids shared caches from storing it, so the CDN hit rate is zero and the origin takes everything.WrongCache-Control: private, max-age=60RightCache-Control: public, max-age=0, s-maxage=60Calling sequential IDs unguessable
majorBase62 is not encryption. The code after 5ban is 5bao, so anyone can walk your links.
Wrongcode = base62(next_id())Right# reversible mix: gcd(MULT, 62**7) == 1code = base62(next_id() * MULT % 62**7).rjust(7, "0")Checking an alias, then inserting it
criticalTwo requests can both see it free and both insert. Only a conditional write decides.
Wrongif not db.get(alias): db.put(alias, url)Righttry: db.put_if_absent(alias, url)except AlreadyExists: return 409Adding up hourly unique visitors
majorSomeone who clicks in two hours is counted twice.
WrongSELECT sum(unique_visitors) FROM hourlyRightSELECT uniqMerge(visitors_state) FROM hourlyWaiting for analytics in the redirect
majorA slow analytics store then makes every link slow.
Wrongclickhouse.insert(event)return 302Rightproducer.send(event) # async, batchedreturn 302
Interview tips
Lead with numbers
- "100 to 1 reads, so caching is critical."
- 115K reads a second, 350K at peak; 1,150 writes.
- Seven base62 characters, 3.5 trillion codes.
Explain trade-offs
- 302 keeps control and analytics, 301 saves load.
- Ranges avoid collisions; hashing avoids a coordinator.
- Key-value store for links, relational for accounts.
Anticipate failures
- Redis down: circuit breaker, read the store.
- ZooKeeper down: IDs in memory for hours.
- Kafka down: buffer, spill to disk, replay.
End with extensions
- Custom domains, QR codes, webhooks.
- Password-protected links and A/B tests.
- Deep links for mobile apps.