Design a URL shortener: encoding, hashing, 301 vs 302
One hundred million URLs a day, each shrinking to seven characters, surviving ten years and redirecting in milliseconds. The design turns on two decisions that look cosmetic and are not: which redirect status code you return, and whether you hash the URL or count.
1,160/sSustained writes, from 100M per day (§1)
11,600/sSustained reads at a 10:1 ratio. Reads win (§1)
627 = 3.5TWhy the code is 7 characters and not 6 (§4)
365 TBTen years of rows at 100 bytes each (§1)
Key points
Reads outnumber writes ten to one, so the design that wins is whichever one serves a redirect most cheaply. Everything else follows from that sentence.
301 lets browsers cache the redirect and skip your servers entirely. 302 brings every click back to you. The choice is server load versus click analytics, and it is irreversible in practice because caches already hold your 301.
Hashing a URL and truncating will collide, so every write pays a database existence check forever. Converting a unique ID to base 62 cannot collide, because the uniqueness was established before the encoding.
Outcomes
01Derive writes/s, reads/s, row count and storage from one daily figure.
02Choose 301 or 302 by naming who pays, and say why the choice is hard to reverse.
03Prove that 7 characters is the floor, not a guess.
04Explain why base 62 conversion beats hash-plus-collision-handling.
01
Count the load before drawing a box
Four clarifying questions, and their answers set every later decision. A long URL becomes something like https://tinyurl.com/y7keocwj, and clicking it redirects to the original. Traffic is 100 million new URLs per day. Codes should be as short as possible over a 62-character alphabet — digits plus both cases. Shortened URLs are never deleted or updated, which removes an entire class of invalidation logic. Two use cases remain: shorten, and redirect.
Now the envelope, using the Day 3 shortcuts:
Quantity
Working
Result
Write rate
100M ÷ 86,400 s
~1,160 /s
Read rate
writes × 10 (stated ratio)
~11,600 /s
Rows in 10 years
100M × 365 × 10
365 billion
Storage
365B × 100 bytes
36.5 TB/yr, 365 TB/decade
Shorten (writes)1.2 K/s
Redirect (reads)11.6 K/s
Rows after 10 years365 B
📏 Log scale — each step right is roughly 10×.
Read the numbers, do not just produce them. 1,160 writes per second is unremarkable. 11,600 reads per second is still unremarkable if they are cheap — and the whole design effort goes into making them cheap. 365 billion rows is the number that actually constrains you: it rules out a single database, and it is what forces the code length in §4.
02
Redirect first: 301 sheds load, 302 counts clicks
Two endpoints carry the whole API. POST /api/v1/data/shorten takes a long URL and returns a short one. GET /{shortUrl} returns an HTTP redirect. That second one has two flavours, and the choice between them is the first real trade-off of the lesson.
How to read: Step through it. The top row of each panel is the first click; the bottom row is every click after it, by the same browser. The difference is entirely in the bottom row.
Most commercial shorteners run 302, because click analytics is the product. If your shortener exists purely to make links tidy, 301 is cheaper and kinder to your infrastructure.
Gotcha — the decision is one-way
A 301 is a permanent instruction. Browsers, proxies and CDNs are entitled to cache it indefinitely, and many do. Shipping 301 and then adding analytics later does not work: you will never see the clicks from clients that already have the old answer, and you have no way to purge their caches. If there is any chance you will want click data, start with 302. The interviewer will usually probe exactly this.
03
The redirect path: cache first, database second
The naive store is a hash table of short URL to long URL. It fits on a whiteboard and fails on 365 billion rows: memory is finite and expensive. So the mapping lives in a table of three columns — id, shortURL, longURL — with a cache in front of it, because the read:write ratio makes caching the highest-leverage move available.
How to read: Three outcomes, not two. The third one — missing everywhere — is the one candidates forget, and it has a different correct response.
Because records are never updated or deleted, cache invalidation — normally the hardest part of caching — simply does not exist here. Entries can live until evicted. That simplification came from a clarifying question in §1.
04
Minting codes: hash and pray, or convert and know
The short URL is the domain plus a code, so the design problem reduces to a function from long URL to code. First, how long must the code be?
The alphabet holds 62 characters. The decade requirement is 365 billion URLs. So:
625916 M
626 — too small56.8 B
what we need365 B
627 — picked3.5 T
📏 Log scale. Six characters holds 56.8 billion, which is short of 365 billion. Seven is the floor, not a guess — and it leaves nearly 10× headroom.
Two ways to produce the code
Option A
Hash and resolve collisions
Hash the long URL with CRC32, MD5 or SHA-1 and keep the first 7 characters.
Truncating to 7 characters guarantees collisions — you are mapping an infinite space into 3.5 trillion slots.
So every write needs a database existence check, and a Bloom filter in front of it to keep that check fast.
On a collision, append a salt and rehash. The hot path pays for this forever.
Upside: stateless. No ID generator to depend on.
Option B — the book's pick
Base 62 conversion
Take a unique ID and change its base. 11157 becomes 2TX.
No existence check at all. IDs are unique by construction, so codes are too — the encoding is a bijection.
Reuses the Day 8 snowflake generator for distributed minting.
Cost: you now depend on the ID generator. If it stalls, shortening stalls.
Also: codes are sequential and therefore enumerable (see Q4).
How to read: Repeated division by 62. Each remainder indexes into the alphabet, and the digits come out least-significant first — so you read them upwards.
This is reversible. Decoding walks the other way — multiply by 62 and add — so the code carries its own ID and you never need a reverse lookup table.
Try it: type a number or type a code — both boxes stay in sync, and the division ladder re-runs underneath. Try 627−1 to confirm that seven characters really do cover the whole decade.
code length
3 chars
that length holds
238,328
distinct codes
round trip
holds
encode then decode
short URL
tinyurl.com/2TX
Notice that the code length grows one character per 62× of ID space, and that nothing anywhere does a uniqueness check. The encoding is a bijection, so uniqueness was settled before it ran.
Interview line
“Hash-and-truncate is stateless but pays a database read on every write, forever, and the collision rate grows as the table fills. Base 62 conversion costs me a dependency on the ID generator and gives me guaranteed uniqueness with zero reads. At 1,160 writes a second I'd take the dependency — and I'd note that the resulting codes are enumerable, so I'd add a random component if the links need to be unguessable.”
05
The shorten path: dedup first, mint second
Six steps, and the lookup at the front is what makes repeat submissions free.
Submit
The long URL arrives at a web server.
Look it up
Already stored? Return the existing code untouched. No new row, no new ID.
Mint an ID
New URL: ask the distributed ID generator (Day 8) for a unique 64-bit integer.
Convert
Base 62 encode it. 2009215674938 becomes zn9edcu — seven characters.
Insert
Store the (id, shortURL, longURL) triple.
Return
Hand the short URL back to the client.
Gotcha — the dedup lookup is not free
Step 2 is a lookup on the long URL, which can be 2 KB. Indexing a 2 KB text column is expensive, so in practice you index a hash of it instead — a long_url_hash column with a unique index. Note the irony: you avoided hashing for the code and reintroduced it for deduplication. The difference is that a collision here costs you a wasted row, not a wrong redirect.
The ID generator is doing quiet heavy lifting. Globally unique IDs with no per-request coordination is exactly what Day 8's snowflake was built for — and because shortening stalls if the generator stalls, it inherits the same mission-critical availability requirement.
Base 62, both directionspython
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
BASE = len(ALPHABET) # 62
def encode(num):
assert num >= 0
if num == 0:
return ALPHABET[0]
out = ''
while num > 0: # repeated divmod, least significant digit firstnum, rem = divmod(num, BASE)
out = ALPHABET[rem] + out # prepend, so the string comes out in order
return out
def decode(s):
num = 0
for ch in s: # Horner's method: shift left one digit, addnum = num * BASE + ALPHABET.index(ch)
return num
print(encode(11157)) # 2TX
print(decode('2TX')) # 11157 — round trip holds
print(encode(2009215674938)) # zn9edcu — a chapter-scale ID in 7 chars
print(len(encode(62**7 - 1))) # 7 — the full range fits the picked length
Make the shorten endpoint idempotent
Step 2's dedup lookup gives you something close to idempotency by accident: submit the same long URL twice and you get the same code back. But that only works because this system never updates anything. The general mechanism is worth knowing by name, because it is asked about constantly and it reappears on Day 11.
The client generates a unique idempotency key and sends it as a header. The server stores it alongside the outcome:
Key not seen → record it as in progress, do the work, store the response against the key, return it.
Key seen and complete → return the stored response verbatim. Do not redo the work. The client cannot tell this was a retry, which is the point.
Key seen and still in progress → return 409, because the original request may yet succeed. This is the case people forget, and it is the one a retry storm actually hits.
TTL → keys expire, typically in 24 hours. Long enough to outlive any sane retry, short enough that the table does not grow forever.
Store the key with a unique constraint rather than checking-then-inserting — otherwise two concurrent retries both read “not seen” and both do the work, which is Day 5's race condition wearing a different hat. Stripe's payments API is the reference implementation of this pattern, and for good reason: for a shortener a duplicate costs a wasted row, but for a payment it costs a double charge.
What to mention if time remains
Rate limiting on the shorten endpoint (Day 5). Without it, one client can burn through your ID space and your storage budget.
Stateless web tier scaled by adding servers (Day 2). Nothing here holds state.
Sharding the mapping table by code prefix once 365 billion rows outgrows replication alone (Day 6 for the routing).
Analytics pipeline — and note that the click event should go onto a queue, not into the redirect's critical path. A redirect must not wait for an analytics write.
Custom aliases (/black-friday), which reintroduce collisions deliberately and need a reserved-word list.
Q&A
Check yourself
Q1You shipped 301 six months ago. Marketing now wants per-link click counts. What do you tell them, and what is your actual plan?
Switch to 302 and counts start working immediately
Switch to 302, but historical links already cached in browsers may never report again — so counts will undercount old links indefinitely
Add a tracking pixel to the redirect response
✓ Switch to 302, but old links are permanently under-counted. A 301 is cacheable indefinitely and you cannot purge other people's browser caches. Any client that already resolved the link may go straight to the destination forever. The practical plan: switch new links to 302 immediately, accept that pre-existing links report partial data, and be explicit about the discontinuity in the dashboard. You cannot add a tracking pixel — a redirect has no body to put one in. This question is really testing whether you understand that some design choices propagate into systems you do not control.
Q2Your shortener uses base 62 over a sequential ID. A journalist discovers they can increment a code and browse other people's links. What happened, and what are your options?
Nothing to fix — shortened URLs are public by design
Sequential IDs make codes enumerable; mitigate by encoding a non-sequential value or adding random characters
Add rate limiting to the redirect endpoint
✓ Sequential IDs make the whole corpus walkable. Base 62 is a bijection, so consecutive IDs produce near-consecutive codes and anyone can crawl your entire link database. Three real mitigations: (a) encode a value that is unique but not sequential — snowflake IDs help somewhat since the low bits move, but the high bits are still time-ordered; (b) apply a reversible permutation (a Feistel network or multiply-by-a-coprime modulo 627) so IDs scatter across the space while staying collision-free; (c) append 2–3 random characters, accepting a slightly longer code and a uniqueness check. Rate limiting only slows the crawl. This is one of the most common follow-ups on this question, because it shows whether you treat “unique” and “unguessable” as the same property. They are not.
Q3A link goes viral: one code receives 400,000 requests per second, far above your 11,600/s average. Your cache is fine but the service degrades. Where would you look first?
Add more cache nodes
The hot key lands on one cache shard — and if analytics writes are synchronous, every click is also a write
Shard the database by code
✓ A hot key on one shard, plus synchronous analytics writes. Two things bite. First, Day 6's lesson: consistent hashing spreads keys, not traffic — 400,000 requests for one key all land on one cache node regardless of how many you have. The fix is to replicate that key across nodes, or add a tiny in-process cache on each web server so most hits never leave the box. Second, if you increment a click counter synchronously, you have turned a read-only path into 400,000 writes per second to one row. Click events belong on a queue, aggregated asynchronously. Sharding the database does not help: these requests never reach the database.
Q4An interviewer asks: “Why not just store the mapping in Redis and skip the database entirely?” Give the strongest version of both answers.
Redis is not durable, so you would lose data
For: it is a pure key-value workload and Redis is built for it. Against: 365 TB in RAM is economically absurd, and the access pattern is long-tail
Redis cannot handle 11,600 requests per second
✓ The honest answer is about cost and access distribution, not capability.For: the workload is exactly a key-value lookup with no updates and no range queries — Redis handles the throughput trivially, and Redis persistence (AOF with appendfsync everysec) addresses the durability objection. Against: the decade's data is 365 TB, and RAM costs roughly two orders of magnitude more per byte than disk; link traffic is also strongly long-tail, with most clicks landing on a small set of recent links. So you cache the hot few percent in RAM and keep the cold 95%+ on disk, which is the design in §3. Saying “Redis isn't durable” as a flat statement is the weak answer — it is configurable, and an interviewer who knows that will push.
Q5Design a deletion feature: users want to delete their short links. The original spec said links are never deleted. What breaks?
Nothing — just remove the row
Cache invalidation returns, deleted codes must not be reused, and 404 becomes a cacheable mistake
The base 62 encoding stops working
✓ Three things you had deliberately designed away.(1) Cache invalidation reappears — §3 relied on records being immutable, so now every delete must purge cache entries across every node. (2) You must not reuse the code, or an old link suddenly points somewhere new, which is a genuine security problem (someone's bookmarked link now goes to a site you do not control). Keep a tombstone row rather than freeing the ID. (3) Your 404 path is now semantically different: “never existed” versus “deleted”, and if you ever cache 404s you must be careful not to cache them before a link exists. The point of this question is that “never deleted” was not a trivial simplification in the spec — it removed an entire dimension of the design, and the interviewer wants to see you notice that.
In practiceWhat production adds, and the questions that come next optional
This lesson covers the layer that decides an interview. Below it is the operational layer — the things that only show up once a system is running, and the questions that come if someone keeps pulling the thread. None of it is answered above.
API design
REST vs. RPC/gRPC vs. GraphQL: what each optimises for and the concrete cost of each
Pagination: offset vs. cursor/keyset, and why offset breaks at scale and under concurrent writes
Error taxonomy, retry-after semantics, and which errors clients are allowed to retry
Terms used
301 Moved Permanently
A redirect browsers may cache indefinitely. Sheds load, hides clicks, hard to reverse.
302 Found
A temporary redirect. Every click reaches your server, so every click is measurable.
Location header
The header carrying the destination URL in a redirect response.
Base 62
Positional notation over 0-9 a-z A-Z. Shortest URL-safe encoding without special characters.
Bijection
A one-to-one, reversible mapping. Base 62 encoding is one, which is why it cannot collide.
Collision
Two different inputs producing the same code. Guaranteed when hashing into a fixed-length output.
Bloom filter
Probabilistic membership check used to skip most database existence lookups.
Hot key
One key taking disproportionate traffic. Not solved by sharding or consistent hashing.
Tombstone
A marker row recording that something was deleted, so its identifier is never reused.
What breaks next. A shortener waits for links to arrive. Day 10 inverts that: a crawler goes and finds a billion pages a month, which means deciding what to fetch next, how fast, and how not to get banned while doing it.
Source: System Design Interview, Ch. 8 — Design a URL shortener (pp. 119–131). The 301-irreversibility discussion, enumeration mitigations, hot-key analysis and the deletion question are common interview follow-ups added here.