Design a URL Shortener: Base62 IDs, Caching and Redirects
Complete notes on designing a URL shortener: why truncated hashes collide, and how a counter with Base62 encoding, range-based ID allocation and a cache make it scale.
A URL shortener takes a long URL and returns a short one, usually a domain followed by a code of about seven characters. When someone opens the short link, the service looks up the code and redirects the browser to the original address. The short links you see in delivery messages and social posts all work this way.
The product is small, but it touches most of the building blocks of system design: unique ID generation, a read-heavy workload, caching, database choice and HTTP semantics. These notes go through the design in the same order you would present it in an interview: requirements, estimation, API, the core design, scaling and trade-offs.
1. Clarify the requirements
The first step is to agree on what is being built. The requirements below are a reasonable starting set.
- Functional: given a long URL, return a short URL. Opening the short URL redirects the user to the original one.
- Functional (optional, ask first): custom aliases, link expiry, and click analytics.
- Non-functional: redirects must be fast (under roughly 100 ms at the server), the service must be highly available, and a short code must never map to two different URLs.
- Workload: a link is created once and opened many times, so the system is read-heavy. Assume a read-to-write ratio of about 100 to 1.
- Out of scope for now: user accounts, billing, and spam detection.
2. Estimate the scale
The numbers below are assumptions, stated to size the system. Assume 100 million new links per month. That is roughly 40 writes per second on average. With a 100 to 1 ratio, redirects are about 4,000 per second on average and perhaps 10,000 per second at peak.
Each record holds a short code, the long URL, and a few metadata fields, around 500 bytes. One hundred million records a month is about 50 GB per month, or roughly 3 TB over five years. That is comfortably within the range of a sharded key-value store, and it shows that the hard part of this system is not storage but serving reads quickly.
How long should the code be? With 62 possible characters (a to z, A to Z, 0 to 9), seven characters give 62 to the power of 7, which is about 3.5 trillion combinations. At 100 million links a month that lasts for thousands of years, so seven characters is enough.
3. Define the API
Two endpoints carry the whole product.
POST /api/v1/urls
Body: { "longUrl": "https://example.com/some/very/long/path", "expiresAt": null }
Response: 201 Created
{ "shortUrl": "https://sho.rt/aZ3kP9x", "code": "aZ3kP9x" }
GET /{code}
Response: 302 Found
Location: https://example.com/some/very/long/path
404 Not Found (unknown or expired code)4. Why hashing the URL fails
A hash function such as MD5 produces 128 bits. To get a seven-character code you must throw most of those bits away. Once you truncate, two different URLs can produce the same seven characters. This is called a collision, and with billions of links it is not a rare event, it is a certainty.
You can patch it: check the database, and if the code is taken, add a salt and hash again. But now every write needs a read first, the retry loop gets slower as the table fills, and two servers can still race to claim the same code. You have built a slower, more fragile version of a problem that has a clean solution.
5. The right approach: a counter plus Base62
Give every new URL a unique number from a counter, and then write that number in base 62. Because every number is unique, every code is unique. There is no collision to check for, so a write is a single insert.
Base62 is simply a number system with 62 digits. The number 125 in base 62 is '21', because 2 times 62 plus 1 is 125. The encoding is a short loop.
const ALPHABET =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
function encode(id) {
if (id === 0) return ALPHABET[0];
let code = "";
while (id > 0) {
code = ALPHABET[id % 62] + code;
id = Math.floor(id / 62);
}
return code;
}
encode(125); // "21"
encode(3521614606207) // "ZZZZZZZ" -> the largest 7-character code6. High-level design
The write path generates an ID, encodes it, and stores the mapping. The read path looks up the code, first in the cache and then in the database, and returns a redirect.
+------------------+
Client ---> LB ----> | App servers | ----> ID range service
| (stateless) | (hands out blocks of IDs)
+---------+--------+
|
read path | write path
+-----------------------+----------------------+
v v
+--------------+ miss +-----------------------------------+
| Redis cache | -------> | Key-value DB (code -> long URL) |
| code -> URL | <------- | partitioned by code |
+--------------+ fill +-----------------------------------+urls ---------------------------------------------- code VARCHAR(7) PRIMARY KEY long_url TEXT NOT NULL created_at TIMESTAMP expires_at TIMESTAMP NULL owner_id BIGINT NULL
7. Scaling the ID generator: range-based allocation
If every write has to call one central counter, that counter is both a bottleneck and a single point of failure.
The fix is range-based ID allocation. A small coordination service (it can be backed by ZooKeeper, etcd, or a single database row updated in a transaction) hands each app server a block of IDs, for example one million at a time. Server A owns 1 to 1,000,000, server B owns 1,000,001 to 2,000,000. Each server then increments a local in-memory counter with no network call at all. It only talks to the range service again when its block is exhausted.
If a server crashes, the unused IDs in its block are lost. That is acceptable: we have trillions of codes, and wasting a few hundred thousand costs nothing. It is worth stating this explicitly as an accepted trade-off.
8. Serving read-heavy traffic with a cache
A link is written once and may be read millions of times. This is the definition of a read-heavy system, and the standard tool is a cache. Popular codes are kept in Redis using the cache-aside pattern: check the cache, on a miss read the database and populate the cache with a TTL. With a realistic traffic distribution, a small fraction of links receive most of the clicks, so a cache holding the hottest 20 percent absorbs the vast majority of reads and the database sees very little traffic.
For the database itself, the access pattern is a pure key lookup with no joins, so a key-value or wide-column store partitioned by code is a natural fit. A relational database with the code as primary key also works at this scale; what matters is that you justify the choice by the access pattern.
9. Trade-off: 301 or 302 redirect
A 301 (Moved Permanently) response is cached by the browser. The next time the same user opens the link, the browser redirects without contacting our servers, which reduces load. The cost is that we never see that click, so analytics are incomplete, and we cannot change or expire the destination for that user.
A 302 (Found) response is not cached by default, so every click reaches our servers. Load is higher, but we can count every click and we stay in control of the link. If analytics is a requirement, choose 302. If the only goal is minimum load, choose 301. Stating the choice with its reason is worth more than the choice itself.
10. Additional considerations
- Sequential codes are guessable. If that matters, shuffle the ID before encoding (for example with a bijective function such as a Feistel permutation or multiplication by a large odd number modulo 62^7) so that consecutive IDs produce unrelated codes while staying unique.
- Custom aliases: store them in the same table and enforce uniqueness with a conditional insert. Reserve a separate namespace (or a minimum length) so they never collide with generated codes.
- Expiry: store expires_at, check it on read, and delete lazily with a background job. Cache TTL must never exceed the remaining lifetime.
- Same long URL submitted twice: it is fine to return two different codes. De-duplication needs an extra index on the long URL and is rarely worth it.
- Analytics: do not update a counter in the redirect path. Publish a click event to a queue and aggregate asynchronously.
Interview summary
The whole design in five points:
- Requirements: create a short link, redirect, read-heavy traffic, no collisions.
- APIs: POST to shorten, GET on the short code to redirect.
- Unique IDs: counter plus Base62 encoding, with range-based allocation so servers do not share one counter.
- Storage: key-value database for the mapping, Redis cache for hot links.
- Trade-off: 301 reduces load, 302 preserves analytics and control.
Summary
A URL shortener cannot be built on a truncated hash, because truncation creates collisions. Generate a unique number instead, encode it in Base62, distribute ID ranges so no server waits on a shared counter, put a cache in front of a key-value store because reads dominate, and close with the 301 versus 302 trade-off. This is a standard interview design, not a description of any particular company's internal architecture.
Puneet Tiwari
Full Stack Developer
