TheScalableDev
System DesignIntermediate30 minread O(1) cached · write O(1) amortizedFree

System Design - URL Shortener

Status

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.
01

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.

ComponentJob
load balancerSpread requests across API replicas
API serviceHandles 'shorten' (write) and 'redirect' (read)
ID generatorMints unique short codes
DatabaseStores the shortCode → longUrl mapping
CacheServes hot lookups before the DB
02

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.

TypeRequirementWhy it matters
FunctionalGiven a long URL, return a short oneThe core write path
FunctionalGiven a short code, redirect to the long URLThe core read path
FunctionalOptional custom alias (e.g. /summer-sale)Needs an atomic availability check
FunctionalOptional expiry date; delete a linkNeeds a TTL and a delete path
Non-functionalRedirect latency under about 100 msRedirects are on every click
Non-functionalHigh availability (99.9% or better)A dead shortener breaks every link ever shared
Non-functionalCodes must not be guessable in orderPrivacy: stop people scanning /1, /2, /3
Out of scope (say so)Full analytics dashboards, user accounts, billingMention as extensions, do not design them yet

Check yourself

Which requirement is most critical for the redirect path?

03

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.

PathFrequencyLatency 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.

04

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.

QuantityCalculationResult
Write QPS (queries per second)100M ÷ (30 days × 86,400 s) = 100M ÷ 2.6Mabout 40 per second
Average read QPS40 × 100about 4,000 per second
Peak read QPS10× the average for viral spikesabout 40,000 per second
Links per year100M × 121.2 billion
Links over 5 years1.2B × 56 billion
Storage per record7-char code + ~200-char URL + metadataabout 500 bytes
Storage over 5 years6B × 500 Babout 3 TB
Redirect bandwidth40,000 × 500 Babout 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.

cache 100 M hottest links × 500 B = 50 GB → at a 90% hit rate, 40,000 reads/s → 4,000/s reach the database
A 50 GB cache fits on a few nodes and cuts database load tenfold.

Check yourself

Which number actually forces caching in this design?

05

The API

Define the interface before the internals. A small, clear API also shows the interviewer you think from the user's side.

The two core endpoints.
1POST /api/v1/urls
2{ "url": "https://example.com/very/long/path?utm_source=x",
3 "alias": "summer-sale", // optional
4 "expiresAt": "2026-12-31" } // optional
5
6-> 201 Created
7{ "short": "https://ti.dev/summer-sale" }
8-> 409 Conflict (alias already taken)
9-> 400 Bad Request (invalid or blocked URL)
10-> 429 Too Many Requests (rate limit)
11
12GET /{code}
13-> 302 Found Location: https://example.com/very/long/path?utm_source=x
14-> 404 Not Found (unknown code)
15-> 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.

06

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.

Encoding an ID as a base62 short code.
1const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2function encode(id) {
3 let s = "";
4 while (id > 0) {
5 s = ALPHABET[id % 62] + s;
6 id = Math.floor(id / 62);
7 }
8 return s || "0";
9}
LengthCombinationsEnough for
562^5 = 916 millionA small service
662^6 = 56.8 billionOur 6 billion links with room to spare
762^7 = 3.5 trillionAlmost any service ever built
862^8 = 218 trillionOverkill
62^7 = 3,521,614,606,208 ≈ 3.5 trillion codes
Seven base62 characters give over 3.5 trillion unique codes.

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?

07

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.

ApproachHow it worksStrengthWeakness
Hash and truncateMD5 or SHA-256 the long URL, base62-encode, keep the first 7 charactersSame URL always gives the same code; no counterCollisions are certain at scale; needs a retry loop
Random codePick 7 random base62 characters; insert; retry if the key existsUnguessable, no coordinationEvery write needs an existence check; collision rate rises as the table fills
Counter + base62Encode an incrementing integerZero collisions, tiny codesSequential, so guessable; one counter is a bottleneck and single point of failure
Pre-generated key serviceA separate service creates unused keys ahead of time and hands them outFast writes, no collisions, no checks at request timeOne 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.

expected collisions ≈ n² / (2N) = (6×10⁹)² / (2 × 3.5×10¹²) ≈ 5 million
n = links stored, N = size of the code space. Collisions are not rare; they are routine.

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.

QuestionAnswer
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?

08

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.

ScaleRows per yearStorage
100M links/month1.2 billion~600 GB
1B links/month12 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.

FieldTypeNotes
short_codestring, primary keyPoint lookups only; this is the shard key
long_urlstring (up to 2,048 chars)The destination
created_attimestampAudit and expiry
expires_attimestamp, nullableNull means never
owner_idstring, nullableFor deletion and quotas
url_hashstring, 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?

09

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.

Question301302
Browser caches it?Yes, often indefinitelyNo
Server loadLowerHigher
Can you count every click?NoYes
Can you change the destination later?Hard: cached copies persistYes, immediately
Search engines transfer ranking to the target?YesUsually not

Check yourself

Why would a shortener prefer 302 over 301?

10

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.

  1. 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.

  2. 02On a miss, read the database

    Fetch the mapping from the sharded store. This takes a few milliseconds.

  3. 03Fill the cache

    Write the mapping into the cache with a TTL (time to live), often hours to a day.

  4. 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?

11

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.

POST /shortennext codewritereadmissClientLoad BalancerAPI ServiceID GeneratorDatabaseCache

Click a node to inspect it.

The URL shortener end to end.
12

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:

MethodHowProsCons
Hash of the codeshard = hash(code) mod NEven spread, no hot shardsChanging N moves most keys, so use consistent hashing
Range of the codeshard 1 holds a-f..., shard 2 holds g-m...Simple to reason aboutUneven 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.

13

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.

  1. 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.

  2. 02Aggregate

    A stream processor counts events per code per minute and writes the totals to an analytics store.

  3. 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?

14

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.

ThreatDefense
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 botsAuthentication, 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 codesTreat a short link as public. Never put secrets in the destination; offer expiring or password-protected links
Open-redirect abuseOnly allow http and https; reject javascript: and data: URLs
Loops (short link pointing at a short link)Reject destinations on your own domain
15

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.

16

What breaks, and how you survive it

FailureImpactDefense
Cache node diesMisses spike; database load jumpsReplicate cache nodes; consistent hashing so only a slice is lost; protect the database with rate limits and request coalescing
Database shard downCodes on that shard return errorsReplicas with automatic failover; serve from cache while the shard recovers
ID coordinator downNew servers cannot get blocksServers keep minting from their current block; run the coordinator with replicas; issue larger blocks
Region outageTotal outage for users thereMulti-region active-active; mappings are immutable, so replication conflicts are rare
Viral linkOne cache key and shard overloadedReplicate hot keys; in-process cache; CDN caching
Abuse waveSpam links and blocklist overloadRate limits, CAPTCHAs, async scanning, kill switch for creation
17

How to run this in an interview

  1. 01Requirements (5 min)

    Ask about scale, custom aliases, expiry and analytics. Write down functional and non-functional requirements, and what is out of scope.

  2. 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.

  3. 03API and data model (5 min)

    Two endpoints, one table keyed by short code, a key-value store justified by the access pattern.

  4. 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.

  5. 05Scale and cache (10 min)

    Consistent-hash sharding, replication, Redis with LRU and negative caching, stampede protection.

  6. 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.

  1. FixHashes collide. Either retry-on-collision with DB uniqueness check, or use counter-based IDs encoded in base62 - deterministic uniqueness.

  2. FixA synchronous DB increment doubles your write load on the hottest path. Fire an async event instead.

  3. 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.