Designing a URL Shortener: System Design Explained

Introduction:
“Design a URL shortener” is one of the most popular system design interview questions, and a great first real-world design to learn from. The product looks tiny: you paste a long link and get a short one like sho.rt/4c92. But behind it are many of the ideas we covered in earlier lessons: rate limiting, database sharding, caching and unique ID generation.
In this lesson we will design one step by step, the same way you would in an interview: requirements, estimates, the API, how to make short codes, the database, redirects, and then how to scale it. The code samples are in Node.js and every output shown was produced by running them.
Step 1: Requirements
Always start by agreeing on what the system must do.
1. Functional requirements:
- Given a long URL, create a short URL.
- Visiting the short URL redirects to the long URL.
- Optional: the user can pick a custom alias (like
/diwali-sale). - Optional: links can expire, and we count clicks.
2. Non-functional requirements:
- Very fast redirects. A redirect should take a few milliseconds. People click links on slow phones.
- Highly available. If redirects are down, every link ever shared is broken.
- Short codes must be unique and should not be easy to guess one after another.
- Read-heavy. A link is created once and clicked many times.
Step 2: Back-of-the-Envelope Estimates
Let’s assume:
- 100 million new links per month
- A 100 : 1 read to write ratio, so 10 billion redirects per month
- We keep links for 5 years
Now the numbers:
- Writes: 100M / (30 × 24 × 3600) ≈ 40 new links per second
- Reads: 40 × 100 ≈ 4,000 redirects per second on average, maybe 20,000 at peak
- Total links in 5 years: 100M × 12 × 5 = 6 billion
- Storage: about 500 bytes per link (URL, code, dates, owner) × 6 billion ≈ 3 TB
Two important conclusions: we need room for 6 billion unique codes, and the redirect path (reads) is where the performance work must go.
Step 3: The API
POST /api/links
Body: { "url": "https://example.com/very/long/path", "alias": "optional" }
-> 201 { "code": "4c92", "shortUrl": "https://sho.rt/4c92" }
GET /{code}
-> 302 redirect, header Location: https://example.com/very/long/path
-> 404 if the code does not exist
GET /api/links/{code}
-> 200 { "url": ..., "clicks": ..., "createdAt": ... }
In a real product, the create and stats APIs need a logged-in user (see Authentication with JWT in Node.js) and a rate limit, so nobody can create millions of spam links.
Step 4: How Long Should the Code Be?
Short codes use Base62: the digits 0–9, the letters a–z and A–Z. These are all safe in a URL. Each extra character multiplies the number of possible codes by 62:
for (const n of [1, 2, 3, 4, 5, 6, 7]) console.log(n, (62 ** n).toLocaleString("en-US"));
// 1 62
// 2 3,844
// 3 238,328
// 4 14,776,336
// 5 916,132,832
// 6 56,800,235,584
// 7 3,521,614,606,208
We need 6 billion codes. Six characters give about 56 billion, which is enough, and seven characters give 3.5 trillion, which is plenty of room to grow. Most real shorteners use 6 to 8 characters.
Step 5: Generating the Short Code
This is the heart of the design. There are three common approaches.
1. Hash the URL:
Take a hash of the long URL (like SHA-256) and keep the first 7 characters:
const crypto = require("node:crypto");
const hashCode = (url) => crypto.createHash("sha256").update(url).digest("base64url").slice(0, 7);
console.log(hashCode("https://example.com/blog/a-very-long-article?utm_source=x")); // w9LFrjY
console.log(hashCode("https://example.com/blog/a-very-long-article?utm_source=x")); // w9LFrjY
console.log(hashCode("https://example.com/blog/a-very-long-article?utm_source=y")); // 2bAkC4g
The good part: the same URL always gives the same code, so you can avoid duplicates. The problem is collisions. Two different URLs can produce the same 7 characters. Because of the “birthday problem”, collisions arrive much sooner than you would expect. With 7 Base64 characters there are about 4.4 trillion possible codes, but after only 1 million links the chance that at least one pair collided is already about 11%, and after 10 million it is practically 100%.
So with hashing, every insert must check “does this code already exist?” and, if so, try again with a changed input. That extra database lookup on every write gets slower as the table grows.
2. A counter + Base62 (recommended):
Give every new link a unique number from a counter (1,000,000, then 1,000,001, …) and convert that number to Base62:
const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function encode(num) {
if (num === 0) return ALPHABET[0];
let code = "";
while (num > 0) {
code = ALPHABET[num % 62] + code;
num = Math.floor(num / 62);
}
return code;
}
function decode(code) {
let num = 0;
for (const ch of code) num = num * 62 + ALPHABET.indexOf(ch);
return num;
}
console.log(encode(125), encode(1000000), encode(3521614606207)); // 21 4c92 ZZZZZZZ
console.log(decode("cb"), decode("4c92")); // 755 1000000
Every number is different, so every code is different: no collisions, ever, and no lookup before inserting.
The catch is that sequential codes are guessable. If your link is 4c92, someone can try 4c93 and see other people’s links. Fixes:
- Shuffle the ID before encoding (for example, multiply it by a large prime modulo 62⁷, or use a library like Sqids). Codes then look random but are still unique.
- Never put private documents behind a short link alone.
3. Pre-generated keys (Key Generation Service):
A separate service creates millions of random unused codes ahead of time and stores them in a “free keys” table. When a link is created, the app takes one free key and marks it as used. It has no collisions and no guessable order, at the cost of one more service to run.
Getting unique IDs on many servers:
One database counter becomes a bottleneck when many app servers create links. Common solutions:
- Ranges: each app server asks a central store (like Redis
INCRBYor ZooKeeper) for a block of 1,000 IDs, and hands them out from memory. If a server crashes, a few IDs are skipped, which is fine. - Snowflake-style IDs: each server builds IDs from the time, its own machine number and a small sequence, with no coordination at all. The codes are a bit longer.
Step 6: The Data Model
The main table is simple:
CREATE TABLE links (
code VARCHAR(10) PRIMARY KEY,
long_url TEXT NOT NULL,
user_id BIGINT,
created_at TIMESTAMP NOT NULL DEFAULT now(),
expires_at TIMESTAMP,
is_active BOOLEAN NOT NULL DEFAULT true
);
The redirect path does exactly one thing: find a row by its code. That is a perfect fit for a key-value lookup, so both a SQL database (with code as the primary key) and a NoSQL store like DynamoDB or Cassandra work well. With 3 TB of data, we will shard by code (a hash of the code decides the shard), so every redirect goes to exactly one shard.
Clicks are stored separately, as we will see in Step 9.
Step 7: A Working Version in Node.js
Here is a small but complete shortener with Express, using the counter + Base62 approach and an in-memory Map in place of the database:
const express = require("express");
const { encode } = require("./base62");
const app = express();
app.use(express.json());
const links = new Map(); // code -> { url, clicks, createdAt }
let nextId = 1_000_000; // start high so codes are not "1", "2", "3"
const RESERVED = new Set(["api", "admin", "login"]);
function isValidUrl(value) {
try {
const u = new URL(value);
return u.protocol === "http:" || u.protocol === "https:";
} catch {
return false;
}
}
app.post("/api/links", (req, res) => {
const { url, alias } = req.body ?? {};
if (!isValidUrl(url)) return res.status(400).json({ error: "Please send a valid http(s) URL" });
let code;
if (alias) {
if (!/^[a-zA-Z0-9-]{3,30}$/.test(alias) || RESERVED.has(alias)) {
return res.status(400).json({ error: "Alias must be 3-30 letters, digits or dashes" });
}
if (links.has(alias)) return res.status(409).json({ error: "Alias already taken" });
code = alias;
} else {
code = encode(nextId++);
}
links.set(code, { url, clicks: 0, createdAt: new Date().toISOString() });
res.status(201).json({ code, shortUrl: `${req.protocol}://${req.get("host")}/${code}` });
});
app.get("/api/links/:code", (req, res) => {
const link = links.get(req.params.code);
if (!link) return res.status(404).json({ error: "Not found" });
res.json({ code: req.params.code, ...link });
});
app.get("/:code", (req, res) => {
const link = links.get(req.params.code);
if (!link) return res.status(404).send("Short link not found");
link.clicks++;
res.redirect(302, link.url);
});
app.listen(3000);
Testing it with fetch gave these results:
POST url=https://blog.khanwaseem.com/greedy-algorithms/ -> 201 { code: '4c92' }
POST url=https://example.com/very/long/path?x=1 -> 201 { code: '4c93' }
POST alias=diwali-sale -> 201 { code: 'diwali-sale' }
POST alias=diwali-sale (again) -> 409 Alias already taken
POST url=javascript:alert(1) -> 400 Please send a valid http(s) URL
POST alias=api -> 400 Alias must be 3-30 letters, digits or dashes
GET /4c92 -> 302, Location: https://blog.khanwaseem.com/greedy-algorithms/
GET /api/links/4c92 (after 2 visits) -> { clicks: 2, ... }
GET /nope -> 404 Short link not found
Notice the URL check. Without it, someone could shorten a javascript: link, which is a security hole. Real services also check new links against lists of known phishing and malware sites.
Step 8: 301 or 302 Redirect?
This small choice matters a lot:
- 301 (Moved Permanently): the browser caches the redirect. The next click on the same device goes straight to the long URL, without touching our server. Less load, but we can no longer count clicks or change the destination.
- 302 (Found, temporary): the browser asks our server every time. A bit more load, but every click is counted and the owner can change where the link goes later.
Most commercial shorteners use 302 (or 307), because analytics and editable links are the product. A real example is the Eskillsfy URL Shortener, which lets you change a link’s destination after sharing it and counts clicks by day, country, device and referrer. Both features are only possible because every click goes through its server.
Step 9: Scaling the Redirect Path
With 4,000 to 20,000 redirects per second, the read path needs care.
1. Cache hot links:
Link traffic is very uneven: a link shared by a celebrity may get millions of clicks while most links get a handful. Put a cache like Redis in front of the database: look up the code in Redis first, and only go to the database on a miss (the cache-aside pattern). Even a small cache holding the most popular 20% of links can serve most of the traffic, because hot links take most of the clicks.
2. Many stateless app servers:
The redirect servers keep no state, so a load balancer can spread traffic across as many of them as needed.
3. Database replicas and shards:
Use read replicas for extra read capacity, and shard by code as described above.
4. CDN or edge redirects:
Very popular links can even be redirected at the edge (a CDN or edge function), close to the user.
5. Don’t count clicks inside the redirect:
Writing to the database on every click would slow every redirect. Instead, the redirect server pushes a small event (code, time, country, device, referrer) to a message queue like Kafka and returns the redirect immediately. Separate workers read the queue and update the analytics store in batches. This is also where you filter out link-preview bots, so a WhatsApp or Slack preview is not counted as a click.
Step 10: Other Details Interviewers Ask About
- Same URL twice: Should two users shortening the same URL get the same code? Usually no, because each user wants their own click statistics. Per-user de-duplication is a nice extra.
- Expiry and deletion: Store
expires_atand check it on redirect. A background job can clean up expired rows. Many services never reuse old codes, so a printed link can never start pointing somewhere unexpected. - Abuse: Rate limit link creation per user and IP, scan URLs for phishing, and let admins disable a link (
is_active = false). - Custom domains: Businesses want
go.mybrand.com/sale. The domain becomes part of the key.
The Final Design:
+-------------+
Browser ---> | Load | ---> App servers (stateless)
| balancer | | | \
+-------------+ v v v
Redis Database Message queue
cache (sharded (click events)
by code) |
v
Analytics workers
-> analytics DB
ID ranges from a central counter (Redis INCRBY / ZooKeeper) -> Base62 codes
Conclusion:
A URL shortener is simple on the surface, but it touches almost every core system design idea. We estimated about 6 billion links and 4,000+ redirects per second, chose counter + Base62 codes (unique by design, no collision checks, shuffled so they are not guessable), stored links in a key-value friendly table sharded by code, used 302 redirects so clicks can be counted and destinations changed, put Redis in front of the database for hot links, and moved click tracking to a message queue so redirects stay fast.
In the next System Design lesson, we will look closer at that last piece: Message Queues Explained.


