Design a URL Shortener
The classic opener. Deceptively simple, and a precise test of whether you scope, estimate, and pick an ID strategy for stated reasons.
#1. Requirements
Functional
- Given a long URL, return a short one.
- Visiting the short URL redirects to the original.
- Optional: custom aliases, expiration, click analytics.
Non-functional
- Read-heavy — redirects vastly outnumber creations.
- Redirect latency must be low (it's in the user's critical path, before the real page even starts loading).
- High availability — a dead shortener breaks every link ever shared.
- Short codes must not be predictable enough to enumerate.
Explicitly out of scope (say this): user accounts, spam/malware scanning, an analytics dashboard. Name them explicitly, so the boundaries of the design are on the record.
Clarifying questions worth asking:
- Traffic volume, and the read/write ratio?
- How long must links live? Forever, or can they expire?
- Custom aliases needed?
- Is analytics required, and does it need to be real-time?
#2. Estimation
Assume 100M new URLs/day, read:write of 100:1, 5-year retention.
Writes: 100M / 10⁵ s = 1,000 QPS avg → ~3,000 peak
Reads: 1,000 × 100 = 100,000 QPS avg → ~300,000 peak
Storage per record:
short_code 7 B long_url ~200 B (cap at 2048)
created_at 8 B user_id 8 B → ~250 B, round to 500 B
Per day: 100M × 500 B = 50 GB/day
5 years: 50 GB × 365 × 5 ≈ 91 TB
With replication (×3) ≈ 275 TB
Keyspace: 62⁷ = 3.5 × 10¹² → 100M/day for ~95 years ✓What the numbers decided:
- 91 TB rules out a single node → sharded store.
- 300K read QPS at ~500 B → tiny payloads, extremely cacheable → cache tier is the primary read path.
- 62⁷ confirms 7 characters is enough; no need for 8.
#3. API
POST /api/v1/urls
{ "long_url": "...", "custom_alias": null, "expires_at": null }
→ 201 { "short_url": "https://sho.rt/aB3xK9p" }
GET /{short_code}
→ 302 Found, Location: <long_url>#4. Data model
urls
├── short_code VARCHAR(7) PRIMARY KEY
├── long_url TEXT
├── user_id BIGINT
├── created_at TIMESTAMP
└── expires_at TIMESTAMP NULLA single-table key-value access pattern — short_code is the only lookup key. That's a strong argument for a key-value store (DynamoDB, Cassandra) over a relational database: no joins, no range scans, perfect partitioning on the primary key.
Shard on short_code by hash. It's high-cardinality, uniformly distributed by construction (the codes are essentially random), and present in every read.
#5. ID generation — the actual interesting part
Four approaches. Compare them; don't just pick one.
First, the encoding everything below uses: base62 just means writing a number using all ten digits plus both cases of the alphabet — 62 symbols instead of 10 — so a big number becomes a short string like bQ7kx2M.
A. Hash and truncate. Run the URL through a hash function, encode the result in base62, keep 7 characters. Problem: two different URLs producing the same short code (a collision) becomes likely far sooner than the size of the keyspace suggests — the same counter-intuitive maths as the birthday paradox, where 23 people already give even odds of a shared birthday. So before every insert you have to read the database to check the code isn't already taken, and retry with a different code if it is. Hashing also means the same long URL always produces the same short code, so two users shortening the same link get one shared code — which may or may not be what you want.
B. Counter + base62. A global counter, base62-encoded.
Problems: sequential codes are enumerable (anyone can walk aaaaaab, aaaaaac and read every link ever created — a genuine privacy leak), and a single counter is a coordination bottleneck.
C. Counter with range allocation (recommended). A coordination service hands out blocks (e.g. "you own 1,000,000–1,999,999"). Each application server allocates locally with zero coordination and requests a new block when low.
Then fix the guessability: don't turn the counter straight into a code. Scramble it first with a format-preserving encryption (FPE) — a cipher that maps each number in the range to exactly one other number in the same range. Because that mapping is one-to-one, two counters can never produce the same code — collisions are impossible by construction, with no check needed before writing — yet consecutive counters produce codes that look nothing alike.
counter 1,000,001 ──► FPE(key, n) ──► 2,847,193,554 ──► "bQ7kx2M"
bijective base62
✓ no collisions ever ✓ not enumerable ✓ no coordination per writeD. Pre-generated key pool. A background job generates random unused codes into an "available" table; servers claim batches. Simple and unguessable, but you now run two extra pieces: the generator job, and a claim step that guarantees two servers can never grab the same batch.
#6. High-level design
┌──────────┐
create ───────────►│ │──► ID service (block allocation)
│ Write │
│ Service │──► DB (sharded KV)
└──────────┘
┌─────┐ ┌───────┐ ┌──────────┐
redirect ──────►│ CDN │───►│ LB │───►│ Read │
└─────┘ └───────┘ │ Service │
└────┬─────┘
┌────────────┴────────────┐
▼ ▼
┌──────────┐ ┌──────────────┐
│ Redis │ miss ────► │ DB (sharded) │
│ cache │ ◄───fill── └──────────────┘
└──────────┘
│
└──► Kafka ──► analytics pipeline
(async, off the redirect path)Redirect path, narrated: request hits the LB → read service → Redis lookup by short_code → hit (~99%) returns 302 immediately, ~1 ms → miss falls through to the sharded database, populates the cache, returns. A click event is published asynchronously to Kafka; analytics never blocks the redirect.
#7. Deep dives
#The cache is the system
At 300K peak QPS with a 500-byte value, the hot working set is tiny.
Hot set: say 20% of the last 30 days of links
30 days × 100M = 3 × 10⁹ links; 20% = 600M
600M × 250 B ≈ 150 GB → ~5 Redis nodes at 32 GB
At a 99% hit rate the DB sees 3,000 QPS instead of 300,000.Use LRU (least recently used: when the cache is full, evict the entry nobody has asked for in the longest time) with a long TTL. Access is heavily skewed — a link shared on a popular account gets millions of hits in an hour, then nothing. That's ideal cache behaviour.
Guard the failure modes (caching):
- TTL jitter — add a small random amount to each expiry time, so thousands of keys cached at the same moment don't all expire at the same moment and hit the database together (an avalanche).
- Cache negative lookups briefly — remember "this code doesn't exist" too. Random 7-character probes are the obvious attack, and without this each one would go straight to the database (cache penetration).
- A circuit breaker — if the database starts failing or slowing, stop sending it traffic for a moment instead of piling on. Otherwise a cold (empty) cache, say after a restart, sends all 300K QPS to the database at once and takes it down.
#Scaling reads further
Put a CDN in front. A 302 with a short Cache-Control (say 60 s) lets the edge serve repeat hits on viral links entirely — the single biggest lever if a link goes viral, since one link can be 30% of your total traffic.
The tension: caching the redirect at the edge costs you per-click analytics precision for those requests. Resolve it by accepting sampled analytics for hot links, or by having the edge log asynchronously.
#Custom aliases
Must be globally unique, so this does need a uniqueness check — but the check is a single-shard insert with a unique constraint, not a lock. Let the insert fail and return 409. Reserve a blocklist (api, admin, login) and validate the character set.
#Expiration and deletion
A expires_at column plus lazy deletion: check on read, and run a background job to reclaim. Don't scan the whole table — index on expires_at, or partition by expiry month so cleanup is a partition drop (deleting one month's whole partition in a single cheap operation instead of row by row).
#Analytics
Never write to a counter on the redirect path — a viral link would create a single hot row taking 50K writes/s. Instead: publish click events to Kafka, aggregate in a stream processor, and store rollups in a columnar store. Approximate uniques via HyperLogLog.
#8. Failure modes & follow-ups
| Failure | Behaviour |
|---|---|
| Cache node dies | Consistent hashing limits loss to 1/N of keys; those fall through to the DB. Circuit breaker if the DB saturates. |
| DB shard dies | Replica promoted; that shard's links are briefly unavailable — bounded blast radius, not total outage. |
| ID service down | Servers keep allocating from their current block. Only blocks the creation path once exhausted, and never blocks redirects. |
| Kafka down | Analytics events dropped or buffered locally. Redirects unaffected — the whole point of keeping it async. |
Common follow-ups and the one-line answers:
- "How do you handle a viral link?" — it's a cache hit by definition, and the CDN absorbs it. The remaining risk is a hot key: every request for that one link lands on the single Redis node that holds it. Fix it by copying that key to several nodes, or by caching it in each read server's own memory (a local cache) so most requests never reach Redis.
- "How do you stop malicious URLs?" — asynchronous scanning against a reputation service, plus the ability to disable a code (which is why 302 over 301 matters).
- "Multi-region?" — links are immutable once created, so replicate the table asynchronously everywhere and serve reads locally. Creation can route to a home region. Immutability makes this one of the easiest systems to distribute globally — worth pointing out.
- "Can you make it cheaper?" — 301 redirects push traffic to browsers entirely, at the cost of analytics and revocability.
#Check yourself
What do the URL shortener's numbers decide?Show answer
301 versus 302 for a shortener?Show answer
Why is hash-and-truncate a weak ID strategy?Show answer
What ID strategy is recommended, and why?Show answer
Why use a key-value store sharded by hash of short_code?Show answer
Name the cache's three guards.Show answer
Why never count clicks on the redirect path?Show answer
Why is a shortener easy to run in many regions?Show answer
#What to carry forward
- Drive the easy question: a working design in ten minutes, then go deep on IDs or the read path.
- The numbers decide: shard for storage, cache for reads, seven characters for the keyspace.
- Range-allocated counters plus format-preserving encryption: no collisions, no enumeration, no coordination.
- 302 keeps analytics and revocability; 301 trades them for load.
- Keep analytics asynchronous and off the redirect path.