How a URL shortener works
Sunil Tiwari · Oct 12, 2026 · 5 min read
System design walkthrough: requirements, ID generation, caching and the redirect path.
A URL shortener turns https://example.com/a/very/long/path?ref=newsletter into sho.rt/aZ3kQ9x and sends anyone who opens the short link to the long one. It is a two-endpoint product, and still one of the best tours of read-heavy system design: capacity estimates, ID generation, caching, and the small HTTP details that decide whether your analytics work.
Requirements
Functional
- Create a short link for a long URL, with an optional custom alias and expiry date.
- Redirect
GET /<code>to the original URL. - Count clicks per link (by day, country, referrer).
Non-functional
- Redirects are fast: under 50 ms at p99, measured at the server.
- Highly available. A broken redirect breaks someone else's page, email or printed QR code.
- Codes never collide and never change once issued.
Back-of-the-envelope
Assume 100 million new links a month and about 100 reads for every write.
Those are averages. Plan for peaks of 5 to 10 times that, so roughly 40,000 redirects per second at the top.
| Quantity | Estimate |
| Links after 10 years | 100M×12×10=1.2×1010 |
| Size of one row (code, URL, metadata) | about 500 bytes |
| Total storage | 1.2×1010×500 B≈6 TB |
| Hot set worth caching (10M links) | about 5 GB, fits one Redis node |
How long must the code be? With the 62 characters [0-9a-zA-Z] and length k there are 62k possible codes:
Six characters already cover ten years of links. Seven leaves room for nearly 3,000 years at this rate, or for growth well beyond the estimate, at the cost of one extra character.
The architecture
Two services share one data model. The Links API handles the rare writes. The Redirect service handles the flood of reads and is built to answer almost everything from memory.

Everything in the app tier is stateless, so you scale it by adding servers behind the load balancer. State lives in three places: the links table (source of truth), Redis (a copy of the hot part) and the analytics store (clicks, written asynchronously).
Creating a link

The interesting decision is where the code comes from. There are three common options:
| Approach | How it works | Problem |
| Hash the URL | base62(md5(url))[:7] | Collisions. You must check and retry, and two users shortening the same URL get the same code (and share its analytics). |
| Random code | 7 random base62 characters | Also collides eventually, every insert needs a uniqueness check. |
| Counter + base62 | Unique integer ID, encoded in base62 | Needs a source of unique IDs. No collisions by construction. |
The counter wins. Encoding is a few lines:
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def base62(n: int) -> str:
if n == 0:
return ALPHABET[0]
out = []
while n:
n, r = divmod(n, 62)
out.append(ALPHABET[r])
return "".join(reversed(out))
base62(4_814_007) # 'kclh'Custom aliases skip the counter and go straight to the insert. A unique index on code makes "is this alias free?" and "save it" one atomic step: if the insert fails on the constraint, return 409.
Handing out IDs without a bottleneck
A single counter that every write must call is a single point of failure and a round trip per link. The fix is to hand out blocks. Each app server asks the ID service for a range of 1,000 numbers, then issues IDs from memory until the range runs out.

At 40 writes per second, a block of 1,000 lasts each server a minute or more, so the ID service sees a handful of requests a minute. If a server crashes, the unused part of its block is simply skipped. Gaps are harmless, duplicates are not.
One side effect: sequential IDs make codes guessable (kclh, kcli, kclj…). If links should not be enumerable, scramble the integer before encoding with a reversible permutation, for example multiplying by a large odd constant modulo 627, or use a library such as Sqids.
The redirect path
The hot path is one cache lookup. Only misses touch the database, and the result is cached for next time.

Because links almost never change after creation, the cache stays correct with a simple TTL. Deleting or expiring a link needs one extra step: delete its cache key too.
Trade-offs worth discussing
- 301 or 302. A 301 (permanent) is cached by browsers, so repeat visits never reach you. That saves load but loses those clicks from analytics, and you can never change the destination for that browser. Most shorteners use 302 (or 307) and set a short
Cache-Controlso the CDN absorbs bursts. - Analytics off the hot path. Publishing the click event is fire and forget. If the queue is slow, the redirect still returns immediately. You lose a few clicks in an outage instead of losing redirects.
- Viral links. A single link getting millions of hits is one Redis key on one shard. Keep a small in-process LRU cache in front of Redis, or let the CDN cache the 302 for a few seconds.
- Abuse. Shorteners are a favourite tool for hiding phishing URLs. Check new links against a blocklist (for example Google Safe Browsing) and rate-limit creation per account and per IP.
- Database choice. The access pattern is pure key-value (
codetolong_url), so a sharded key-value store works as well as Postgres. Shard bycodeand every lookup hits exactly one shard.
The canvas next to this note has the whole design on one page. Drag it, zoom into a figure, or open it full screen.