A URL shortener turns https://example.com/products/2024/summer-sale?utm_source=newsletter into sho.rt/aZ3k9Qx and redirects anyone who opens the short link. It looks trivial, which is exactly why interviewers like it: the interesting part is the numbers. Redirects outnumber link creation 100 to 1, the data set is tens of terabytes, and every short key must be unique without slowing the write path down. This lesson walks the full eight-step interview framework, with the reasoning you should say out loud at each step.
Detailed Notes
How to use this lesson
Treat this as a 45-minute interview. Every step below is one block of the conversation. The numbers are assumptions you state out loud, not facts about any real company. An interviewer will not check that 500 million links a month is realistic; they will check that your estimate drives your design.
Step 1: Clarify Requirements
Never start drawing. Spend the first five minutes turning a one-line prompt ("design TinyURL") into a precise scope. A good opening: "Before I design anything, I'd like to agree on what the system must do, how big it is, and what I can leave out."
Functional requirements
A user submits a long URL and receives a short link.
Anyone who opens the short link is redirected to the original URL.
A user can optionally pick a custom alias (for example sho.rt/summer-sale).
A link can optionally have an expiry time. After that it stops working.
Extended requirements
Mention these, then ask whether to include them. Do not design them unless asked.
Click analytics: how many times a link was opened, from which country, from which referrer.
Link management: a logged-in user can list and delete their own links.
Abuse protection: block links to malware and phishing pages.
Non-functional requirements
Non-functional requirements describe how well the system must behave. Put a number on each one, because numbers are what you design against.
Low latency: a redirect must feel instant. Target a 99th-percentile (p99) redirect time under 100 ms. "p99 under 100 ms" means 99 of every 100 requests finish faster than that.
High availability: a short link printed on a poster or sent in an email must keep working. Target 99.99% availability, about 52 minutes of downtime per year. Availability matters more for redirects than for link creation.
Scalability: billions of stored links and tens of thousands of redirects per second.
Uniqueness and correctness: two different long URLs must never receive the same short key, and a key must never redirect to the wrong place.
Unpredictability (nice to have): keys should not be guessable one after another, otherwise someone can crawl every private link.
Durability: once we return a short link, we must not lose it.
Consistency decision. Redirects can tolerate slightly stale data (a link deleted one second ago may still redirect for a moment). Link creation must be consistent: a key can be given out only once. Saying this early shows you think about consistency per operation, not per system.
Out of scope
State what you are not building so the interviewer can redirect you: user registration and billing, A/B testing destinations, QR codes, and a full anti-abuse pipeline. We will mention abuse and analytics but not build them in depth.
Interview tip. Candidates often skip this step and jump to "I'd use a hash function and a NoSQL database." Interviewers read that as pattern matching. Two or three sharp questions (expected scale, expiry, custom aliases) separate strong candidates immediately.
Step 2: Estimate Scale
Back-of-the-envelope estimation means rough calculations that tell you which parts of the system will be hard. The goal is not precision. It is to learn whether you need one machine or a thousand, and whether the system is read-heavy or write-heavy. Round every number so the arithmetic is easy to do aloud.
Assumptions to state
500 million new short links per month.
Read-to-write ratio of 100 : 1. People open links far more often than they create them.
Each stored record takes about 500 bytes (long URL, key, timestamps, owner).
We keep each link for 5 years.
A day has about 100,000 seconds. The real value is 86,400, but 100,000 makes mental math easy and the error is small.
Request load
text
500M links / 30 days = about 17M writes per day
17M / 100,000 seconds = about 170 writes per second
Rounded write rate = 200 writes per second
200 writes x 100 redirects = 20,000 reads per second
20,000 reads x 3 peak factor = 60,000 peak reads per second
Why peak matters. Traffic is never flat. A link goes viral, or people read email at 9 a.m. We multiply the average by a peak factor (3 is a common starting point) because the system must survive the busiest minute, not the average one.
URL Shortener: Estimate the ScaleEstimation
Request load
500Mnew links / month
given
17Mper day
÷ 30 days
~200/swrites (from 170)
÷ 100,000 s
20K/sreads
× 100 read:write
60K/sreads at peak
× 3 peak factor
Storage
15 TB
30 billion links × ~500 bytes
Partition the data across machines
Bandwidth
~6 MB/s
20K redirects/s × 300 bytes out
Bandwidth is not a bottleneck
Cache
~40 GB
hottest 20% of 400M daily links × 500 bytes
Put a cache in front of the database
Key point. Reads dominate (cache them), storage needs partitioning, and bandwidth can be ignored.
Every estimate derives from two numbers: 500 million new links a month and 100 reads for every write.
Storage
text
500M links x 12 months x 5 years = 30 billion links
30 billion x 500 bytes = 15 TB
Fifteen terabytes technically fits on one large server, but that is a poor idea. Copying 15 TB at 500 MB per second takes over 8 hours, so a backup, restore or new replica would be painfully slow, and one failure would block every link. That one calculation justifies partitioning (splitting data across machines), which we design in Step 6.
Bandwidth
text
Incoming: 200 writes/s x 500 bytes = 100 KB/s
Outgoing: 20,000 redirects/s x 300 bytes = 6 MB/s
An HTTP redirect response is tiny (headers and a Location URL), so bandwidth is not the bottleneck. Saying "bandwidth is a non-issue here, so I'll ignore it" is a perfectly good interview answer.
Cache size
text
Redirects per day = 20,000 x 100,000 = 2 billion
Distinct links read per day = about 400M (popular links repeat)
Cache the hottest 20% = 80M links x 500 bytes = 40 GB
This uses the 80/20 rule: roughly 20% of links produce 80% of the traffic. Forty gigabytes fits in the memory of a few machines. A cache is a fast, temporary copy of data kept in memory, so most redirects never touch the database.
Other sizing checks
Key length. We need 30 billion unique keys. Using a-z, A-Z and 0-9 (62 symbols, called base62), 6 characters give 62^6 = 56.8 billion combinations, only about 2x our need. 7 characters give 62^7 = 3.5 trillion, about 100x our need. We pick 7 characters.
App servers. One app server handles roughly 5,000 to 10,000 simple requests per second. At 60,000 peak reads/s we need about 10 servers, plus headroom and multiple availability zones.
Database load after caching. With a 90% cache hit rate only 10% of reads reach the database: about 2,000 reads/s on average, 6,000 at peak. That is easy for a small cluster. The cache is what makes the design cheap.
Interview tip. Finish every estimate with "so what": "reads dominate, so I'll optimize the read path", "15 TB means I must partition", "bandwidth is tiny, so I'll skip it."
Step 3: Define the APIs
An API (application programming interface) is the contract between clients and the service. Define it before the internals, because the operations you promise decide what you must store and how fast each path has to be.
400 Bad Request if the URL is malformed, longer than 2,048 characters, or not http/https.
401 Unauthorized if the caller is not logged in.
409 Conflict if the custom alias is already taken.
429 Too Many Requests if the caller exceeds the creation rate limit.
Design decision: idempotency. A client may retry after a timeout and accidentally create two links. Accept an optional Idempotency-Key header: if the same key arrives again, return the first response instead of creating a new link.
Redirect
http
GET /summer-sale
HTTP/1.1 302 Found
Location: https://example.com/products/2024/summer-sale?utm_source=newsletter
302 Found (temporary) or 301 Moved Permanently. We compare them in the deep dive.
404 Not Found if the key does not exist.
410 Gone if the link existed but expired or was deleted.
Management APIs
http
GET /v1/links?cursor=...&limit=50 # list my links, paginated
DELETE /v1/links/{short_key} # disable a link
GET /v1/links/{short_key}/stats # click analytics (extended)
How the API shapes the architecture
The redirect carries only a key and needs only one value (the long URL). There are no joins, ranges or search. That is a pure key-value lookup, the most important fact for choosing the database and cache. The redirect endpoint is also the only high-volume, latency-critical endpoint, so it gets its own service and scaling plan.
Step 4: Define the Data Model
Start from access patterns, not tables. We need three storage operations:
Read by key: "given aZ3k9Qx, return the long URL" (60,000 per second at peak).
Insert: "store a new key and URL, fail if the key exists" (200 per second).
List by owner: "all links created by user 42" (rare, dashboard only).
Fields and why each exists
short_key: the primary key and the partition key (it decides which machine stores the row). Every redirect is one lookup on it.
long_url: the destination returned in the redirect.
user_id: the owner. Supports link management and per-user rate limits.
created_at: supports analytics and retention cleanup.
expires_at: supports expiry. Null means "never expires".
status: active, disabled or blocked. Lets us take down abusive links without deleting history.
Conditional insert (only if short_key is absent) guarantees uniqueness.
usersRelational DB
PKuser_iduuid
UQemailvarchar
created_attimestamp
Small table; any relational database works.
click_eventsAnalytics store
PKshort_keyvarchar(16)
SKclicked_attimestamp
countryvarchar(2)
referrervarchar
Append-only and written asynchronously, so a viral link cannot create a hot row.
unused_keysKGS store
PKshort_keychar(7)
Moved to used_keys the moment a batch is handed out.
urls.user_idusers.user_id· many to one
click_events.short_keyurls.short_key· many to one
Key point. The partition key is short_key. Every redirect is exactly one lookup on it.
One row per short link keyed by short_key. Click events live in a separate store.
Why clicks are not a column
It is tempting to add a click_count column. Do not. A viral link would be updated thousands of times per second, turning one row into a hot spot (one record receiving a disproportionate share of traffic), and every redirect would wait on a database write. Instead we append click events to a separate analytics store, off the request path.
Which database?
Reason from the access patterns instead of saying "NoSQL because scale":
Lookups are by a single key, with no joins or multi-row transactions. That fits a key-value or wide-column store.
15 TB and 6,000 database reads per second need horizontal partitioning, which these stores do automatically.
Uniqueness needs a conditional write ("insert only if this key does not exist"), which most key-value stores provide.
"List by owner" needs a secondary index on user_id.
PostgreSQL is also valid, especially at lower scale, with sharding added later. What matters is that you explain the choice.
Trade-off thinking. SQL gives ad-hoc queries and familiar tooling but needs manual sharding at 15 TB. A key-value store scales out naturally but makes new query shapes hard. Our workload has exactly one query shape, so key-value wins.
Step 5: High-Level Design
The golden rule: separate the write path from the read path, because their requirements differ. Writes are rare and need uniqueness. Reads are constant and need speed.
The Write Path and the Read PathArchitecture
Key point. One request in a hundred is a write. Put every expensive optimization on the read path.
Reads outnumber writes 100 to 1, so the cache sits on the read side only.
Components and why each exists
API gateway / load balancer: single entry point. A load balancer spreads requests across identical servers so none is overwhelmed and a failed one is skipped. The gateway also handles TLS, authentication and rate limiting.
Shortening service (write path): validates the URL, obtains a unique key, inserts the row.
Key generation service (KGS) (write path): hands out unique, unused keys so the shortening service never guesses and checks.
Redirect service (read path): finds the long URL and returns the redirect. It is stateless: it keeps no user data between requests, so any instance can serve any request and we can add instances freely.
Cache: in-memory key-value store in front of the database. Most redirects end here.
URL database: the source of truth, partitioned by short_key and replicated.
Splitting services lets each scale independently: 10 redirect servers might need only 2 shortening servers.
Redirect Flow with a Cache MissRequest flow
BrowserRedirectserviceCacheURL database1GET /aZ3k9Qx2get(aZ3k9Qx)3miss4read by keycheck status and expires_at5long_url6set(key, url, TTL)7302 Location: long_url
A cache hit stops at step 3; a miss continues to the database and fills the cache.
Request flow
Write path.
Client sends POST /v1/links. The gateway authenticates and rate limits.
The shortening service validates the URL.
It takes a pre-generated key from KGS, or uses the custom alias.
It inserts the row with a conditional write. If the alias exists, it returns 409.
It returns 201 with the short URL.
Read path.
Browser sends GET /aZ3k9Qx.
The redirect service checks the cache. On a hit it answers immediately.
On a miss it reads the database, checks expires_at and status, fills the cache, and answers.
It emits a click event asynchronously.
Step 6: Deep Dive
Interviewers pick the hardest part and push. For a URL shortener spend most time on key generation and caching.
6.1 How do we generate unique short keys?
We need a 7-character base62 key that is unique, fast and hard to guess.
Two Ways to Get a Key (and Why KGS Wins)Comparison
Hash the URL
check-and-retry on every write
1
Hash the long URL
SHA-256, then base62 encode
2
Keep the first 7 characters
discards most of the hash
3
Check the database
is this key already taken?
4
On collision, try again
loop until a free key is found
Collision check and retry loop while the user waits
Same URL always gives the same key
Simple, but slow and stateful on the write path
Pre-generate keys (KGS)
take one key and insert
1
KGS creates random keys offline
drops any already used
2
Pool of unused keys
moved to used on hand-out
3
Server fetches a batch of 1,000
keeps them in memory
4
A write takes one key and inserts
no loop, no retry
No collision handling on the request path
Keys are random, so not guessable
One more component to run and replicate
Fastest write path; worth the extra service
Key point. The uniqueness check does not disappear. It moves offline, where nobody is waiting.
Pre-generating keys moves the uniqueness check off the request path.
Option A: hash the long URL. Compute SHA-256, base62-encode, keep 7 characters. Cutting a hash makes collisions (two URLs producing one key) likely at billions of rows, and the same URL always yields the same key. You must check the database and retry while the user waits.
Option B: random key plus check. Generate a random key and insert conditionally. With 30 billion of 3.5 trillion keys used, a random key is taken less than 1% of the time, so retries are rare. A good simple first answer.
Option C: pre-generated keys (KGS). Recommended. A separate service generates random unique keys ahead of time in two tables, unused_keys and used_keys. A shortening server asks for a batch (say 1,000 keys), KGS marks them used immediately, and the server hands them out from memory. A write is one insert with no check and no loop.
Details an interviewer will probe:
A server crashes holding unused keys? Those keys are lost. Fine: we have 3.5 trillion and need 30 billion.
Two servers get the same key? KGS marks keys used before returning them, from a single place guarded by an atomic update.
KGS a single point of failure? Yes unless replicated. Run a standby, and let servers keep a local buffer to survive a short outage.
Why still use a conditional write? Defense in depth, and custom aliases need it.
A fourth idea is a counter range: each server reserves a block of sequential numbers and base62-encodes the next one. It is collision-free and cheap, but sequential keys are guessable. Mitigate by scrambling the number with a reversible bit-shuffle.
Trade-off thinking. Hashing is stateless but collision-prone. Random keys are simple but need retries. KGS adds a component but gives the cleanest write path. Counter ranges are cheapest but expose ordering.
6.2 Caching the read path
Pattern: cache-aside. The application checks the cache; on a miss it loads from the database and fills the cache.
Eviction: LRU. When full, drop the least recently used entry. Link traffic has strong temporal locality, so LRU keeps hot links.
Sizing. 40 GB, spread across several nodes partitioned by short_key, so one node failing loses only part of the cache.
TTL (time to live). Each entry lives for the smaller of one day and the time left until expires_at, so an expired link cannot be served forever.
Negative caching. Cache "key does not exist" for 30 to 60 seconds so attackers probing random keys cannot hammer the database.
Invalidation on delete. Delete the cache entry when a link is disabled. The short TTL is the safety net.
Expected result: 90% or higher hit rate, cutting database traffic 10x.
6.3 Partitioning and replication
At 15 TB we partition (also called shard) the table: split rows across machines, each holding a subset.
Partitioning and Replication of the URL TableArchitecture
Key point. Random keys hash evenly, so no partition becomes hotter than the others.
hash(short_key) picks the partition. Each partition has a leader and replicas in other zones.
Partition by hash of short_key. Keys are random, so rows spread evenly. Range partitioning (A-F, G-M) would be uneven and create hot partitions.
Consistent hashing. With hash(key) mod N, adding a machine remaps almost every key. Consistent hashing places machines and keys on a ring so adding or removing a machine moves only about 1/N of the keys. Managed stores do this for you; just name it.
Replication. Each partition keeps 3 copies on different machines or zones. A replica is a copy of data on another machine, so losing one machine loses no data and reads continue. Writes go to a leader and are copied to replicas.
Read-your-write. A user who creates a link and immediately clicks it must not get a 404 from a stale replica. Read from the leader briefly, or have the shortening service warm the cache after insert.
6.4 Redirect type, analytics and abuse
301 vs 302. A 301 is permanent: browsers may cache it, so later clicks may never reach us. That cuts load but breaks analytics and makes edits or expiry unreliable. A 302 is temporary: every click reaches us, so we can count, expire and change it. With analytics and expiry, choose 302. If cost is the only concern and links never change, 301 is defensible.
Click analytics without slowing redirects. The redirect service publishes a click event to a message queue (a durable buffer where producers append messages and consumers read them later at their own pace). Background workers aggregate events into an analytics store. If the queue or workers fail, redirects keep working.
Key point. Asynchronous analytics keeps the redirect path small and fast.
If the queue or workers fall behind, redirects are unaffected.
Abuse and security.
Rate limit creation per user and per IP at the gateway.
Check destinations against a malware and phishing blocklist asynchronously; set status = blocked if flagged.
Use random keys so private links cannot be enumerated, but never rely on key secrecy for real access control.
Allow only http and https schemes, preventing javascript: and file: redirects.
Step 7: Bottlenecks and Failure Handling
Bottlenecks
Database overload.Cause: cache misses or a cache outage. Mitigation: high hit rate, read replicas, request coalescing (simultaneous misses for one key trigger one database read).
Cache cold start.Cause: a restarted cache is empty. Mitigation: warm gradually, run several nodes, rate limit database fallback traffic.
Hot keys.Cause: a viral link overloads one cache node. Mitigation: replicate the entry across nodes, add a small in-process cache with a few seconds of TTL on each redirect server, and in extreme cases serve from a CDN.
Key exhaustion.Mitigation: monitor unused_keys and alert at 20% remaining. At 7 characters this is decades away.
Queue backlog.Cause: clicks arrive faster than workers process. Mitigation: scale workers by queue depth. Redirects are unaffected.
Failures
Redirect server fails. The load balancer health check removes it; being stateless, others take over.
Cache node fails. Its keys fall through to the database; consistent hashing remaps only that node's keys. Rate limit the fallback during recovery.
Database node fails. A replica is promoted to leader. Writes to that partition pause briefly while cached redirects keep succeeding.
KGS fails. Servers use their local key batches while the standby takes over.
Availability zone fails. All tiers run in two or three zones.
Graceful degradation. If the database is down and a key is not cached, return 503 with Retry-After. Never redirect to a guess.
Interview tip. Do not list failures as a checklist and stop. Pick the two most likely (cache failure, partition failure), explain what the user sees, and name what you would monitor: redirect p99 latency, cache hit rate, error rate, unused-key count, queue depth.
Solid arrows are synchronous requests. Dashed arrows are asynchronous or fallback paths.
Request flow
Create: client, gateway (auth, rate limit), shortening service, key from the KGS batch, conditional insert into the partitioned database, response. Redirect: client, gateway, redirect service, cache (or database on a miss), 302 response, click event emitted.
Data flow
Long URL and key live in the partitioned, replicated URL database (source of truth). Hot rows live in the cache. Click events flow redirect service, queue, workers, analytics store. Unused and used keys live in the KGS store.
Background processing
KGS refills the key pool. Workers aggregate clicks. A cleanup job deletes expired rows and cache entries. A scanner checks new URLs against a malware list.
Critical design decisions
Read/write separation, because reads are 100x writes.
A cache holding the hottest 20%, removing about 90% of database load.
7-character base62 keys from a KGS, for collision-free, unpredictable keys without retry loops.
A key-value store partitioned by hashed key, because the only query is lookup by key.
302 redirects with asynchronous analytics, keeping the redirect path small and fast.
If time remains, discuss multi-region: replicate the URL table to every region so redirects are served locally via latency-based DNS. Creation can stay single-region, or each region can own its own key range to keep keys unique.