Case Study: URL Shortener
Design a TinyURL/bit.ly-style service end to end — requirements, estimates, key generation (base62, counters, hashing), the redirect path, caching, analytics and scaling.
A classic first system design problem: small enough to finish in 45 minutes, rich enough to show estimation, data modelling, key generation and caching.
1. Requirements
Functional
- Given a long URL, return a short one (
sho.rt/aZ3kP9q). - Visiting the short URL redirects to the long one.
- Optional: custom aliases, expiry, click analytics.
Non-functional
- Very read-heavy (redirects ≫ creations), so redirects must be fast (p99 under ~50 ms) and highly available.
- Short codes must be unique and not easily guessable in sequence (optional).
2. Estimates
- 100M new URLs/month ≈ 40 writes/s (peak ~200/s).
- Read:write of 100:1 → 4,000 redirects/s (peak ~20k/s).
- Storage: 100M × 12 months × 5 years = 6B URLs × ~500 bytes ≈ 3 TB.
- Code length: 62⁷ ≈ 3.5 trillion — 7 base62 characters is plenty.
3. API
POST /api/v1/urls { "long_url": "https://...", "alias": "optional", "expires_at": "optional" }
→ 201 { "short_url": "https://sho.rt/aZ3kP9q" }
GET /aZ3kP9q
→ 301/302 Location: https://...301 (permanent) lets browsers cache the redirect — less load, but you lose click analytics. 302 (temporary) sends every click through you. Choose 302 if analytics matter.
4. High-level design
5. Generating short codes
| Approach | How | Pros | Cons |
|---|---|---|---|
| Hash + truncate | base62(md5(long_url))[0:7] | Same URL → same code; no coordination | Collisions: check and retry with a salt |
| Global counter + base62 | Unique integer ID → base62 | No collisions, short codes | Need a distributed counter; sequential codes are guessable |
| Counter ranges | Each server leases a block of 1M IDs from a coordinator (ZooKeeper/DB) | No per-request coordination | Unused IDs lost on crash (harmless) |
| Pre-generated key service | Offline-generate random codes into a table; hand them out | Random, unique, fast | Extra service and storage |
| Snowflake-style IDs | Timestamp + machine ID + sequence | Decentralised | Longer codes (~11 chars) |
static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
static String encode(long n) {
if (n == 0) return "0";
StringBuilder sb = new StringBuilder();
while (n > 0) { sb.append(ALPHABET.charAt((int) (n % 62))); n /= 62; }
return sb.reverse().toString();
}ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode(n: int) -> str:
if n == 0:
return "0"
out = []
while n:
n, r = divmod(n, 62)
out.append(ALPHABET[r])
return "".join(reversed(out))const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function encode(n: bigint): string {
if (n === 0n) return "0";
let s = "";
while (n > 0n) { s = ALPHABET[Number(n % 62n)] + s; n /= 62n; }
return s;
}To make sequential IDs non-guessable, permute the ID first (multiply by a large odd constant modulo 62⁷, or a small block cipher) before encoding.
6. Data model
CREATE TABLE urls (
code VARCHAR(10) PRIMARY KEY,
long_url TEXT NOT NULL,
user_id BIGINT,
created_at TIMESTAMP NOT NULL,
expires_at TIMESTAMP
);Access is a pure key lookup, so a key-value store (DynamoDB, Cassandra) or sharded SQL both work. Shard by code (hash), which spreads load evenly.
7. The read path
GET /aZ3kP9qhits a stateless app server.- Look up
aZ3kP9qin Redis. URLs follow a power law — a small fraction gets most clicks — so a cache of the hot 20% absorbs most reads. - On a miss, read from the database and populate the cache (cache-aside, with a TTL).
- Return 302 with the
Locationheader; asynchronously publish a click event. - Missing or expired codes return 404. Cache negative results briefly to stop repeated lookups for junk codes.
8. Analytics
Don't write to the database on every click. Publish click events (code, time, referrer, country, user agent) to Kafka, aggregate with a stream processor, and store counts in a columnar/analytics store.
9. Further concerns
- Abuse: rate-limit creation, scan long URLs against malware/phishing lists.
- Custom aliases: check uniqueness with a conditional insert.
- Expiry: lazy deletion on read plus a background cleanup job.
- Availability: replicate the DB, multi-region read replicas plus CDN/edge caching of redirects.
- Read-heavy: optimise the redirect path with caching; 7 base62 characters give 3.5 trillion codes.
- Key generation: counter ranges + base62 (unique, no collisions) or hash + collision check.
- 302 keeps analytics; 301 reduces load.
- Simple key-value data model, sharded by code.
- Clicks go through a queue to an analytics pipeline, not the primary DB.