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.
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).
| Quantity | Math | Result |
|---|---|---|
| Write QPS | 10M / 86,400 s | about 115/s (peak 2–3x, about 300/s) |
| Read QPS | 115 × 100 | about 11,500/s (peak about 30,000/s) |
| Row size | key + long URL + metadata | about 500 bytes |
| Storage per year | 10M × 365 × 500 B | about 1.8 TB |
| Links in 5 years | 10M × 365 × 5 | about 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.
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=mailPlus 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).
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.
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.
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:
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.
| Approach | Collisions | Coordination | Guessable | Notes |
|---|---|---|---|---|
| Counter + base62 | None | Every write hits the counter | Yes | Simplest; counter is a hotspot |
| Hash + truncate | Yes, must check and retry | None | No | Dedupes identical URLs |
| Key ranges (KGS) | None | Once per 1,000+ keys | No, if shuffled | The usual interview 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 goal to the choice.
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 the redirect request in order.
- Tap the steps below in the right order.
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
302responses 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.
- 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.