Requirements and estimates
- Create a short link for a long URL, optionally with a custom alias and expiry.
- Visiting the short link redirects to the original URL, fast.
- Basic click analytics.
- Non-functional: very high availability for redirects, low latency, links must never point to the wrong place.
100M new links/month ≈ 40 writes/s (peak ~100/s)read:write = 100:1 ≈ 4,000 redirects/s (peak ~10k/s)5 years × 100M × 12 = 6 billion links6B × ~500 bytes ≈ 3 TB of storagecode length: 62⁷ ≈ 3.5 trillion → 7 base-62 characters is plenty
API and data model
POST /api/v1/links { "url": "https://…", "alias": "optional", "expiresAt": "optional" }→ 201 { "code": "aZ3kP9q", "short": "https://sho.rt/aZ3kP9q" }GET /{code} → 301/302 Location: https://… (404 if unknown or expired)
One table: links(code PRIMARY KEY, long_url, user_id, created_at, expires_at). Lookups are always by code, so a key-value store or a sharded SQL table both work.
301 (permanent) lets browsers cache the redirect, which reduces load but hides repeat clicks from analytics. 302 (temporary) sends every click through you. Pick based on whether analytics matter.
Generating short codes
| Approach | How | Trade-offs |
|---|---|---|
| Hash the URL | First 7 chars of base62(MD5/SHA of the URL) | Same URL gives the same code; collisions must be detected and retried |
| Counter + base62 | A unique number encoded in base 62 | No collisions; codes are guessable and a single counter is a bottleneck |
| Pre-allocated ranges | Each app server leases a block of 1,000 ids from a coordinator (or a DB sequence) | No per-request coordination; a crashed server wastes the rest of its block (fine) |
| Snowflake-style ids | timestamp + machine id + sequence, encoded | Decentralized and roughly time-ordered; longer codes |
| Pre-generated keys | A key service fills a table of unused random codes | Not guessable, fast handout; must mark keys used atomically |
static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";static String base62(long n) {StringBuilder sb = new StringBuilder();do { sb.append(ALPHABET.charAt((int) (n % 62))); n /= 62; } while (n > 0);return sb.reverse().toString();}
Scaling the read path
- Redirects are reads of immutable data: perfect for caching. A Redis cache of hot codes (link popularity follows a power law) absorbs most traffic.
- Stateless redirect servers behind a load balancer; the database sharded by
code(hash), with replicas. - A Bloom filter of existing codes rejects random guesses before they reach the cache or DB.
- Click analytics go to a queue (code, time, referrer, country) and are aggregated asynchronously, so redirects stay fast.
Redirect path
GET /aZ3kP9q reaches one of many stateless redirect servers.
See it animated
Interview questions
Try answering out loud first, then open the model answer.
Q1How long should the short code be?beginner
Size it from total links. Base 62 with 7 characters gives 62⁷ ≈ 3.5 trillion codes, far more than 6 billion links over 5 years; 6 characters (≈ 57 billion) would also do. Leave headroom so random or hashed codes rarely collide.
Q2How do you avoid two servers generating the same code?intermediate
Either make collisions impossible (a counter: each server leases a unique range of ids from a coordinator and base62-encodes them) or detect them (insert with a unique constraint on the code and retry with a new code on conflict). Range leasing avoids a round trip per link.
Q3Why might you not want sequential codes?intermediate
They're guessable: anyone can enumerate links and find private documents, and they reveal how many links you create. Shuffle the id with a reversible permutation, add randomness, or use pre-generated random keys.
Q4How would you handle 100k redirects per second?intermediate
Cache aggressively (the data never changes), keep redirect servers stateless and horizontally scaled, put a CDN or edge cache in front for the hottest links, shard and replicate the store, and move analytics off the request path through a queue.
Quick check
0 of 3 answered