System design · Read-heavy scaling, caching
How to design a URL shortener
A URL shortener (bit.ly, TinyURL) turns a long link into a short code and redirects anyone who opens it. It is the most common warm-up question in a system design interview because it looks trivial and hides every read-heavy scaling lesson: one write, thousands of reads, and every redirect has to be fast.
Updated · 5 min read
The short version
- Reads dominate. At 100 million new links a month that is about 40 writes and 4,000 redirects a second, around 15,000 at peak.
- Encode a unique ID as 7 base62 characters: about 3.5 trillion codes and no collisions by construction.
- Store code to URL in a key-value store sharded by code, and serve redirects from an in-memory cache.
- 301 lets browsers cache the redirect; 302 sends every click back to you. Pick on purpose.
- Count clicks through a queue so analytics can never slow a redirect.
Run it: click the fixes, watch the numbers
Scroll the diagram to see every component at a readable size.
- p99 latency
- 5,896ms
- Errors
- 35.2%
- Cost
- $610/mo
The database's 1 read replica can serve 1,000 reads/s but is receiving 2,057. 35% of requests fail. A cache in front of it would absorb most of those reads.
Embed this simulation in your blog, docs or course
Free to embed. Paste this HTML anywhere that accepts an iframe.
Clarifying questions to ask first
- How many new links a month, and how long do we keep them? (Assume 100 million a month, kept for 5 years.)
- How many times is each link opened? (Assume about 100 redirects for every new link, so reads dominate.)
- Do users need custom aliases and expiry dates? (Assume yes, both optional.)
- Do we need click analytics? (Assume counts per link, but they must never slow a redirect.)
- Can links be private? (Assume some are, so codes must not be guessable in sequence.)
Numbers that shape the design
| Quantity | Assumption | Result |
|---|---|---|
| New links | 100 million per month | ≈ 40 writes/s on average |
| Redirects | 100 reads per write | ≈ 4,000 reads/s average, ≈ 15,000/s at peak |
| Storage per link | ≈ 500 bytes (code, URL, metadata) | 100M × 12 × 5 years × 500 B ≈ 3 TB |
| Code space | 7 characters of base62 | 62⁷ ≈ 3.5 trillion codes |
The write path barely matters. Reads are 100 times larger and bursty, so the design is about serving redirects cheaply: aim for a p99 under 50ms at the server.
API
Keep the redirect endpoint at the root so short links stay short.
POST /api/links
{ "long_url": "https://example.com/a/very/long/path", "alias": "launch", "expires_at": "2027-01-01" }
→ 201 Created
{ "code": "launch", "short_url": "https://sho.rt/launch" }
GET /{code}
→ 302 Found
Location: https://example.com/a/very/long/pathData model
Every read is one lookup by code, so it's one table keyed by code. A key-value store such as DynamoDB or Cassandra fits, as does a relational table sharded by code.
links
code varchar(10) primary key
long_url text
owner_id bigint nullable
created_at timestamp
expires_at timestamp nullableGenerating short codes
- Counter + base62: give every link a unique integer ID and encode it with a-z, A-Z, 0-9. No collisions. So the counter isn't a bottleneck, hand each API server a block of IDs (say 1,000 at a time) from a coordinator, or use a Snowflake-style generator.
- Hash + truncate: hash the long URL (SHA-256, say) and keep 7 characters. The same URL always gets the same code, but two URLs can collide, so check and retry.
- Sequential IDs give guessable codes. For private links, shuffle the ID with a reversible permutation before encoding, or add random characters.
High-level design
- Writes: load balancer, API server, ID generator, database.
- Reads: the API server checks the cache first. Only misses go to the database, and the result is written back.
- The database is sharded by code, so every lookup touches one shard. Database sharding covers choosing a shard key and resharding later.
Scaling the redirect path
- The mapping almost never changes, so cache it in Redis or Memcached. At a 90% hit ratio only one redirect in ten reaches the database.
- 301 lets browsers and CDNs cache the redirect, which removes load but hides repeat clicks. 302 brings every click back, which keeps analytics accurate and costs more traffic.
- Give links that can be edited or expire a short TTL or explicit invalidation.
- For click counts, the handler publishes a small event to Kafka, Kinesis or SQS and returns. A separate consumer aggregates counts into an analytics store.
Common traps
- Adding API servers when the database is the bottleneck. In the simulation above, 3,000 redirects a second against a database that serves 1,000 fails two thirds of requests. Find the bottleneck from the numbers.
- Hashing the URL and keeping 7 characters without saying how you detect a collision and retry. A base62 counter can't collide.
- Plain auto-increment codes for private links. Anyone can walk them. Shuffle the ID before encoding.
- Sizing for the average. The cache and database have to survive about 15,000 redirects a second at peak, especially right after a cache restart.
- Putting a CDN in front by default. At 20,000 redirects a second CloudFront's list price is over $50,000 a month, and a redirect is too small to save bandwidth. Cache in memory and let browsers cache 301s first.
- Writing a click row to the links table on every redirect. That turns a read-heavy system into a write-heavy one.
Follow-up questions interviewers ask
- "A custom alias is already taken." The insert fails on the primary key and you return a conflict.
- "Should the same long URL always get the same code?" A counter gives a new code each time. For one code per URL, hash the URL or look it up first, at the cost of an index on long_url.
- "What if the ID coordinator goes down?" Each API server holds a block of IDs and keeps creating links until it runs out. Redirects never touch the coordinator.
- "How do you handle expired links?" Check expires_at on redirect, keep cache TTLs no longer than the link's remaining life, and let a background job remove old rows.
Frequently asked questions
Should a URL shortener use SQL or NoSQL?
+
Either works. Every read is a single key lookup, so a key-value store like DynamoDB scales out easily and a relational database sharded by code works too. The cache in front matters far more than the database.
Should a URL shortener use a 301 or 302 redirect?
+
Use 302 if you need accurate click analytics, because browsers request the short URL every time. Use 301 to let browsers and CDNs cache the redirect, accepting that repeat clicks go uncounted.
How long should a short code be?
+
Seven base62 characters give about 3.5 trillion codes, enough for billions of links a year for decades. Six give about 57 billion, often enough for a smaller service.
How do you avoid two links getting the same code?
+
Generate codes from a unique counter encoded in base62, which cannot collide. If you hash the URL instead, check whether the code exists and retry with a different salt.