Design a URL shortener
A small product with a 100-to-1 read-heavy workload. The interesting parts are generating short codes without collisions and keeping redirects fast.
The problem
Around 2002, people shared links by pasting them into emails and forum posts, and long URLs kept breaking: mail clients wrapped them across lines and the link stopped working. TinyURL launched to fix exactly that. A few years later Twitter’s 140-character limit made short links a necessity, and services such as Bitly turned them into a product with click analytics.
The system looks trivial: store a mapping, look it up. That is why it is a popular interview question. The interviewer can see quickly whether you ask about scale before designing, whether you notice that reads dominate, and whether you can generate unique short codes across many servers without a bottleneck.
Requirements
Functional
- Given a long URL, return a short URL.
- Given a short URL, redirect to the long URL.
- Optional custom alias chosen by the user.
- Optional expiry time.
- Click counts per link (basic analytics).
Out of scope unless asked: user accounts and billing, link editing, QR codes, a full analytics dashboard.
Non-functional
- Redirect latency: p99 under 100 ms at the server. A redirect delays someone’s page load, so it must be quick.
- Availability: 99.99% for redirects. A broken short link is a broken link everywhere it was shared. Creation can tolerate slightly less.
- Durability: a link, once issued, must never be lost or point somewhere else.
- Scale: 100 million new links a month.
- Codes should not be trivially guessable in sequence.
Capacity estimates
| Quantity | Working | Result |
|---|---|---|
| Writes | 100M per month / 2.6M seconds | about 40 per second |
| Redirects | 100 reads per write | about 4,000 per second average |
| Peak redirects | 4x to 5x average | about 20,000 per second |
| Links in 5 years | 100M x 60 months | 6 billion |
| Storage | 6B x 500 bytes | about 3 TB |
| Cache for the hot set | 20% of one day’s distinct links, 500 bytes each | a few GB |
Two conclusions drive the design. The write rate is tiny, so almost any database can absorb it. The read rate is moderate and highly skewed towards recent and popular links, so a small cache will absorb most of it.
API
POST /v1/urls
Authorization: Bearer <token>
Idempotency-Key: 7f3c...
{ "long_url": "https://example.com/a/very/long/path", "alias": "launch", "expires_at": "2027-01-01T00:00:00Z" }
201 Created
{ "code": "launch", "short_url": "https://sho.rt/launch", "long_url": "...", "expires_at": "..." }
GET /{code}
302 Found
Location: https://example.com/a/very/long/path
A missing or expired code returns 404 (or 410 Gone for expired links, if you want clients to tell the difference). A taken alias returns 409 Conflict. Creation is rate limited per account, and the idempotency key lets a client retry a timed-out request without creating two links.
Data model
One table, keyed by the short code:
| Column | Type | Notes |
|---|---|---|
code |
string, primary key | 7 base-62 characters, or a custom alias |
long_url |
string | up to about 2,000 characters |
owner_id |
string | for listing and quotas |
created_at |
timestamp | |
expires_at |
timestamp, nullable | drives TTL deletion |
Every hot-path query is “get by primary key”, with no joins and no range scans. A key-value store such as DynamoDB or Cassandra fits well and scales horizontally by hashing the code. A sharded relational database works equally well at 3 TB, and is a reasonable choice if the team already runs one.
“List my links” is a second access pattern: a secondary index on owner_id, created_at, or a separate table written alongside the first.
High-level architecture
Redirect (read path). The load balancer sends GET /{code} to a stateless redirect service. It looks the code up in Redis. On a hit it returns the 302 straight away. On a miss it reads the URL store, writes the result to Redis with a TTL, and responds. Either way it puts a click event on a stream and does not wait for it.
Shorten (write path). The Shorten API validates the URL, takes the next ID from its in-memory range, encodes it, and writes the row with a conditional “put if absent”. When its range runs out it leases another from the allocator.
Analytics. Workers consume the click stream, aggregate counts per link per minute, and write them to an analytics store. This path can fall behind or fail without affecting redirects.
Deep dives
Generating short codes
There are three common approaches.
Hash the long URL. Take MD5 or SHA-256 of the URL and keep the first 7 base-62 characters. The same URL always yields the same code, which removes duplicates but also means two users cannot have separate links, with separate analytics, to the same target. Truncating a hash causes collisions well before the space is full (the birthday bound for 627 is around two million entries for a 50% chance of at least one), so every write needs a check and a retry.
Random code. Generate 7 random characters and write with put-if-absent, retrying on the rare collision. It is simple, needs no coordination and the codes are unguessable. The collision rate grows as the space fills, but at 6 billion out of 3.5 trillion it stays under 0.2%.
Counter, encoded in base 62. A global counter guarantees uniqueness with no check. The naive version, one database sequence hit on every write, is a bottleneck and a single point of failure. The standard fix is range leasing: each API server asks the allocator for a block of, say, one million IDs and serves them from memory. The allocator is a row in a strongly consistent store (or ZooKeeper or etcd) that is touched once per million writes. If a server dies, its unused IDs are skipped.
Sequential counters are guessable: if your link is abc123, someone can try abc124. To prevent that, scramble the counter with a reversible function before encoding, so consecutive IDs produce unrelated-looking codes while uniqueness is preserved.
I would choose counter ranges with a scramble: writes never collide and need no read-before-write. Random codes are a perfectly good answer too, and simpler.
Custom aliases live in the same table. Write with put-if-absent and return 409 if the alias is taken. Reserve a namespace so generated codes and aliases cannot collide, for example by making generated codes exactly 7 characters and requiring aliases to be a different length.
Keeping redirects fast
At peak the service handles about 20,000 redirects per second and the traffic is skewed: a small share of links receives most of the clicks.
- Cache-aside with Redis. A few gigabytes holds the hot set. With a hit rate above 90%, the store sees under 2,000 reads per second at peak.
- TTL and expiry. Cache entries carry a TTL no longer than the link’s remaining life, so an expired link cannot be served from cache.
- Negative caching. Scanners request random codes. Cache “not found” for a short time so those requests do not each hit the store.
- 301 or 302. A
301tells browsers to remember the redirect, which removes repeat traffic but also removes your ability to count clicks, expire the link or take down a malicious target. A302keeps you in the path. - Edge caching. If analytics allow it, a CDN can cache the redirect response for a short time and report hits through its logs.
Analytics without slowing redirects
The redirect service emits {code, timestamp, country, referrer} to a stream such as Kafka and returns. If the stream is unavailable the event is dropped or buffered briefly in memory; the redirect still succeeds. Workers aggregate per link per minute and write to a store built for counts over time. Counts are therefore eventually consistent, a few seconds behind, which is fine for a dashboard.
Bottlenecks and failure modes
- Cache lost or cold. All reads fall to the store at once. Mitigate by sizing the store for the uncached peak for a short period, coalescing concurrent misses on the same code, and running Redis with replicas.
- Allocator down. Servers keep working until their current range is used up, which at 40 writes per second across the fleet is hours for a block of a million. Run the allocator on a replicated, consistent store.
- Store replica lag. A link created a moment ago may miss on a replica. Read your own writes by populating the cache at creation time.
- A single viral link. One key gets a large share of traffic. It is served from cache, and a small in-process cache on each redirect server removes even the Redis hop.
- Abuse. Short links hide phishing targets. Check new URLs against a blocklist, rate limit creation, and keep the ability to disable a code quickly, which is another reason to prefer
302.
Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Code generation | Counter ranges plus scramble | Random with collision check | No read-before-write; slightly more moving parts |
| Storage | Key-value store | Sharded SQL | Access is by primary key only; SQL is fine at this size |
| Redirect status | 302 | 301 | Keeps analytics and control; costs repeat traffic |
| Analytics | Asynchronous stream | Synchronous counter update | Redirect latency is independent of analytics health; counts lag by seconds |
| Consistency | Eventual on replicas, cache filled on write | Strong reads everywhere | Availability of redirects matters more than instant global visibility |
45-minute interview script
A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.
- 0:00 to 5:00
Requirements 5 min
Confirm the two core operations (shorten, redirect). Ask about custom aliases, expiry, analytics and who the users are. State the non-functional targets out loud and write them on the board.
- 5:00 to 9:00
Capacity estimates 4 min
Derive writes per second, redirects per second and five-year storage. Say the conclusion, which is that this is read-heavy and fits comfortably in a few terabytes.
- 9:00 to 13:00
API 4 min
Two endpoints. Mention authentication for creation, the status code for redirects, and idempotency for retries.
- 13:00 to 17:00
Data model 4 min
One table keyed by code. Explain why a key-value store fits and what the second access pattern (list my links) needs.
- 17:00 to 25:00
High-level design 8 min
Draw the read path first because it carries the traffic, then the write path, then the asynchronous analytics path. Narrate one redirect and one shorten end to end.
- 25:00 to 33:00
Deep dive: generating codes 8 min
Compare hashing the URL, random codes and counter ranges. Pick one and defend it. Cover custom aliases and predictability.
- 33:00 to 39:00
Deep dive: the redirect path 6 min
Cache sizing and hit rate, 301 against 302, negative caching, what happens when the cache is cold.
- 39:00 to 43:00
Failure modes and trade-offs 4 min
Walk through losing the cache, the allocator and a store replica. Mention abuse and hot links.
- 43:00 to 45:00
Wrap-up 2 min
Summarise the design in three sentences and name what you would build next with more time.
Key takeaways
- Redirects outnumber writes by about 100 to 1, so design and draw the read path first.
- Seven base-62 characters give 3.5 trillion codes, far more than the 6 billion needed over five years.
- Counter ranges leased to each API server give unique codes with no collision check on the write path.
- A 302 keeps every click visible to you; a 301 lets browsers skip you. Choose based on whether analytics matter.
- Analytics are written asynchronously through a stream, so a slow analytics pipeline can never slow a redirect.
Try it
Check yourself
0 of 4 answered
Flashcards
These 5 cards are in your review deck. Tap a card to see the answer.
What is the read-to-write ratio you would assume for a URL shortener, and why does it matter?
Around 100 to 1. It means the redirect path dominates cost and latency, so you cache aggressively and optimise reads first.
Three ways to generate a short code?
Hash the long URL and truncate (collisions, same URL gives same code), random string with a put-if-absent check, or a unique counter encoded in base 62 (no collisions, needs coordination).
301 or 302 for redirects?
301 is cached by browsers, which cuts load but hides repeat clicks. 302 is not cached, so you see every click and can change or disable the target. Analytics-driven products use 302.
How do counter ranges avoid a central bottleneck?
Each API server leases a large block (say a million IDs) in one call, then hands them out from memory. The allocator is contacted once per block, not once per request.
How do you stop sequential codes being guessable?
Pass the counter through a reversible scramble (for example a Feistel network or multiplication by a large odd constant modulo the code space) before base-62 encoding.