Skip to content

Lesson 22 of 38Case studies

Design a URL Shortener

Design a TinyURL-style service end to end, from short key generation to caching redirects and counting clicks.

18 min read0/5 questions

The URL shortener is the "hello world" of system design interviews. It looks tiny, but it touches every building block you just learned: key generation, a read-heavy cache, a database that grows forever, and an async pipeline for analytics. Nail this one and you have a template for every case study after it.

We will use the same framework in every case study: requirements, numbers, API, data model, high-level design, deep dives, then bottlenecks and scaling.

Requirements

Start every design by agreeing on scope out loud. An interviewer wants to see you ask before you draw.

Functional

  • Given a long URL, return a short one like sho.rt/aZ3kP9q.
  • Visiting the short URL redirects to the long one.
  • Optional custom alias (sho.rt/launch-day) and an optional expiry date.
  • Basic click analytics per link (count, country, referrer).

Non-functional

  • Redirects must be fast: under 50 ms at the server, because they sit in front of every click.
  • Highly available. A broken shortener breaks every link ever shared.
  • Short keys must never collide. Two long URLs must never get the same key.
  • Keys should not be guessable in order (so people cannot scrape every link).

Out of scope: user accounts beyond an API key, link previews, editing a link after creation, spam detection (we mention it, we do not build it).

Back-of-the-envelope numbers

Assume 10 million new links per day and a read to write ratio of 100 to 1 (links are created once and clicked many times).

QuantityMathResult
Write QPS10M / 86,400 sabout 115/s (peak 2–3x, about 300/s)
Read QPS115 × 100about 11,500/s (peak about 30,000/s)
Row sizekey + long URL + metadataabout 500 bytes
Storage per year10M × 365 × 500 Babout 1.8 TB
Links in 5 years10M × 365 × 5about 18 billion

Two conclusions fall out of this table. The system is read-heavy, so caching redirects is the main lever. And we need room for at least 18 billion keys, which decides the key length below.

Quick check
Keys use 62 characters (a–z, A–Z, 0–9). What is the shortest key length that fits 18 billion links with plenty of headroom?
Need a nudge? A hint rules out a wrong answer.

API

Two endpoints do almost all the work.

POST /api/v1/urls
Authorization: Bearer <api-key>
{ "long_url": "https://example.com/very/long/path?ref=mail", "alias": null, "expires_at": "2027-01-01" }
 
201 Created
{ "short_url": "https://sho.rt/aZ3kP9q", "key": "aZ3kP9q" }
GET /aZ3kP9q
 
302 Found
Location: https://example.com/very/long/path?ref=mail

Plus GET /api/v1/urls/{key}/stats for analytics. If the key does not exist or has expired, the redirect returns 404 (or 410 Gone for expired links).

Data model

The core table is a key-value lookup, which is exactly what you want for a read path that must be fast.

CREATE TABLE urls (
  key        VARCHAR(10) PRIMARY KEY,   -- "aZ3kP9q"
  long_url   TEXT        NOT NULL,
  owner_id   BIGINT,
  created_at TIMESTAMPTZ NOT NULL,
  expires_at TIMESTAMPTZ
);

Every read is WHERE key = ?, a primary key lookup. There are no joins and no range queries, so this table shards cleanly by key across many nodes. A key-value store such as DynamoDB or Cassandra fits as well as Postgres; at 1.8 TB a year, you will shard eventually either way.

Clicks go to a separate clicks table (or an analytics store like ClickHouse) as an append-only log: key, ts, country, referrer, user_agent. We keep it apart because it receives one row per click, 100x the write volume of urls.

High-level design

Step through the two paths: creating a link (write) and following one (read).

URL shortener architecture
Stateless servicesAsync analyticsBrowserBrowserLoad bal.: L7Load bal.L7Write API: POST /urlsWrite APIPOST /urlsRedirect: GET /:keyRedirectGET /:keyKey service: key rangesKey servicekey rangesRedis: key → urlRediskey → urlURL store: shardedURL storeshardedClick queue: KafkaClick queueKafkaAggregatorAggregatorAnalytics: ClickHouseAnalyticsClickHouseHTTPSnext keyINSERTGETon missclickbatch

Write path. POST /api/v1/urls hits the load balancer, which routes it to any Write API instance. They are stateless, so any one will do.

1/8
Quick check
Redirects are read 100x more than links are created, and 20% of links get 80% of clicks. What should you cache?
Need a nudge? A hint rules out a wrong answer.

Deep dive 1: generating the short key

This is the part interviewers care about most. There are three classic approaches.

A. Counter plus base62. Keep a global counter. Link number 1 gets 1, link number 125 gets 21. Encode the number in base 62 (digits, lower case, upper case) so it stays short. No collisions are possible, because every number is unique.

Here is the encoder. Run it, then try a larger number.

