“Design TinyURL” is the “hello world” of system design interviews, and one of the most frequently reported questions at companies like Google, Amazon and Microsoft. It looks tiny (turn a long link into a short one), but it tests everything that matters: estimates, unique ID generation, database choice, caching for a read-heavy load, and HTTP details. We'll solve it with the READS framework from Part 1.
Step 1 · Requirements
Start by agreeing the scope with the interviewer. A good set:
- Functional: given a long URL, return a short one; opening the short URL redirects to the original; optional custom alias and expiry.
- Non-functional: redirects must be very fast (a few milliseconds) and highly available; short codes should not be easy to guess (nice to have); links last for years.
- Out of scope (say it): user accounts, editing links, a detailed analytics dashboard.
Step 2 · Estimates
Assume 100 million new links a month and a 100 : 1 read-to-write ratio.
- Writes: 100M ÷ (30 × 100,000 s) ≈ 40 per second.
- Reads: 40 × 100 ≈ 4,000 redirects per second, ~8,000 at peak.
- Storage: 100M × 12 months × 5 years = 6 billion links × ~500 bytes ≈ 3 TB.
- Code length: 6 billion codes needed. 62⁶ ≈ 57 billion would do; 7 characters (3.5 trillion) gives plenty of headroom.
Step 3 · API
POST /api/urlswith{ longUrl, customAlias?, expiresAt? }→{ shortUrl }GET /{code}→302 FoundwithLocation: <long URL>(or404if unknown or expired)
Step 4 · Design
Generating the short code
This is the heart of the question. Each long URL needs a unique short code. Turn a number into base62:
🎮 Base62 explorer: number in, short code out
- 125 ÷ 62 = 2 remainder 1 → 1
- 2 ÷ 62 = 0 remainder 2 → 2
62 symbols: 0–9, a–z, A–Z. Seven characters give 62⁷ ≈ 3.5 trillion codes, enough for over a billion new links a day for years. (Max ID here: 62⁷ − 1.)
Where does the unique number come from? Four common answers:
| Approach | Pros | Cons | Good for |
|---|---|---|---|
| Hash + truncate (MD5 → 7 chars) | Same URL → same code; no shared state | Collisions: must check DB and retry | Simple systems, dedup wanted |
| Counter + base62 | No collisions, shortest codes | Guessable codes; counter must be shared safely | Most interview answers |
| Counter ranges per server | No collisions, no per-request coordination | Small gaps if a server dies (fine) | Scaling the counter idea |
| Pre-generated key service | Fast, random-looking codes | Extra service to run and keep available | Codes must not be guessable |
A strong answer: a small coordination service (or a database row) hands each app server a range of IDs, say 1,000,000 at a time. The server counts through its range in memory, converts each ID to base62, and asks for a new range when it runs out. No collisions, no network call per link. If codes must not be guessable, shuffle the bits of the ID before encoding, or use a pre-generated key service.
ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode(n: int) -> str:
"""Turn a numeric ID into a short base62 code."""
if n == 0:
return ALPHABET[0]
code = []
while n > 0:
n, r = divmod(n, 62)
code.append(ALPHABET[r])
return "".join(reversed(code))
def decode(code: str) -> int:
"""Turn a short code back into the numeric ID."""
n = 0
for ch in code:
n = n * 62 + ALPHABET.index(ch)
return n
print(encode(125)) # 21
print(encode(2009215674938)) # zn9edcu
print(decode("zn9edcu")) # 2009215674938
print(62 ** 7) # 3521614606208 possible 7-character codesThe data model
urls code VARCHAR(7) PRIMARY KEY -- "zn9edcu" long_url TEXT NOT NULL created_at TIMESTAMP expires_at TIMESTAMP NULL user_id BIGINT NULL -- if accounts are added later
Every redirect is a lookup by primary key, with no joins. A key-value or wide-column store (DynamoDB, Cassandra) scales this effortlessly; PostgreSQL works well too at moderate scale.
The redirect: 301 or 302?
🎮 Redirect simulator: 301 vs 302
Click 3 times with each code. 301 saves server load because the browser caches it, but you lose click counts. 302 sends every click through you, so analytics work. If accurate click counts matter, use 302 (or a 301 with a short cache time).
Step 5 · Scale
- Cache hot links: a small share of links get most of the clicks. Keep them in Redis with LRU eviction. Caching ~20% of a day's traffic is only tens of GB of memory, and most redirects never touch the database.
- Stateless app servers behind a load balancer: add more as traffic grows.
- Database: read replicas, then shard by
code(hash of the code) when data or writes outgrow one machine. Lookups always include the code, so every query goes to exactly one shard. - Analytics without slowing redirects: push a click event onto a queue and let workers count clicks in the background.
- Abuse: rate-limit link creation per user or IP (that's the next part!) and check long URLs against a malware blocklist.
- Expiry: a background job deletes expired links; the redirect path also checks
expires_at.
🧠 PATH memory card
Remember the URL shortener design for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
A wedding-hall cloakroom: you hand over a big bag (the long URL) and get a small token. The attendant takes the next number from a counter, writes it as a short token, and keeps the bags people collect most at the front. Show your token and you get the bag back: that's the redirect.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Count → Convert → Cache”
- Count→Unique ID from a counter (ranges per server)
- Convert→ID → base62, 7 characters ≈ 3.5 trillion codes
- Cache→Hot codes in Redis; reads are 100× writes
- Token→Short code stored as code → long URL
- Get the bag back→GET /code → 302 to the long URL
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Server A owns IDs 1–1,000,000. A new link arrives: next ID is 125. 125 ÷ 62 = 2 remainder 1 → “1”; 2 ÷ 62 = 0 remainder 2 → “2”. Read bottom-up: code “21”. Save21 → long URL. Someone openstt.ly/21: cache miss → DB → store in cache → 302. Next click: cache hit, about 1 ms. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 8 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Follow-up questions interviewers ask
- “Same long URL submitted twice?” Either return a new code (simplest) or look up an index on
long_urland reuse the old one. - “Custom aliases?” Check the alias isn't taken, then insert it directly. Keep custom aliases in a range the counter can't produce (e.g. require 8+ characters).
- “What if the ID service dies?” Servers still have their current range; run the service with replicas.
- “Multiple regions?” Give each region its own ID ranges, replicate the database, and serve redirects from the nearest region.
Where to go next
Your shortener is public, so someone will try to create a million links a minute. Next, protect it with one of the most asked infrastructure questions: design a rate limiter.
Key takeaways
- Clarify scope: shorten, redirect, optional alias and expiry; redirects must be fast and always available.
- 100M links/month ≈ 40 writes/s and ≈ 4,000 reads/s: a read-heavy system.
- Unique counter (ranges per server) → base62 → 7-character code. No collisions.
- Store code → long URL in a key-value store; cache hot codes in Redis.
- 302 if you need analytics, 301 to minimise load. Shard by code when one database isn't enough.
Frequently asked questions
How does a URL shortener work?
When you submit a long URL, the service gives it a unique ID, converts that ID into a short code (usually base62: 0-9, a-z, A-Z), and stores the pair code → long URL in a database. When someone opens the short link, the service looks up the code (in a cache first, then the database) and replies with an HTTP 301 or 302 redirect to the long URL.
Why use base62 for short URLs?
Base62 uses only letters and digits, which are safe in URLs and easy to read and type. Each character carries one of 62 values, so codes stay very short: 7 characters give 62^7, about 3.5 trillion unique codes. Base64 adds + and /, which have special meanings in URLs.
Should a URL shortener use hashing or a counter?
Both work. Hashing the long URL (e.g. MD5) and taking the first 7 characters is simple and gives the same code for the same URL, but different URLs can collide, so you must check the database and retry. A unique counter converted to base62 never collides, but codes are guessable and the counter must be shared safely; handing out ID ranges to each server solves that. Many interview answers pick the counter with ranges.
301 or 302 redirect for a URL shortener?
A 301 (moved permanently) lets browsers cache the redirect, which saves server load but hides repeat clicks from your analytics. A 302 (found, temporary) sends every click through your servers, so you can count clicks, change the destination or expire the link. Choose 302 if analytics matter; 301 if raw speed and cost matter most.
Which database is best for a URL shortener?
The access pattern is a simple key lookup (code → long URL) at very high read volume, with no joins. A key-value or wide-column NoSQL store like DynamoDB or Cassandra fits well and scales horizontally. A relational database like PostgreSQL with an index on the code also works fine at moderate scale, especially with a cache in front.
🧠 Quick check: URL shortener
1. A URL shortener gets 100 reads for every write. What does that tell you?
2. How many unique codes do 7 base62 characters give?
3. You take the first 7 characters of an MD5 hash as the code. What must you handle?
4. The product team wants to count every click. Which redirect?