Design a URL Shortener with Fast Redirect Lookups
System DesignModel answerLast updated
Design a system that converts long URLs into short codes and resolves them to the original URL with low latency at modest scale.
Background
A URL shortener takes an arbitrary long URL (e.g., https://example.com/very/long/path?query=123) and returns a short code (e.g., short.ly/aB3xZ). When a user visits the short link, they are redirected to the original URL within milliseconds.
This is a classic entry-level system design problem that tests your understanding of storage choices, indexing, and read-heavy workload optimisation.
Functional Requirements
- Shorten: given a long URL, return a unique short code (6–8 alphanumeric characters).
- Redirect: given a short code, return the original URL (HTTP 301/302 redirect).
- Optional: basic click analytics (count redirects per short code).
Non-Functional Requirements / Scale
- Write rate: ~500 new short URLs per second (peak).
- Read rate: ~50,000 redirects per second (100:1 read-to-write ratio).
- Data retention: URLs live for at least 2 years.
- p99 redirect latency: under 20 ms.
- Availability: 99.9% uptime is sufficient; strong consistency is not required.
What Is Expected
Walk through:
- API design (endpoints and response codes)
- Short code generation strategy
- Data model and storage choice
- How you index and cache for fast lookups
- At least two trade-offs you consciously made
Hints
Hint 1
How many total short codes will you need to store over 2 years at 500 writes/sec? Does a relational DB with a single primary-key index handle that, or do you need something else?
Hint 2
The read-to-write ratio is 100:1. What layer can absorb most reads before they ever hit your database?
Hint 3
Think about what HTTP status code to return on redirect and why the choice affects browser and CDN caching behaviour.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
1. Capacity Estimation
- Writes per day: 500 × 86,400 ≈ 43 million URLs/day
- Over 2 years (730 days): 43 million × 730 ≈ ~31 billion rows
- Average row size: 8-byte code + 2 KB URL + metadata ≈ 2.1 KB per row
- Total storage: 31 × 10^9 rows × 2.1 × 10^3 bytes ≈ ~65 TB over 2 years — manageable across a sharded key-value store
- Reads: 50,000/sec → caching is essential to avoid overwhelming the primary store
2. API Design
POST /shorten
Body: { "url": "https://..." }
Response 201: { "short_code": "aB3xZ9" }
GET /{short_code}
Response 301 (permanent) or 302 (temporary): Location: <original_url>
GET /stats/{short_code} # optional
Response 200: { "clicks": 1042 }
301 vs 302 trade-off:
- 301 (permanent): browsers cache the redirect locally, reducing future server load. Downside: you lose click analytics and cannot later change the destination.
- 302 (temporary): every click hits your servers, enabling accurate counting and future re-targeting. This is the right default for a commercial shortener where analytics matter.
3. Short Code Generation
Option A — Hash-based: MD5/SHA-256 the long URL, take the first 7 base-62 characters.
- Pros: deterministic (same URL → same code, natural deduplication).
- Cons: collision probability rises with scale; must detect and handle collisions explicitly.
Option B — Counter + base-62 encode: use a distributed counter (e.g., a dedicated ID-generation service or database sequence), encode the integer in base-62.
- 7 characters of base-62 = 62^7 ≈ 3.5 trillion codes — sufficient for centuries at this scale.
- Pros: zero collision risk, predictable length, monotonically increasing.
- Cons: exposes rough write volume; counter service is a potential single point of failure (mitigate with range pre-allocation per application node).
Recommended: Option B with range pre-allocation. Each app node claims a block of 10,000 IDs from a counter service at startup and only contacts the counter service when the block is exhausted. This eliminates per-request coordination overhead.
4. Data Model and Storage
Primary store — key-value database (e.g., Redis Cluster, DynamoDB, or Cassandra):
| Field | Type | Notes |
|---|---|---|
| short_code | string | partition key / primary key |
| original_url | string | up to 2 KB |
| created_at | timestamp | |
| expires_at | timestamp | nullable |
| click_count | counter | eventually consistent |
A key-value store is ideal here because:
- The access pattern is almost exclusively point lookups by
short_code— no range queries or JOINs are needed. - Horizontal sharding by
short_codedistributes load evenly across nodes. - Most KV stores support TTL natively, which handles link expiry without a background cleanup job.
A relational database with a B-tree index on short_code works at smaller scale but becomes a bottleneck at 50,000 reads/sec without an additional caching layer.
5. Caching Layer
Place a Redis cache between the app servers and the primary store:
Client → Load Balancer → App Server → Redis Cache → KV Store
- Cache key:
short_code - Cache value:
original_url - TTL: 24 hours (refresh on access)
- Expected hit rate: popular links follow a power-law distribution; caching the top 20% of codes absorbs roughly 80% of reads.
- At 50,000 reads/sec with an 80% hit rate, the KV store sees only ~10,000 reads/sec — well within capacity.
Memory requirement for the cache: if 20% of the 31 billion total codes are "hot" at any one time that is optimistic — in practice only a small recent working set is hot. Caching 10 million entries × 2.1 KB ≈ ~21 GB of RAM, affordable on a few Redis nodes.
6. Architecture Overview
Write path:
Client → Load Balancer → App Server → ID Service (range allocation)
→ KV Store (write)
→ Cache (write-through)
Read path:
Client → Load Balancer → App Server → Redis Cache (hit → 302 redirect)
→ KV Store (miss → fetch, populate cache, 302 redirect)
The app tier is stateless; any number of instances can run behind the load balancer.
7. Trade-offs Summary
| Decision | Chosen | Alternative | Reason |
|---|---|---|---|
| HTTP status | 302 | 301 | Retains click analytics and allows destination changes |
| Code generation | Counter + base-62 | Hash | No collisions; minor overhead of counter service worth it at this scale |
| Primary store | KV store | RDBMS | Point-lookup pattern and sharding needs favour KV; relational features are unnecessary |
| Click counting | Async (via queue → counter) | Synchronous increment on redirect | Avoids write hotspots on popular links; decouples counting from the latency-sensitive redirect path |
Common Mistakes to Avoid
- Returning 301 without considering analytics — always clarify whether click tracking is required before choosing the redirect code.
- Using a single SQL table without caching — 50,000 reads/sec will overwhelm a single database instance; a cache is non-negotiable at this scale.
- Ignoring collision handling in hash-based generation — even a low per-code probability compounds to near-certainty across tens of billions of codes.
- Updating click_count synchronously on every redirect — this creates write hotspots on popular links; decouple counting into an async pipeline (e.g., Kafka consumer writing batched increments) instead.