Pythonbase62.py
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" def encode(n: int) -> str: if n == 0: return ALPHABET[0] chars = [] while n > 0: n, rem = divmod(n, 62) chars.append(ALPHABET[rem]) return "".join(reversed(chars)) def decode(s: str) -> int: n = 0 for ch in s: n = n * 62 + ALPHABET.index(ch) return n for n in [1, 61, 62, 125, 3_500_000_000_000]: key = encode(n) print(n, "->", key, "->", decode(key))
Output
Press Run (⌘ Enter) to see what happens.

The catch: sequential keys are guessable (aZ3kP9q is followed by aZ3kP9r), and a single global counter is a bottleneck and a single point of failure.

B. Hash the URL. Take md5(long_url) or SHA-256, encode it in base62, keep the first 7 characters. The same URL always gets the same key, which is nice for deduplication. But truncating a hash means collisions: two different URLs can share the first 7 characters. You must check the database on every write and retry with a salt when you hit one.

Collisions arrive far sooner than intuition says (the birthday paradox). This shrinks the key to 3 characters so you can watch it happen:

Pythoncollisions.py
import hashlib ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" def short_hash(url: str, length: int) -> str: n = int(hashlib.sha256(url.encode()).hexdigest(), 16) out = [] for _ in range(length): n, rem = divmod(n, 62) out.append(ALPHABET[rem]) return "".join(out) seen = {}for i in range(100_000): url = f"https://example.com/page/{i}" key = short_hash(url, 3) # only 62**3 = 238,328 possible keys if key in seen: print(f"collision after {i + 1} URLs: {key}") print(" ", seen[key]) print(" ", url) break seen[key] = url
Output
Press Run (⌘ Enter) to see what happens.

C. Pre-generated keys (a key generation service). A separate service hands out ranges of counter values: server A gets 1,000,000 to 1,999,999, server B gets 2,000,000 to 2,999,999. Each server encodes its own range locally with no coordination per request. To stop keys being guessable, run each number through a reversible shuffle (for example, multiply by a large odd constant modulo 62⁷) before encoding.

ApproachCollisionsCoordinationGuessableNotes
Counter + base62NoneEvery write hits the counterYesSimplest; counter is a hotspot
Hash + truncateYes, must check and retryNoneNoDedupes identical URLs
Key ranges (KGS)NoneOnce per 1,000+ keysNo, if shuffledThe usual interview answer
Quick check
A Write API server took the range 4,000,000 to 4,999,999 and crashed after using 300 keys. What happens to the other 999,700 keys?
Need a nudge? A hint rules out a wrong answer.

Deep dive 2: 301 or 302?

Both status codes redirect the browser. The difference is caching.

  • 301 Moved Permanently: the browser caches the redirect. The second click never reaches your servers. Less load, but you lose analytics for repeat clicks, and you cannot change or expire the link for that browser.
  • 302 Found (or 307): the browser asks you every time. More load, but every click is counted and expiry works.

Most commercial shorteners use 302 because analytics is the product. A shortener that only cares about cost would pick 301.

Match the pairs0/4 matched

Match the goal to the choice.

Choose an item, then its match on the other side.

Deep dive 3: analytics without slowing redirects

If the redirect handler did UPDATE urls SET clicks = clicks + 1 on every request, a viral link would hammer one row with 10,000 writes a second. Row locks would turn the fastest endpoint into the slowest.

Instead the Redirect service publishes a click event to a queue and returns immediately. Aggregator workers read events in batches, group them by key and minute, and write one row per group. Ten thousand clicks become a single +10000 write.

Put it in order5 steps

Put the redirect request in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Bottlenecks, failures, and 10x scale

  • Cache failure. If Redis dies, 30,000 reads a second fall onto the database. Run Redis with replicas, and keep a small in-process LRU in each Redirect server as a second layer.
  • Hot keys. A link shared during a sporting final can get 100,000 clicks a second. The in-process cache and a CDN in front of redirects (cache 302 responses for a few seconds) absorb it.
  • Key service outage. Each Write API holds a buffer of keys, so it can keep creating links for minutes while the key service recovers. Run the key service with a leader and a standby.
  • Abuse. Rate-limit link creation per API key, and check new URLs against a malware blocklist.
  • 10x growth (100M links a day, 300,000 reads a second): add Redirect servers (stateless), add Redis shards, add database shards by key. The design does not change, which is the sign of a good one. Move redirects to edge functions on the CDN so most clicks never leave the user's region.
Key terms
base62
Encoding a number with the 62 characters 0–9, a–z, A–Z. Seven characters cover about 3.5 trillion values.
key generation service
A service that hands out ranges of unique IDs so app servers can mint keys locally without colliding.
birthday paradox
Random values collide much sooner than expected: around the square root of the key space, not near its size.
301 vs 302
301 is permanent and cached by browsers; 302 is temporary, so every click reaches the server.
read-heavy
A workload where reads vastly outnumber writes, so caching the read path gives the biggest win.