How do you design a URL shortener?
A counter encoded in base62 gives short, unique codes without collision checks; a cache in front of the database serves almost every redirect. The real decisions are 301 vs 302, how to count clicks without slowing redirects, and how to stop abuse.
The verdict, which we’ll earn piece by piece: the core is small; the details make it work.
- Generate codes from a counter, encoded in base62 (
0-9a-zA-Z). Seven characters give 62⁷ ≈ 3.5 trillion codes, with no collisions to check. Hand each app server a block of IDs so they don’t contend on one counter. - Store
code → long URLin a key-value table, and put a cache in front: redirects are read-heavy and very skewed, so a small cache serves most of them. - Return 302 (or 307) if you need click analytics, 301 if you don’t; browsers cache 301s and stop asking you.
- Count clicks asynchronously: write an event to a queue and aggregate later, so counting never slows a redirect.
- Plan for abuse from day one: malware and phishing links, enumeration of codes, and spam sign-ups.
The URL shortener is the classic interview question, and I think it has lasted because it’s small enough to hold in your head yet full of good ideas. It looks like an open-and-shut case: a table with two columns. Then the questions start. Why did the click counts stop rising? How did someone find a private invoice link by guessing? Why does the database groan when one link goes viral? Let’s work the case, starting with the evidence that matters most: some numbers.
Case file
The case Click counts stop rising, private links get guessed, the database groans on a viral link Suspects Hashing the URL, random codes, a shared counter Culprit 301 caching, guessable sequential codes, a counter row updated on every redirect The fix Permuted counter + base62, a cache in front, 302 and click events through a queue
The first clue: rough numbers #
Say 100 million new links a month and 100 reads per link over its life.
| Quantity | Estimate |
|---|---|
| Writes | 100M / month ≈ 40 per second on average, a few hundred at peak |
| Reads (redirects) | 100 × writes ≈ 4,000 per second, tens of thousands at peak |
| Storage per link | ~500 bytes (code, URL, owner, timestamps) |
| Storage after 5 years | 6 billion links × 500 B ≈ 3 TB |
Back-of-envelope maths shrinks the suspect list quickly: this is a read-heavy key-value lookup. One PostgreSQL or DynamoDB table plus a cache handles it comfortably; the design is about keeping redirects fast and the system safe.
Diagram source
flowchart LR
U[Browser] -->|GET /aZ3kQ9x| LB[Load balancer / CDN]
LB --> APP[Redirect service]
APP -->|1. lookup| C[(Cache)]
APP -->|2. on miss| DB[(code → URL table)]
APP -->|3. click event| Q[[Queue]]
Q --> AGG[Click aggregator] --> A[(Analytics store)]
APP -->|302 Location: long URL| U
The suspects: generating the short code #
There are four reasonable ways to do it, and each one has a weakness worth questioning.
| Approach | How | Pros | Cons |
|---|---|---|---|
| Hash the URL (MD5/SHA, take 7 chars) | base62(sha256(url))[:7] |
Same URL gets the same code | Collisions must be checked and resolved; same URL from two users shares stats |
| Random code | 7 random base62 characters | Unguessable; no coordination | Collision check on every insert (rare, but needs a unique index and a retry) |
| Counter + base62 | Next ID from a sequence, encoded | No collisions, shortest codes | Sequential codes are guessable; needs a shared counter |
| Pre-generated keys | A key service hands out unused random codes in batches | No collision checks at write time; unguessable | Another service to run |
What I’d use: a counter for simplicity, with two adjustments.
- Block allocation: each app server reserves 1,000 IDs at a time (
UPDATE counters SET next = next + 1000 RETURNING next), so the shared counter is touched rarely. - Codes that don’t reveal order: pass the ID through a reversible permutation (for example a small Feistel network, or a block cipher over the ID) before encoding. Codes still never collide, but nobody can walk through
aZ3kQ9x,aZ3kQ9y, … to find other people’s links. This is the reveal I love in this case: because the permutation is reversible, uniqueness comes for free, and the codes only look random. One small function quietly removes both the collision check and the enumeration problem.
Permuted codes still fill the code space densely, so if links can be private (documents, invoices), use random codes of 8+ characters with a unique index instead, and make enumeration expensive with rate limits.
Clue: where the reads really go #
With 100 reads per link, redirects are where the pressure lands. Skew is our friend here:
- Cache: keep hot codes in Redis or in-process; link popularity is skewed, so a cache holding 1% of links served about half of all requests in my measurement (Zipf-distributed traffic, s = 0.9), and more when popularity is more concentrated. The cache eviction post measures how much the eviction policy matters.
- CDN: for public links, cache the redirect response itself at the edge for a short time.
- Database: a primary-key lookup by code. Partition by code if one table gets too big; nothing ever needs to join across codes.
The red herring: 301 or 302? #
One status code, and a big decision hiding in it. 301 looks like the obvious, efficient choice, and that’s exactly what makes it the classic false lead: it’s also why click counts quietly stop.
| Status | Meaning | Effect |
|---|---|---|
| 301 Moved Permanently | Browsers and crawlers may cache it indefinitely | Fewer requests; you lose click counts after the first visit; you can’t change the destination later |
| 302 Found / 307 Temporary Redirect | Not cached by default | Every click reaches you: analytics, expiry, editing and abuse takedowns all work |
Most commercial shorteners use 302 or 307 for that reason. Add Cache-Control: private, max-age=… if you want a middle ground.
The viral link #
Counting sounds trivial until a link goes viral. Never update a counter row on every redirect: hot links would turn into lock contention. Instead:
- The redirect service publishes a small event (code, time, referrer, country from the IP, user-agent class) to a queue and returns immediately.
- A consumer aggregates per code per minute and writes the totals.
- For unique visitors, keep a HyperLogLog per code per day instead of storing every visitor ID (the HyperLogLog post).
The other villains: abuse and safety #
A shortener hides destinations by design, which is exactly what attackers want too.
- Check destinations against safe-browsing lists at creation and periodically after; disable links that turn malicious.
- Rate-limit creation per account and per IP (rate-limiting post).
- Don’t allow redirect loops to your own domain, or
javascript:anddata:URLs. - Show a preview page (add
+to the code, for example) so people can see where a link goes.
Similar cases, different motives #
The same building blocks, weighted differently depending on who clicks.
| Situation | What I’d use |
|---|---|
| Public shortener (anyone can create links) | Permuted counter codes, a CDN in front of redirects, 302s, and abuse controls on day one: safe-browsing checks, creation rate limits, a preview page |
| Links in marketing emails (one company, millions of clicks in a burst) | Codes created ahead of the send, cached before it goes out; click events through a queue so a burst never touches the main database; 302 so campaign stats stay complete |
Internal links (go/wiki-style, behind sign-in) |
Human-chosen names instead of generated codes, a plain table, no CDN; access checks on the redirect, because the destination may be private |
| Private document or invoice links | Random codes of 8+ characters, an expiry date, and rate limits on lookups, so guessing is too slow to pay off |
Remember this
- A counter in base62, passed through a reversible permutation: unique and unguessable-looking.
- 302 keeps every click reaching you; 301 quietly ends your analytics.
- Never count clicks on the redirect path: publish an event and aggregate later.
Case closed: what I’d do by default #
- Counter + base62 with block allocation, permuted so codes don’t reveal order; random codes of 8+ characters for links that must stay private.
- Key-value table with the code as primary key, cache in front, CDN for public links.
- 302 or 307, and click events through a queue.
- HyperLogLog for unique visitors, aggregated per day.
- Abuse controls before launch, not after the first phishing campaign.
A URL shortener is a tiny product with a lot of computer science packed inside it: number bases, permutations, caching curves, probabilistic counting. What I admire is how each one solves its piece of the mystery cheaply, and how neatly they fit together once you see them side by side.
Comments
No comments yet.
Sign in to comment. We'll email you a link; no password needed.