Octonote AI
Make your own →

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.

100×10630×24×3600 s≈39 writes/s⇒≈3,900 reads/s\frac{100 \times 10^{6}}{30 \times 24 \times 3600\ \text{s}} \approx 39\ \text{writes/s} \qquad\Rightarrow\qquad \approx 3{,}900\ \text{reads/s}

Those are averages. Plan for peaks of 5 to 10 times that, so roughly 40,000 redirects per second at the top.

QuantityEstimate
Links after 10 years100M×12×10=1.2×1010100\text{M} \times 12 \times 10 = 1.2 \times 10^{10}
Size of one row (code, URL, metadata)about 500 bytes
Total storage1.2×1010×500 B≈6 TB1.2 \times 10^{10} \times 500\ \text{B} \approx 6\ \text{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 kk there are 62k62^k possible codes:

626≈5.7×1010627≈3.5×101262^{6} \approx 5.7 \times 10^{10} \qquad 62^{7} \approx 3.5 \times 10^{12}

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.

URL shortener at a glance
URL shortener at a glance

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

Creating a short link
Creating a short link

The interesting decision is where the code comes from. There are three common options:

ApproachHow it worksProblem
Hash the URLbase62(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 code7 random base62 charactersAlso collides eventually, every insert needs a uniqueness check.
Counter + base62Unique integer ID, encoded in base62Needs 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.

Handing out IDs without a bottleneck
Handing out IDs without a bottleneck

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 62762^7, 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.

The redirect path
The redirect path

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-Control so 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 (code to long_url), so a sharded key-value store works as well as Postgres. Shard by code and 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.
Make a page like this. Free.Notes and diagrams side by side, written by you or by Claude Code and Codex. Publish it in one click.
Make your own, free