System Design - URL Shortener
A short URL service end to end: base62 code generation, storage, caching, and redirects.
A URL shortener is a tiny dictionary with a twist. Writes are rare - someone pastes a long link and gets a short code back. Reads are constant - anyone clicking that code needs to be bounced to the original instantly. So the whole design is: mint a unique code cheaply, store one small row, and make the hot read path as close to O(1) as possible.
Builds on
- Caching — the redirect path is dominated by a cache hit.
- Horizontal scaling — a billion rows means sharding the mapping table.
What a URL shortener is
A URL shortener turns a long link into a short code (bit.ly/2xKf style) and, when someone visits that code, sends them to the original URL. bit.ly and t.co are the familiar examples. Imagine pasting a 300-character link with tracking parameters into a text message or a tweet. It is ugly, it breaks across lines, and it eats your character limit. A short link fixes all three problems.
From the outside it looks trivial: one box to paste a link, one link back. That is why it is the most common first system design interview question. It is small enough to finish in 45 minutes, but it touches every important idea: estimation, unique ID generation, storage choices, caching, the read-versus-write imbalance, and abuse. If you understand this lesson well, you have a template for many other designs.
| Component | Job |
|---|---|
| load balancer | Spread requests across API replicas |
| API service | Handles 'shorten' (write) and 'redirect' (read) |
| ID generator | Mints unique short codes |
| Database | Stores the shortCode → longUrl mapping |
| Cache | Serves hot lookups before the DB |
Requirements: what are we building?
Before drawing anything, an interviewer expects you to ask questions and write down what the system must do. These are the functional requirements (what it does) and the non-functional requirements (how well it does it). Stating them takes two minutes and prevents you from designing the wrong thing for forty.
| Type | Requirement | Why it matters |
|---|---|---|
| Functional | Given a long URL, return a short one | The core write path |
| Functional | Given a short code, redirect to the long URL | The core read path |
| Functional | Optional custom alias (e.g. /summer-sale) | Needs an atomic availability check |
| Functional | Optional expiry date; delete a link | Needs a TTL and a delete path |
| Non-functional | Redirect latency under about 100 ms | Redirects are on every click |
| Non-functional | High availability (99.9% or better) | A dead shortener breaks every link ever shared |
| Non-functional | Codes must not be guessable in order | Privacy: stop people scanning /1, /2, /3 |
| Out of scope (say so) | Full analytics dashboards, user accounts, billing | Mention as extensions, do not design them yet |
Check yourself
Which requirement is most critical for the redirect path?
Reads massively outnumber writes
Someone shortens a link once, but hundreds of thousands of people may click it. A real service runs at roughly 100 reads for every 1 write - often far more skewed for a viral link. That one ratio drives every decision after it.
| Path | Frequency | Latency requirement |
|---|---|---|
| Write (shorten) | ~1× | Hundreds of ms is fine |
| Read (redirect) | ~100× | Must be as fast as possible |
Systems like this are read-heavy, and read-heavy systems are cheap to scale: you can copy data into caches and replicas freely, because the data almost never changes after it is written. Once a short code points to a long URL, that mapping is effectively immutable. Immutable data is the easiest kind to cache, because there is nothing to invalidate.
Back-of-the-envelope numbers
Assume a popular service creates 100 million new short links per month, with a 100:1 read-to-write ratio. Work through the arithmetic out loud. Interviewers care that the method is sound, not that the digits are exact.
| Quantity | Calculation | Result |
|---|---|---|
| Write QPS (queries per second) | 100M ÷ (30 days × 86,400 s) = 100M ÷ 2.6M | about 40 per second |
| Average read QPS | 40 × 100 | about 4,000 per second |
| Peak read QPS | 10× the average for viral spikes | about 40,000 per second |
| Links per year | 100M × 12 | 1.2 billion |
| Links over 5 years | 1.2B × 5 | 6 billion |
| Storage per record | 7-char code + ~200-char URL + metadata | about 500 bytes |
| Storage over 5 years | 6B × 500 B | about 3 TB |
| Redirect bandwidth | 40,000 × 500 B | about 20 MB per second |
Read the table as a story. The write rate is tiny: 40 per second is something a single database handles. Storage is modest: 3 TB fits on a handful of ordinary disks. Bandwidth is trivial. The only number that needs real engineering is peak reads at 40,000 per second, and even that is easily absorbed by a cache.
Check yourself
Which number actually forces caching in this design?
The API
Define the interface before the internals. A small, clear API also shows the interviewer you think from the user's side.
POST /api/v1/urls{ "url": "https://example.com/very/long/path?utm_source=x", "alias": "summer-sale", // optional "expiresAt": "2026-12-31" } // optional -> 201 Created{ "short": "https://ti.dev/summer-sale" }-> 409 Conflict (alias already taken)-> 400 Bad Request (invalid or blocked URL)-> 429 Too Many Requests (rate limit) GET /{code}-> 302 Found Location: https://example.com/very/long/path?utm_source=x-> 404 Not Found (unknown code)-> 410 Gone (expired or deleted)Authentication
creating links needs an API key or login so you can rate-limit and revoke abusers. Redirects are public and need nothing.
Rate limiting
cap link creation per user and per IP address (for example 100 per hour). This protects the ID space and stops spammers.
Validation
check the URL is well formed, uses http or https, and is not on a blocklist (see the security section).
Idempotency
if the same user posts the same URL twice, returning the same short link is friendlier than creating a duplicate.
Minting short codes
A short code is a base62 string: lowercase a-z, uppercase A-Z, digits 0-9 - 62 symbols in total. We choose base62 because those characters are safe in a URL without escaping. Every extra character multiplies the space by 62.
const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function encode(id) { let s = ""; while (id > 0) { s = ALPHABET[id % 62] + s; id = Math.floor(id / 62); } return s || "0";}| Length | Combinations | Enough for |
|---|---|---|
| 5 | 62^5 = 916 million | A small service |
| 6 | 62^6 = 56.8 billion | Our 6 billion links with room to spare |
| 7 | 62^7 = 3.5 trillion | Almost any service ever built |
| 8 | 62^8 = 218 trillion | Overkill |
Seven characters is the common answer: with 6 billion links in five years you would use only 0.17% of the space, which leaves room to avoid predictable patterns. The real question is not the alphabet but how you pick the next code without ever repeating one. That is the next section.
Check yourself
How many unique 7-character base62 codes exist?
Four ways to pick the next code
Every approach must guarantee two things: codes are unique and codes are hard to guess. They trade simplicity against coordination.
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Hash and truncate | MD5 or SHA-256 the long URL, base62-encode, keep the first 7 characters | Same URL always gives the same code; no counter | Collisions are certain at scale; needs a retry loop |
| Random code | Pick 7 random base62 characters; insert; retry if the key exists | Unguessable, no coordination | Every write needs an existence check; collision rate rises as the table fills |
| Counter + base62 | Encode an incrementing integer | Zero collisions, tiny codes | Sequential, so guessable; one counter is a bottleneck and single point of failure |
| Pre-generated key service | A separate service creates unused keys ahead of time and hands them out | Fast writes, no collisions, no checks at request time | One more system to run; must never hand the same key out twice |
Why hash truncation fails. A full 128-bit hash would be safe, but we keep only 7 base62 characters, about 42 bits. By the birthday paradox, collisions begin when you have around the square root of the space, roughly 2 million links. At 6 billion links you can expect about 5 million colliding pairs.
A collision means two different long URLs would share a short code. The standard repair is: on collision, append a salt (a counter or random string) to the input and hash again, then check the database. It works but adds a read to every write and still gets slower as the table fills. Hash-and-truncate is a fine first answer if you immediately explain how you handle collisions.
The distributed counter. The counter approach is attractive but a single counter is a bottleneck. The fix is a range lease: a coordination service such as ZooKeeper or a database row hands each API server a block of 10,000 unused numbers. The server mints codes locally from its block with no further network calls, and asks for a new block when it runs out. At 40 writes per second, one block lasts several minutes, so coordination traffic is negligible.
| Question | Answer |
|---|---|
| What if a server crashes holding an unused block? | Those numbers are lost. With 3.5 trillion codes that waste is irrelevant. |
| What if the coordinator is down? | Servers keep minting from their current block; only a server that runs out is blocked. Run the coordinator with replicas. |
| How do we stop guessing? | Shuffle the bits of the counter (a reversible permutation) before base62 encoding, so consecutive IDs look random. |
Check yourself
Why does truncating a hash to 7 characters cause collisions?
Storage is the easy part
The core record is a single mapping - a short code and a long URL, a few hundred bytes. Even at enormous scale the numbers stay small.
| Scale | Rows per year | Storage |
|---|---|---|
| 100M links/month | 1.2 billion | ~600 GB |
| 1B links/month | 12 billion | ~6 TB |
The database is not the bottleneck. It is the read traffic that forces caching and sharding - not the size of the data.
| Field | Type | Notes |
|---|---|---|
| short_code | string, primary key | Point lookups only; this is the shard key |
| long_url | string (up to 2,048 chars) | The destination |
| created_at | timestamp | Audit and expiry |
| expires_at | timestamp, nullable | Null means never |
| owner_id | string, nullable | For deletion and quotas |
| url_hash | string, indexed (optional) | Detects duplicate submissions |
Which database? There are no joins and no multi-row transactions. Every query is a get-by-key or an insert-if-absent. That shape suits a key-value or wide-column store such as DynamoDB or Cassandra, which shard and replicate automatically. A relational database like PostgreSQL also works fine at this size with a primary-key index and sharding added later. Pick one, justify it by the access pattern, and move on.
Check yourself
What is stored in the database?
The redirect: 301 versus 302
On read, the service answers with an HTTP redirect: a status code plus a Location header holding the long URL. The browser then goes there automatically. Which status code you pick has a real product consequence.
301 Moved Permanently
the browser caches the redirect, so repeat clicks skip your service and go straight to the long URL. Fast and cheap, but you never see those clicks.
302 Found
(temporary): the browser returns to your service every time, so you can count every click and route smartly - at the cost of more traffic.
307 and 308
stricter cousins that preserve the HTTP method (POST stays POST). Rarely needed for a shortener, but good to know they exist.
| Question | 301 | 302 |
|---|---|---|
| Browser caches it? | Yes, often indefinitely | No |
| Server load | Lower | Higher |
| Can you count every click? | No | Yes |
| Can you change the destination later? | Hard: cached copies persist | Yes, immediately |
| Search engines transfer ranking to the target? | Yes | Usually not |
Check yourself
Why would a shortener prefer 302 over 301?
Caching the redirect path
Link popularity is wildly uneven. A few links (a celebrity's post, a product launch) get millions of clicks while most get a handful. This is a power-law distribution, often summarized as the 80/20 rule. It is why a small cache works so well: caching the hottest 20% of links can answer roughly 80% or more of requests.
01Look up the code in the cache
The API asks a Redis cluster for the code. On a hit, it returns the redirect immediately in about a millisecond.
02On a miss, read the database
Fetch the mapping from the sharded store. This takes a few milliseconds.
03Fill the cache
Write the mapping into the cache with a TTL (time to live), often hours to a day.
04Evict by LRU
When memory is full, drop the Least Recently Used entries. Cold links fall out; hot links stay.
Negative caching
also cache 'not found' for a short time (say 60 seconds). Without it, scanners probing random codes bypass the cache and hit your database on every request.
Cache stampede
when a very hot entry expires, thousands of requests miss at once. Prevent it with request coalescing (one request refills while others wait), a little random jitter on TTLs, or refreshing popular keys before they expire.
Hot keys
one viral link can overload a single cache node. Replicate the hottest keys across nodes, or keep a tiny in-process cache on each API server.
Invalidation is rare
mappings are immutable, so you only invalidate on deletion or expiry. This is what makes caching so easy here.
Check yourself
Why does negative caching help?
The full picture
Put it together. A client shortens a URL (write) or follows a short code (read); the load balancer fans out to stateless API replicas; the ID generator mints codes; the database is the source of truth; the cache absorbs the read traffic.
Click a node to inspect it.
Scaling to billions of links
Shard the mapping table by shortCode
so each shard owns a slice of the keyspace; a lookup goes to exactly one shard.
Cache hot links
- a small fraction of links drives most clicks, so a modest Redis cache removes the bulk of database reads.
Scale the API horizontally behind the load balancer; it is stateless.
Distribute the ID generator
with range leases or snowflake IDs so no single box is a bottleneck or point of failure.
How to shard. The short code is the only lookup key, so it is the natural shard key. There are two common ways to map a code to a shard:
| Method | How | Pros | Cons |
|---|---|---|---|
| Hash of the code | shard = hash(code) mod N | Even spread, no hot shards | Changing N moves most keys, so use consistent hashing |
| Range of the code | shard 1 holds a-f..., shard 2 holds g-m... | Simple to reason about | Uneven if codes cluster; sequential counters hit one shard |
Hash-based sharding with consistent hashing is the standard answer. Adding a shard then moves only about 1/N of the keys instead of nearly all of them. Replicate each shard (typically 3 copies) so a failed machine loses nothing and reads can spread across copies.
Counting clicks without slowing redirects
Click counts are a feature users love, and a trap for designers. The naive version updates a counter in the database on every redirect. At 40,000 redirects per second that doubles your write load on the busiest path and creates a hot row for every viral link.
01Emit an event
The redirect handler sends a small event (code, time, country, referrer) to a queue such as Kafka and returns the redirect immediately. This is fire-and-forget: the user never waits for it.
02Aggregate
A stream processor counts events per code per minute and writes the totals to an analytics store.
03Query
Dashboards read pre-aggregated counts. Exact real-time totals are rarely needed; a few minutes of delay is fine.
Check yourself
Where should click counting happen?
Abuse, security and privacy
A shortener hides where a link goes. That is useful, and it is exactly what phishers and malware distributors want. Real services spend as much effort on abuse as on scaling.
| Threat | Defense |
|---|---|
| Malicious destinations (phishing, malware) | Check new links against a blocklist such as Google Safe Browsing; rescan existing links periodically, because a harmless page can turn malicious later |
| Mass link creation by bots | Authentication, per-user and per-IP rate limits, CAPTCHA on anonymous creation |
| Guessing codes (enumeration) | Unpredictable codes; do not expose sequential IDs; rate-limit 404s per IP |
| Private URLs exposed by short codes | Treat a short link as public. Never put secrets in the destination; offer expiring or password-protected links |
| Open-redirect abuse | Only allow http and https; reject javascript: and data: URLs |
| Loops (short link pointing at a short link) | Reject destinations on your own domain |
Expiry, custom aliases and duplicates
Expiry
store
expires_at. On read, if it has passed, return 410. A background job deletes expired rows in batches. Cache entries must not outlive the link, so give each one a TTL no longer than the link's remaining life. Recycling expired codes is risky because browsers and caches may still hold the old mapping - most services never reuse codes.Custom aliases
users choose
/summer-sale. Use a conditional insert so two claimants cannot both win. Reserve a list of words (api,admin,login) so aliases never collide with your own routes, and keep the alias space separate from generated codes (for example by length) so a generator can never mint a code someone already claimed.Duplicate submissions
if two users shorten the same URL, you can return the existing code (saves space, but reveals popularity and merges analytics) or always mint a new one (more privacy, more rows). Most public services mint a new code per request, and dedupe only per user.
Geo and device routing
store rules beside the mapping so a link can send mobile users to an app store and desktop users to a web page. Rules live in the cache with the mapping.
What breaks, and how you survive it
| Failure | Impact | Defense |
|---|---|---|
| Cache node dies | Misses spike; database load jumps | Replicate cache nodes; consistent hashing so only a slice is lost; protect the database with rate limits and request coalescing |
| Database shard down | Codes on that shard return errors | Replicas with automatic failover; serve from cache while the shard recovers |
| ID coordinator down | New servers cannot get blocks | Servers keep minting from their current block; run the coordinator with replicas; issue larger blocks |
| Region outage | Total outage for users there | Multi-region active-active; mappings are immutable, so replication conflicts are rare |
| Viral link | One cache key and shard overloaded | Replicate hot keys; in-process cache; CDN caching |
| Abuse wave | Spam links and blocklist overload | Rate limits, CAPTCHAs, async scanning, kill switch for creation |
How to run this in an interview
01Requirements (5 min)
Ask about scale, custom aliases, expiry and analytics. Write down functional and non-functional requirements, and what is out of scope.
02Estimates (5 min)
40 writes per second, 4k average and 40k peak reads, 3 TB over five years, 50 GB cache. Conclude that reads and the cache are what matter.
03API and data model (5 min)
Two endpoints, one table keyed by short code, a key-value store justified by the access pattern.
04Code generation (10 min)
Compare hash, random, counter and key service. Explain the birthday-paradox collision problem and settle on range-leased counters with scrambled bits.
05Scale and cache (10 min)
Consistent-hash sharding, replication, Redis with LRU and negative caching, stampede protection.
06Extras (10 min)
301 versus 302, async analytics, abuse handling, failure modes. Let the interviewer steer.
Recap
A shortener is one mapping table: shortCode → longUrl, plus machinery to serve it fast.
Reads outnumber writes ~100:1, so the redirect path gets the cache and the optimization.
Short codes are base62; 7 characters give ~3.5 trillion codes.
301 vs 302 is an analytics decision: cached redirects are fast but invisible.
Scale by sharding the table by shortCode and keeping the API stateless.
Distribute the ID generator (range leases or snowflake IDs) to avoid a single point of failure.
Terms in this lesson
Every acronym and concept, expanded. Tap a term to open it.
consistent hashing
Mapping keys and servers onto the same ring so adding or removing a server only moves the keys in its arc.
cache stampede
Many requests miss the same expired key at once and all hit the database together, potentially taking it down.
load balancer
A box that spreads incoming requests across healthy servers and stops sending to the ones that are down.
stateless
A server that keeps no session data of its own, so any request can be handled by any instance.
latency
The time a single request takes from start to finish.
queue
A first-in-first-out structure: items leave in the order they arrived.
graph
A set of nodes connected by edges, with no tree-shaped restriction.
node
One element in a linked structure, holding a value and pointers to its neighbors.
APIApplication Programming Interface
A contract that lets one program call another: a fixed list of requests you can make and the responses you get back.
CDNContent Delivery Network
A network of edge servers scattered around the world that cache static files close to users so requests travel a short distance.
TTLtime to live
How long a record or cache entry is valid before it expires.
LRULeast Recently Used
A cache eviction policy that drops the item nobody has read for the longest time - the classic 'use it or lose it' rule.
QPSqueries per second
How many requests hit the system each second - the basic unit of load.
bit
A single 0 or 1 - the smallest unit of data.
base62
An encoding using 62 symbols (a-z, A-Z, 0-9) - the alphabet short codes are written in.
short code
The compact token (e.g. `xK3f9Q`) that maps to a long URL.
301 redirect
A permanent redirect the browser caches, so it skips the service on repeat clicks.
302 redirect
A temporary redirect the browser does not cache, so every click returns through the service - needed for analytics.
snowflake ID
A time-ordered, machine-unique ID scheme (Twitter) that lets many instances mint IDs without colliding.
UTMUrchin Tracking Module
Query parameters such as utm_source added to links so marketers can attribute clicks to a campaign.
QRQuick Response code
A square barcode that encodes a URL; shorter URLs make it simpler and easier to scan.
collision
Two different long URLs being assigned the same short code - the failure that unique-ID schemes exist to prevent.
sharding
Splitting one big table across several databases so each holds a slice of the keys.
range lease
A coordinator hands each server a block of unused IDs (say 10,000) to mint locally with no further coordination.
CAPTCHACompletely Automated Public Turing test to tell Computers and Humans Apart
A challenge that is easy for people and hard for bots, used to slow automated abuse.
enumeration
Guessing sequential short codes to discover other people's links - a privacy risk of predictable IDs.
Where you will see it
Real systems that use this exact idea. Tap a card to open it.
Common traps
The mistakes interviewers watch for. Guess the fix, then reveal it.
FixHashes collide. Either retry-on-collision with DB uniqueness check, or use counter-based IDs encoded in base62 - deterministic uniqueness.
FixA synchronous DB increment doubles your write load on the hottest path. Fire an async event instead.
FixOnce a browser caches the 301, it never returns. If you need ongoing analytics, use 302 or accept the trade-off explicitly.
Interview prep
Questions you could be asked, with the depth an interviewer wants to hear.
A client posts a long URL to the API through a load balancer. The API asks an ID generator for a unique short code, stores the shortCode to longUrl mapping in a database, and caches hot lookups. Reads look up the code and return a 301 redirect.
write O(1) · read cached
Real worldbit.ly and t.co follow exactly this shape, with the cache absorbing almost all read traffic.
DeeperThe ID generator is the subtle piece: it mints collision-free codes without a central counter.