Design a URL shortener
medium 45 minTurn a long URL into a short code and redirect anyone who opens it.
Grow the design
Start with the smallest system that works. Change it only when something breaks.
Version by version
From one box to the full system
Seven versions
Version 1: One service, one database
Forced by: The features: create a link and follow it.
- What changes
- The service takes the next number from a database sequence, encodes it in base62, stores code and URL, and answers 302 on lookup. The code is the primary key.
- What it costs
- Almost nothing. One thing to run. Add a standby, because links must not be lost.
- What breaks next
- Reads. A well-tuned machine does tens of thousands of simple lookups a second; we expect 115,000. At a few thousand reads a second, stop here.
Say: Let me get create and redirect working with one database, then see which target it misses.
Architecture
High-level design
The whole system
Four tiers
- 1
Edge
A CDN with hundreds of locations serves popular redirects in 5 to 20 ms. GeoDNS sends users to the nearest region.
- 2
Gateway
Load balancer, firewall (WAF), sliding-window rate limiter and token checks for management endpoints. It routes
POST /api/v1/urls,GET /{code}andGET .../stats. - 3
Services
URL service (validate, ID, encode, store), redirect service (the hot path), analytics service, user service. All stateless, so you scale by adding instances.
- 4
Data
Redis for hot links, DynamoDB or Cassandra for mappings, PostgreSQL for accounts, Kafka for clicks, ClickHouse for statistics. External: GeoIP, Safe Browsing, QR generator, webhooks.
Why these components?
CDN edge
Keeps popular redirects near users and cuts origin load by about 65%.
Redis
Memory lookups in about a millisecond. With the CDN it absorbs 95% of redirects.
DynamoDB
Key-value lookups in single-digit milliseconds at any size. Partitioned by code.
ZooKeeper
Hands out ID ranges, which makes codes globally unique.
Kafka
Decouples analytics: a click is fire and forget.
ClickHouse
Columnar storage for fast aggregates over billions of rows.
Flows
The three flows
Flow 1: create a link
Flow 2: follow a link (hot path)
Flow 3: read statistics