Design a URL Shortener (TinyURL / bit.ly)
The classic warm-up. Short-code generation strategies (hash, counter + base62, pre-generated keys), a read-heavy redirect path with caching, 301 vs 302, analytics via an event stream, custom aliases, expiry, and abuse prevention.
1. Requirements
Functional
- Create a short URL for a long URL (optional custom alias, optional expiry).
- Redirect short URL → long URL.
- Click analytics per link (counts, geography, referrers).
Non-functional
- Very high availability for redirects (links are embedded everywhere).
- Redirect latency p99 < 50 ms server-side.
- Short codes unpredictable enough to avoid enumeration.
- Durable: links must not be lost.
Out of scope: user management UI, link-in-bio pages, billing.
2. Estimation
| Quantity | Assumption | Result |
|---|---|---|
| New links | 100M / month | ~40 writes/s (peak ~200/s) |
| Redirects | 100:1 read ratio | ~4,000 reads/s avg (peak ~40k–100k/s) |
| Storage per link | code 7 B + URL ~200 B + metadata ~300 B | ~500 B |
| 5 years of links | 100M × 12 × 5 = 6B links | ~3 TB |
| Code length | 62⁷ ≈ 3.5 × 10¹² | 7 chars is plenty |
| Cache | 20% of daily hot links | tens of GB |
Conclusion: small data, read-heavy, latency-sensitive → cache-heavy design; any KV store works.
3. API
POST /api/v1/links
Authorization: Bearer <token>
Content-Type: application/json
{"long_url": "https://example.com/very/long/path?x=1", "custom_alias": "launch", "expires_at": "2027-01-01T00:00:00Z"}
201 Created
{"code": "launch", "short_url": "https://sho.rt/launch", "long_url": "...", "expires_at": "..."}
GET /launch
302 Found
Location: https://example.com/very/long/path?x=1
Cache-Control: private, max-age=90
GET /api/v1/links/{code}/stats?from=…&to=…&granularity=day returns aggregated analytics.
4. Data model
CREATE TABLE links (
code VARCHAR(16) PRIMARY KEY, -- partition key
long_url TEXT NOT NULL,
owner_id BIGINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ,
is_disabled BOOLEAN NOT NULL DEFAULT false
);
CREATE INDEX ON links (owner_id, created_at DESC); -- "my links" page
Access is by primary key only → DynamoDB/Cassandra or sharded Postgres keyed by code. Analytics go to a separate OLAP store.
5. High-level design

Create flow: validate URL (format, safe-browsing check) → if custom alias, conditional insert (IF NOT EXISTS) → else take next ID from the server's local range → encode base62 (optionally shuffled) → insert → return.
Redirect flow: look up code in Redis → on miss read KV and populate (with negative caching for misses) → check expiry/disabled → emit click event async → 302 with Location.
6. Deep dives
Code generation with range allocation
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def base62(n: int) -> str:
if n == 0:
return ALPHABET[0]
out = []
while n:
n, r = divmod(n, 62)
out.append(ALPHABET[r])
return "".join(reversed(out))
class IdAllocator:
"""Leases blocks of IDs from a coordinator so most allocations are local and lock-free."""
def __init__(self, coordinator, block=1_000_000):
self.coord, self.block = coordinator, block
self.next = self.end = 0
def next_id(self) -> int:
if self.next >= self.end:
start = self.coord.lease(self.block) # atomic increment in ZK/DB
self.next, self.end = start, start + self.block
self.next += 1
return self.next - 1
// Bijective shuffle so sequential IDs don't produce guessable codes:
// a 4-round Feistel network over a 42-bit space (62^7 > 2^42).
static final long[] KEYS = {0x3A7F1L, 0x1C2B9L, 0x7E44DL, 0x05F13L}; // secret round keys
static long permute(long id) {
long l = (id >>> 21) & 0x1FFFFF, r = id & 0x1FFFFF;
for (int round = 0; round < 4; round++) {
long f = ((r * 0x5DEECE66DL + KEYS[round]) >>> 7) & 0x1FFFFF;
long t = r; r = l ^ f; l = t;
}
return (l << 21) | r;
}
Custom aliases and uniqueness
Use a conditional write so two users can't claim the same alias: INSERT … IF NOT EXISTS (Cassandra LWT), DynamoDB attribute_not_exists(code), or a unique constraint in SQL. Reserve a namespace for generated codes (e.g., generated codes always 7 chars, aliases ≥ 4 chars and validated against a blocklist) so they never collide.
Expiry
Store expires_at; check on redirect (and set cache TTL ≤ remaining lifetime). Clean up lazily plus a periodic batch job (or the store's native TTL). Don't recycle expired codes quickly — old links in the wild would point somewhere new.
7. Trade-offs and evolution
| Decision | Choice | Alternative |
|---|---|---|
| Code generation | range allocation + shuffle | hash + collision check; KGS |
| Redirect | 302 for analytics | 301 for less load |
| Store | DynamoDB/Cassandra (KV by code) | sharded Postgres |
| Analytics | async Kafka → OLAP | synchronous counters (slows redirects) |
| Multi-region | replicate links globally (read-local), writes to home region | — |
Failure modes: cache cluster loss → DB read storm (use replicas, request coalescing, gradual warm-up); ID coordinator down → servers keep using leased ranges for a long time; Kafka down → buffer locally and drop analytics after a limit rather than failing redirects.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.