Designing a URL shortener: short codes, Base62, token ranges and redirects
A full system design case study for a Bitly-style link shortener: requirements, estimates with the arithmetic, API, data model on ScyllaDB and PostgreSQL, four ways to generate codes, token ranges that neither collide nor leak order, 301 versus 302, caching, analytics, and how to present it in 45 minutes.
On this page
The URL shortener is the "intro" system design question, but it leaves plenty of room to show depth: codes that never collide, can't be guessed, and are read a hundred times more than written. This post walks through every step as in a real interview, with a 45-minute plan.
1. The problem
Version one used the DB's auto-increment id plus Base62. A week later someone scripted increments from aB3xK9p to aB3xK9q... and scraped every customer link, internal document links included.
2. Key idea
Few writes (116/s), many reads (12K/s, ~35K at peak). The URL table is pure key-value with tens of billions of rows, ~22 TB including replicas; a day's links cache in just ~2.2 GB.
| Number source | Collisions? | Length | Guessable? | Verdict |
|---|---|---|---|---|
| Random in 62⁸ | yes, needs conditional writes | 8 | no | fine |
| Hash the long URL, cut to 7 | yes | 7 | same URL, same code | breaks "one URL, many codes" |
| Snowflake (64 bits) | no | 11 | by time | too long |
| Token range + Feistel | no | 7 | no | chosen |
Token range: a coordinator hands out non-overlapping ranges, and can be a single PostgreSQL row: UPDATE id_alloc SET next_start = next_start + 1000000 RETURNING next_start. At 116 writes/s one range lasts ~2.4 hours. If the coordinator dies, links keep being created until the range runs out. The price: numbers wasted when an instance dies, codes not contiguous.
2.1 Redirect: 301 or 302?
| Use when | Don't use when | |
|---|---|---|
| 301 Moved Permanently | load and SEO come first; browsers remember | you count clicks or change/disable links |
302 Found + Cache-Control: private, max-age=0 |
you need analytics | load is the biggest problem |
Read path: Redis first, ScyllaDB on a miss. Clicks go to Kafka without waiting for an ack, then into ClickHouse: analytics never slows a redirect.
2.2 What interviewers ask about
- Snowflake doesn't collide; reject it because 64 bits need 11 characters and it's guessable.
- One URL, one code: lookup-then-write lets two concurrent requests create two codes. Write conditionally to
url_by_hash ... IF NOT EXISTS; normalize the URL before hashing. - Bots scanning nonexistent codes: cache empty results or keep a Bloom filter of every issued code.
3. In Java
final class CodeGenerator {
private static final String ALPHABET =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final int HALF = 21; // 2 halves × 21 bits = 42 bits
private static final long MASK = (1L << HALF) - 1;
static long permute(long n, long[] keys) { // Feistel: always invertible, no collisions
long l = n >>> HALF, r = n & MASK;
for (long k : keys) { long t = r; r = l ^ (mix(r, k) & MASK); l = t; }
return (l << HALF) | r;
}
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();
}
}
// base62(permute(n, keys)): n = 1, 2, 3 give three unrelated codesThis isn't encryption, just enough that codes can't be guessed by incrementing.
Detailed estimates
| Quantity | Calculation | Result |
|---|---|---|
| Writes | 10⁷ / 86,400 | ~116/s, peak ×3 ≈ 350 |
| Reads | 100 × 116 | ~12K/s, peak ≈ 35K |
| Records over 4 years | 10⁷ × 365 × 4 | 1.46 × 10¹⁰ |
| Storage | 1.46 × 10¹⁰ × 500 B | 7.3 TB; ×3 replicas ≈ 22 TB |
| Code space | 62⁶ ≈ 5.7 × 10¹⁰; 62⁷ ≈ 3.5 × 10¹² | 6 characters barely fit; choose 7 for ~240× headroom |
Assume ~500 bytes per record (a ~200-byte long URL plus metadata). What matters is stating the assumptions, not the exact number.
4. Working with AI
Give the AI: the estimation table, the CQL schema, a diagram of the write and read paths, a test that Feistel is invertible over a million numbers.
Check in the AI's design:
- Codes can't be derived from the previous one (shuffled, or random).
- No lookup-then-write for dedupe or custom aliases; use
IF NOT EXISTS. - The 301/302 choice matches the analytics requirement.
- Analytics is asynchronous, off the redirect path.
5. Exercises
Exercise 1: Three code-generation proposals
The AI offers: (A) MD5(longUrl) cut to 7 characters; (B) Snowflake then Base62; (C) UUID v4 then Base62 cut to 8 characters, written with IF NOT EXISTS, retrying on collision. Given "one URL, many codes, unguessable, at most 8 characters", which do you pick and reject?
Solution to Exercise 1
- A rejected: the same URL gets the same code (against the requirement), and cutting to 7 collides across different URLs.
- B rejected: no collisions but 11 characters (over 8) and guessable by time.
- C works: 62⁸ ≈ 2.2 × 10¹⁴ codes; with 14.6 billion links collisions happen but rarely, and
IF NOT EXISTS+ retry handles them. Token range + Feistel is better when you want 7 characters and never retry.
Exercise 2: A viral link
One link takes 30% of all reads in a campaign's first hour. One Redis node hits 95% CPU. What do you do?
Solution to Exercise 2
A hot key: one key always lives on one node, so adding nodes doesn't help. Add an in-process cache (Caffeine, TTL of a few seconds) in the redirect service: each instance asks Redis only a few times per second for that link. You can also cache the response at the CDN for a few seconds and take click logs from the CDN for analytics.
Summary
- Long URL → unique number → Base62 → 7 characters.
- Token ranges: each instance owns a range, handed out in RAM.
- Shuffle with Feistel so codes are unguessable yet collision-free.
- 302 if you need analytics, 301 if load comes first.
- Dedupe and custom aliases via conditional writes, never lookup-then-write.
Read more: Back-of-the-envelope estimation.
Comments
Community rules