Guide / System design Most asked
Design: URL shortener
A complete 45-minute answer for a TinyURL/bit.ly style service: requirements, estimates, ID generation, redirect path, caching, analytics, abuse handling and follow-ups.
The simplest “classic” design, so interviewers use it to test depth: ID generation without collisions, a cached read path, 301 vs 302, analytics and abuse.
Fundamentals (the design)#
1. Requirements#
Functional: create a short URL from a long URL (optional custom alias and expiry), redirect short → long, basic click analytics, delete/disable links. Non-functional: redirect p99 < 50 ms at the service, 99.99% availability for reads, links never collide, highly read-heavy (100:1), short codes not guessable in sequence if links are private. Out of scope: user accounts beyond API keys, rich analytics UI.
2. Estimates#
100M new links/month → ~40 writes/s; reads 100:1 → ~4K QPS average, ~12K peak. Storage: ~500 B per record × 100M × 12 months × 5 years ≈ 3 TB. Code length: 7 base62 characters = 62^7 ≈ 3.5 trillion ≫ 6B links. Cache: 20% of daily redirect traffic ≈ a few GB, so one Redis cluster with replicas.
3. API#
POST /v1/urls { "long_url": "...", "custom_alias": "sale", "expires_at": "..." } → 201 { "short_url": "https://sho.rt/aZ3x9Qk" }
GET /{code} → 301 or 302, Location: long_url
DELETE /v1/urls/{code}
GET /v1/urls/{code}/stats
Create is idempotent via Idempotency-Key (or deterministic hash for “same URL → same code” if desired). Rate-limit creation per API key.
4. Data model#
urls(code PK, long_url, owner_id, created_at, expires_at, status) in a key-value or wide-column store (DynamoDB/Cassandra) or sharded Postgres by code. Lookups are only by code, so a KV store fits. clicks go to a separate analytics pipeline.
5. Generating the code (the core deep dive)#
| Approach | How | Pros | Cons |
|---|---|---|---|
| Hash of the URL (MD5/SHA, take 7 chars) | base62(hash(url))[:7] | Stateless, same URL maps to the same code | Collisions (check DB and retry with a salt), no per-user links |
| Counter + base62 | A global sequence encoded in base62 | No collisions, short | Sequential and guessable, counter is a bottleneck/SPOF |
| Range-allocated counter | A coordinator (ZooKeeper/DB) hands each app server a block of 1,000–100,000 IDs; it encodes locally | No per-request coordination, no collisions | Gaps on crash (fine), still guessable; scramble with a bijective permutation or add a random component |
| Snowflake-style ID → base62 | timestamp + machine ID + sequence | Decentralised | Longer codes (~11 chars) |
| Pre-generated key pool | A key-generation service pre-creates random unique codes in a table; servers claim batches | Short, random, no collision check on the hot path | Another service to run; claimed-but-unused keys are lost on crash (acceptable) |
Recommended answer: range-allocated counter with a bijective scramble (or a key-generation service with a pool). Custom aliases are inserted with a unique constraint; on conflict return 409.
6. Read path (the hot path)#
client → CDN/edge (cache 301s) → LB → redirect service → Redis (code → long_url, TTL 24h) → DB on miss
└─ async: publish click event → Kafka → analytics
- 301 (permanent) can be cached by browsers and CDNs: fewer hits but you lose click counts. 302/307 (temporary) is hit every time: accurate analytics, more load. Choose 302 if analytics matter, 301 if cost matters; many services use 302.
- Cache-aside with negative caching for unknown codes (prevents penetration) and a Bloom filter of valid codes (Caching).
- Redirect service is stateless and autoscaled; the redirect must not wait for analytics (fire-and-forget to Kafka, drop on overload).
7. Analytics#
Click event {code, ts, ip_country, user_agent, referrer} → Kafka → stream aggregation (Flink/ClickHouse) → counts per code per hour. Approximate unique visitors with HyperLogLog. Dashboard reads aggregates, never raw events.
8. Expiry, abuse and safety#
TTL-based expiry with lazy deletion on read plus a background sweeper; reuse of expired codes after a cooling period. Abuse: check destinations against phishing/malware lists (Safe Browsing), block redirect loops and internal IPs (SSRF), rate-limit creation, CAPTCHA for anonymous creation, honour takedown requests.
9. Failure modes and scaling#
Redis down → fall back to DB with rate limiting and a circuit breaker; DB shard hot → replicate hot codes into cache and CDN; region failure → multi-region read replicas of the KV store and anycast/GeoDNS. Sharding by code hash spreads load evenly. The read path scales by adding cache replicas and edge caching.
Most asked questions#
1. How do you generate unique short codes? Range-allocated counters or a key-generation service, base62 encoded; hash plus collision checks as the simple alternative.
2. 301 vs 302? 301 is cacheable (less load, no analytics); 302 is not (accurate counts).
3. How do you handle 100:1 reads? Cache-aside Redis, CDN caching of redirects, read replicas, stateless redirect service.
4. How do you support custom aliases? Unique constraint on code; return 409 on conflict; reserve banned words.
5. How would you delete or expire links? expires_at checked at read time, background cleanup, cache TTL aligned with expiry, tombstones.
Senior-level questions#
1. “How do you avoid guessable codes while keeping them short and collision-free?” Allocate numeric IDs from ranges then apply a bijective scramble (e.g. a Feistel network or multiplicative inverse modulo 62^7) before base62 encoding: unique by construction and non-sequential.
2. “A viral link gets 200K redirects/s.” Edge caching (CDN with short TTL), local in-process caches, replicated hot keys, request coalescing, and load shedding of analytics events; consider 301 for that link temporarily.
3. “Same long URL submitted twice?” Either create separate codes (simple, per-user analytics) or dedupe by hash of the normalised URL per owner with a unique index.
4. “How do you make analytics exactly-once?” Count approximately; for billing use dedupe by event ID in the stream processor with checkpointed state, accept at-least-once for dashboards.
5. “Multi-region active-active writes?” Region-prefixed ID ranges avoid collisions; the KV store replicates globally; conflicts are impossible for codes allocated per region; custom aliases need a home-region or global check.
Quiz#
1. How many 7-character base62 codes exist?
62^7 ≈ 3.5 × 10^12.
2. Why is the redirect analytics write asynchronous?
Redirect latency must not depend on analytics storage; use a queue and tolerate loss or delay.
3. Drawback of hashing the URL for the code?
Collisions require checks and retries, and identical URLs always share a code, which breaks per-user tracking.
4. Which store and why for the code → URL map?
A key-value/wide-column store such as DynamoDB or Cassandra: single-key lookups, easy horizontal scaling, high availability.
5. How do you stop attackers enumerating private links?
Non-sequential codes (scrambled or random), rate limiting on redirects per IP, longer codes for private links, and authorisation for private destinations.