A URL shortener turns https://example.com/some/very/long/path?with=params into sho.rt/aZ3kQ9x and redirects anyone who visits the short link. The redirect has to be fast and almost never fail, which makes it a good exercise in caching and availability. The interesting part is generating the keys.
Requirements and numbers
- Functional: create a short link (optionally with a custom alias and an expiry), redirect, and count clicks.
- Non-functional: redirects in a few milliseconds, very high availability, no two long URLs ever sharing a key, and keys that aren't easy to guess.
| Quantity | Math | Result |
|---|---|---|
| New links per second | 100M per month ÷ 2.6M seconds | ≈ 40/s average, ~120/s peak |
| Redirects per second | 100 reads per write | ≈ 4,000/s average, ~12,000/s peak |
| Rows after 5 years | 100M × 12 × 5 | 6 billion |
| Storage | 6B × ~500 bytes | ≈ 3 TB |
| Key space with 7 base62 characters | 62⁷ | ≈ 3.5 trillion |
Writes are tiny. Reads are 100 times larger and very skewed, since a few links go viral. Seven characters of [0-9a-zA-Z] give about 580 keys for every link you'll ever store.
Generating keys
| Approach | How | Good | Bad |
|---|---|---|---|
| Hash the URL | Take the first 7 base62 characters of MD5 or SHA-256 of the long URL. | The same URL always gets the same key, so no duplicates. | Collisions: check, and on a clash re-hash with a salt and retry. |
| Counter + base62 | A global counter; encode each new number in base62. | No collisions; keys are as short as possible. | One counter is a bottleneck and a single point of failure, and sequential keys can be enumerated. |
| Counter ranges | Each server leases a block (say 1,000 numbers) from a coordinator. | No per-request coordination. | A crashed server wastes its block, which is fine. Keys are still guessable unless scrambled. |
| Pre-generated pool | A key generation service creates random unused keys offline; servers take batches. | No collision check at write time; random, unguessable keys. | An extra service, and the pool must not run dry. |
Collision odds for the hash approach: with 6 billion keys in a space of 3.5 trillion, each new key has about a 0.17% chance of hitting an existing one. One retry fixes nearly all of them, so hashing works fine. A common interview answer is counter ranges with the numbers scrambled (for example by a reversible bit shuffle) so the keys look random, or a pre-generated pool.
General-purpose IDs
The same problem shows up everywhere you need unique IDs without a central database sequence:
- UUID v4: 128 random bits, no coordination at all. But it's long, and random inserts scatter across a B-tree index and slow down writes.
- UUID v7 / ULID: a timestamp prefix plus randomness, so IDs sort roughly by creation time and insert at the "end" of the index.
- Snowflake (Twitter's scheme): a 64-bit integer made of 41 bits of milliseconds, 10 bits of machine ID and 12 bits of sequence. That's 4,096 IDs per millisecond per machine, time-ordered, with no coordination beyond assigning machine IDs. In base62 it's 11 characters, too long for short links but ideal for posts and messages.
The redirect path
- 301 or 302? A
301 Moved Permanentlylets browsers and CDNs cache the redirect, which saves load but hides repeat clicks from you. A302 Foundsends every click through your servers, so you can count them. Use 302 if analytics matter. - Cache: cache-aside in Redis keyed by the short key. Traffic follows a power law, so a cache holding the hottest few percent of links serves 90%+ of redirects, and the database sees roughly 1,200 reads per second at peak.
- Analytics off the hot path: don't write a row per click. Publish a click event to a log (Kafka) and aggregate counts asynchronously.
Storage
The data is a simple mapping looked up by primary key, with no joins, so a key-value store (DynamoDB, Cassandra) fits naturally and partitions by key. PostgreSQL works too at this size: 3 TB over five years is manageable with a few shards. Store short_key (primary key), long_url, owner_id, created_at and expires_at. Expired links can be deleted lazily on read and by a periodic cleanup job.
Abuse
Shorteners attract spam and phishing. Rate-limit link creation per user and per IP (see rate limiting, including how to keep counters consistent across N servers), check new URLs against a malware blocklist, and make custom aliases a logged-in feature.
Interview checklist
- Estimate QPS and storage, and size the key space.
- Compare at least two key-generation schemes and pick one.
- Choose 301 or 302 and explain the analytics trade-off.
- Cache the redirect path and estimate the hit rate.
- Rate-limit creation, and move analytics off the hot path.
Model it in the sandbox
Set the traffic from your estimate, then build the read and write paths and see which component turns red first.
Open the sandboxDo it by hand
Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.
Further reading
- Alex Xu, System Design Interview: An Insider's Guide, volumes 1 and 2. Worked case studies in interview format.
- Martin Kleppmann, Designing Data-Intensive Applications (O'Reilly). The standard book on replication, partitioning and consistency.
- Site Reliability Engineering, Google's free book on running reliable systems.
- The Amazon Builders' Library: practical articles on timeouts, retries, caching and load shedding.
- The System Design Primer: a broad, community-maintained overview.