Design a URL Shortener
The URL shortener is the most common first system design question, because it looks simple and hides real choices: how to make short keys that never collide, how to serve thousands of redirects a second in a few milliseconds, and how to count clicks without slowing anything down. This lesson walks through the whole 45-minute answer in the order you would give it in an interview.
What you will learn
- Agree on requirements and size the system before drawing any boxes.
- Seven base62 characters give about 3.5 trillion keys; hand out counter ranges so servers never collide.
- The redirect path is the hot path: CDN, then an in-memory cache, then a key-value store.
- Choose 302 over 301 if you need to count every click.
- Keep analytics off the redirect path with an event log and asynchronous aggregation.
- Plan for one viral link, cache failures and abuse before the interviewer asks.
In this lesson
- The question
- Step 1: Clarify the requirements
- Step 2: Back-of-the-envelope estimates
- Step 3: The API
- Step 4: The data model
- Step 5: The high-level design
- Step 6: Generating short keys
- Step 7: The redirect path
- Step 8: Counting clicks
- Step 9: Scaling and failures
- Step 10: Expiry, deletes and abuse
- Step 11: Running it in several regions
- Step 12: The follow-up questions
- Recap
Short on time? Read the answer outline for design a URL Shortener.
Practice this question with MaxThe question
Welcome to lesson one of the InterviewDryRun system design course. Today we are designing a URL shortener, the service that turns a long, ugly link into something short you can paste into a message, and then sends anyone who clicks it to the right place.
It is one of the most common system design interview questions, and it is often the first one people meet. It looks easy. That is exactly why it is useful to interviewers: the simple surface hides real decisions about key generation, caching, consistency and scale, and the way you handle those decisions tells them how you think.
Max asks
“Design a service that turns long URLs into short links, redirects visitors quickly, and counts clicks. Walk me through how you would build it.”
That is how Max, our AI interviewer, asks it. Over the next quarter of an hour we will answer it the way a strong candidate would in a real forty-five minute interview. We will clarify the requirements, estimate the load, design the API and the data model, sketch the high-level design, then go deep on key generation, the redirect path, analytics, scaling and failure. At the end we will take the follow-up questions interviewers like to ask.
Step 1: Clarify the requirements
- 01Create a short linkGive a long URL, get back a short code
- 02RedirectVisiting the short link sends you to the long URL
- 03Custom alias (optional)Let a user pick the code, if it is free
- 04Expiry (optional)Links can stop working after a date
- 05Click countsHow many times, roughly when and from where
The first five minutes of any system design interview are for requirements. Do not draw a single box yet. Ask questions, and write the answers down where the interviewer can see them, because everything later depends on them.
The core is two things. A user gives us a long URL and gets back a short code. And anyone who visits the short link is redirected to the original long URL. Everything else is negotiable.
Then ask about the extras. Can users choose their own alias, like a product name? Do links expire? In most interviews the answer is yes to both, but as optional features. Say that you will design for them without letting them complicate the core.
Finally, analytics. The question says count clicks. Ask how fresh those numbers need to be. If the answer is that a dashboard a minute behind is fine, that single answer will save us a lot of work later, because it means counting does not have to happen on the redirect itself.
- 01Fast redirectsTens of milliseconds at the 99th percentile
- 02Highly availableA broken redirect breaks every place the link was shared
- 03Never collideTwo long URLs must never get the same code
- 04Read heavyFar more redirects than new links
- 05Not guessableCodes should not be trivially enumerable
Now the non-functional requirements, which usually matter more. Redirects must be fast, tens of milliseconds, because they sit in front of every click. And the service must be highly available: if we go down, every link anyone ever shared stops working at once.
Correctness has one hard rule. Two different long URLs must never get the same short code, because then somebody's link silently sends people to the wrong site. We can tolerate a stale click counter. We cannot tolerate a collision.
Two more. The system is very read heavy, with far more redirects than new links. And codes should not be easy to guess in sequence, so nobody can walk through every private link we store. Notice the trade-off we have just chosen: availability and speed over strong consistency, everywhere except key creation.
Step 2: Back-of-the-envelope estimates
Next, a few minutes of estimates. The point is not precise arithmetic. The point is to find out which parts of the system are big, so you know where to spend your design time. Say your assumptions out loud and round aggressively.
Let us assume one hundred million new links a month. A month has roughly two and a half million seconds, so that is about forty writes a second on average. That is small. A single database could handle it.
Now reads. Ask the interviewer for the ratio, or assume one hundred reads for every write. That gives about four thousand redirects a second on average.
Traffic is never flat, so multiply by five for the peak: around two hundred writes and twenty thousand redirects a second. Twenty thousand reads a second is where the design gets interesting.
For storage, keep links for five years. One hundred million a month, times twelve, times five, is six billion links. At around five hundred bytes each, with the long URL, the code, the owner and a few timestamps, that is about three terabytes. Too much for one machine's memory, comfortable for a partitioned store.
And the cache. Clicks follow a power law: a small share of links gets almost all the traffic. If we cache the hottest twenty percent of recent links, we are talking tens of gigabytes, which fits in a small in-memory cache cluster. So the shape of the system is now clear: writes are easy, reads are heavy and very cacheable, and storage is big but simple.
One more number that people skip: bandwidth. A redirect response is tiny, a few hundred bytes of headers, so even twenty thousand a second is only a few megabytes a second leaving our servers. That tells the interviewer something useful. The challenge here is not moving bytes, it is answering a very large number of very small lookups quickly. Every design choice that follows is about lookups per second and latency, not throughput.
Step 3: The API
POST /api/links
{ "url": "https://example.com/very/long/path",
"alias": "launch", // optional
"expiresAt": "2027-01-01" } // optional
→ 201 { "code": "aZ3k9Qx", "shortUrl": "https://sho.rt/aZ3k9Qx" }
GET /{code}
→ 302 Location: https://example.com/very/long/path
→ 404 if unknown, 410 if expired
GET /api/links/{code}/stats
→ 200 { "clicks": 18234, "byDay": [...] }With the numbers agreed, define the API. Keep it small. Creating a link is a POST with the long URL and, optionally, a custom alias and an expiry date. It returns the short code and the full short URL.
The redirect is a plain GET on the code. It answers with a redirect status and a Location header pointing at the long URL. If the code does not exist we return not found, and if the link has expired, gone. Interviewers like it when you mention the error cases without being asked.
And a stats endpoint for the owner of the link. Mention that creating links and reading stats need authentication and rate limits, while the redirect itself must stay anonymous and as cheap as possible.
Step 4: The data model
| Column | Type | Why |
|---|---|---|
| code | string, primary key | what every redirect looks up |
| long_url | string, up to 2 KB | where to send the visitor |
| owner_id | id, nullable | for stats and deleting |
| created_at | timestamp | auditing, cleanup |
| expires_at | timestamp, nullable | expiry check on redirect |
The data model is one main table. The code is the primary key, because every redirect is a lookup by code, and that is the only query on the hot path. Next to it, the long URL.
Then the owner, the creation time and an optional expiry time. Click counts do not live in this row. If they did, every redirect would become a write to the same row, and a popular link would turn into a write hot spot.
Because the access pattern is a single key lookup, with no joins and no range queries, a key-value or wide-column store fits naturally, partitioned by the code. A relational database also works at this size if you shard it by code. Say which you pick and why: here, simple horizontal scaling matters more than transactions, so I would pick a key-value store, and keep a relational database for users and billing.
Step 5: The high-level design
Now we can draw. Requests from browsers and apps arrive at a load balancer. Behind it, split the two very different workloads into two services, so each can scale on its own.
The link service handles creation. It validates the URL, picks a code, and writes the row to the links store. It handles a couple of hundred requests a second at peak, so a handful of instances is plenty.
It gets codes from a small key range service, which we will look at in detail in a moment. For now, think of it as the thing that guarantees no two servers ever hand out the same code.
The redirect service handles the twenty thousand reads a second. It is stateless, so we can run as many copies as we need behind the load balancer, in several regions.
And it reads through an in-memory cache. On a hit, which should be the large majority of requests, the redirect never touches the database. On a miss, it reads the links store and fills the cache. Before going deeper, check in with the interviewer: ask which part they would like you to dig into. It shows you are managing the time, and they often have a part in mind.
Notice what this first picture deliberately leaves out: no analytics pipeline, no edge network, no regions. Start with the simplest design that meets the core requirements, get the interviewer to agree it works, and then add parts one at a time, each one justified by a number from the estimates or a requirement from the first five minutes. Building up like this is much easier to follow than drawing twenty boxes at once, and it keeps you honest about why every part exists.
Step 6: Generating short keys
Key generation is the heart of this question, so slow down here. First, length. If codes use lower case letters, upper case letters and digits, that is an alphabet of sixty-two characters, which is why this is called base sixty-two.
Six characters give about fifty-seven billion combinations. Seven give about three and a half trillion. We need six billion over five years, so seven characters gives us hundreds of times more room than we need, which also makes random codes hard to guess.
| Approach | Good | Problem |
|---|---|---|
| Hash the URL, keep 7 chars | same URL, same code | collisions need a check and retry |
| Random 7 chars | simple, not guessable | check-and-insert on every create |
| Global counter, base62 | never collides | single point of failure, guessable |
| Key ranges per server | no collisions, no coordination per link | a range is lost if a server dies |
Now, how to make the code. There are four common approaches, and the interviewer wants to hear you compare them, not just pick one. The first is to hash the long URL, with something like a fast hash function, and keep the first seven characters. The same URL always gets the same code, which is neat, but truncated hashes collide, so you need to check the store and retry with a salt.
The second is to generate seven random characters. It is simple and the codes are not guessable, but every create becomes a check-and-insert, and as the keyspace fills up, collisions get more frequent. You need a conditional insert, one that only succeeds if the key does not exist yet, to make it safe.
The third is a single global counter, converted to base sixty-two. It never collides. But one counter is a single point of failure and a bottleneck, and sequential codes are trivially guessable: if my link is a, b, c, one, two, three, the next one is easy to predict.
The fourth fixes the counter's problems. A small coordination service, backed by something strongly consistent, hands each link server a range of, say, one million numbers at a time. The server then assigns codes from its own range with no coordination at all. If a server dies, we lose the rest of its range, and that is fine: we have trillions to spare.
This is the one I would choose, with one refinement. To stop codes being guessable in sequence, pass each number through a reversible scramble, for example a simple block cipher with a secret key, before encoding it in base sixty-two. The output is still unique, because the scramble is one to one, but neighbouring numbers no longer give neighbouring codes.
Custom aliases go through a different path. The user's alias is checked against the store with the same conditional insert, so if two people claim the same alias at the same moment, exactly one succeeds and the other gets a clear error. Keep aliases in a separate namespace or with a minimum length, so they can never clash with generated codes.
Step 7: The redirect path
Now the hot path, the redirect, in more detail. A visitor clicks a link. The first layer can be a content delivery network at the edge, close to the visitor, which can cache the redirect response for popular codes and answer without our servers being involved at all.
If the edge misses, the request reaches a redirect server, which asks the cache cluster. Use least-recently-used eviction: links that stop being clicked fall out on their own, and viral links stay in.
Only on a cache miss do we read the links store, from the nearest replica, and write the result back to the cache. Because links almost never change after creation, caching is safe. The only events that invalidate an entry are a delete or an expiry, and we can handle those with a short time to live on cached entries.
| Status | Browser does | Use when |
|---|---|---|
| 301 Moved Permanently | caches it, skips us next time | you want minimum load and latency |
| 302 Found | asks us every time | you need every click counted |
This is where interviewers often ask about the status code, so raise it yourself. A three-oh-one, moved permanently, tells the browser to cache the redirect. Next time, the browser goes straight to the long URL and we never see the click. Less load, slightly faster for the user.
A three-oh-two, found, means the browser asks us every time. That costs more traffic, but we see every click, and we can change or expire the link later. Since our requirements include click counts and expiry, choose three-oh-two, and say that out loud as a trade-off you made deliberately.
Step 8: Counting clicks
Now the analytics. The tempting mistake is to increment a counter in the database on every redirect. At twenty thousand redirects a second, mostly on a few hot links, that creates exactly the write hot spot we avoided in the data model.
Instead, the redirect server publishes a small click event, with the code, the time, the country and the referrer, to an event log, without waiting for a reply. A stream processor reads the log and aggregates, for example counts per link per minute, and writes those totals in batches to a stats store.
We can also archive the raw events in cheap object storage, so we can answer new questions later or rebuild the counts if the aggregator has a bug. The cost of this design is that stats are up to a minute behind, which we agreed with the interviewer at the start was fine. This is why that early question mattered.
If the event log is briefly unavailable, the redirect must still work. Buffer events in memory on the redirect server for a short time, and if the buffer fills, drop events rather than block redirects. Losing a few clicks is acceptable. Breaking links is not.
Step 9: Scaling and failures
- 01One viral linkEdge caching, plus a local in-process cache for the hottest codes
- 02Cache stampedeRequest coalescing: one database read per key per server
- 03Cache node failsConsistent hashing moves only that node's keys
- 04Region failsStore replicated across regions, DNS fails over
- 05Key service downServers hold a spare range, so creates keep working
Strong candidates find the weak points before the interviewer does. The classic one here is a single viral link, say fifty thousand redirects a second for one code. All of those requests land on one cache node. The edge network absorbs most of it, and each redirect server can keep a tiny in-process cache of the hottest few thousand codes for a few seconds.
Second, a cache stampede. A hot key expires or a cache node restarts, and thousands of requests miss at the same instant and all hit the database. The fix is request coalescing: on each server, only the first request for a missing key goes to the database, and the others wait for its answer.
Third, a cache node dies. If keys are spread with consistent hashing, only that node's share of keys moves to other nodes, instead of the whole cache being reshuffled and going cold.
Fourth, a whole region goes down. The links store is replicated to other regions, and since links are effectively immutable, replication lag is harmless. Traffic fails over through DNS or anycast. And if the key range service is unavailable, each link server holds a spare range in reserve, so creating links keeps working for a long while.
Step 10: Expiry, deletes and abuse
- 01ExpiryCheck on read; clean up lazily or with a time-to-live
- 02DeletesRemove the row, then evict the cache and the edge
- 03AbuseRate limits on create, scan URLs against blocklists
- 04PrivacyDo not log full IP addresses longer than needed
A few details separate a good answer from a complete one. Expiry: on every redirect, check the expiry time, and answer gone if it has passed. For cleanup, never scan the whole table. Either use the store's built-in time to live, or delete expired rows lazily when they are read, plus a slow background job over expiry-ordered data.
Deletes: remove the row, then evict the code from the cache and purge it from the edge, otherwise the link keeps working for a while after the owner deleted it. A short cache lifetime limits how long that can last.
And abuse. Link shorteners are popular with spammers, because a short link hides where it really goes. Rate limit link creation per user and per address, check new URLs against known malicious site lists, and give people a preview page option. Mentioning abuse without being asked is a strong signal of real-world experience.
Step 11: Running it in several regions
Interviewers who are happy with the single-region design often push on one more thing: what changes when we serve the whole world? Visitors should be redirected by servers near them, so we run the redirect and link services in several regions, and route each visitor to the closest one.
Each region has its own copy of the links store, and the copies replicate to each other in the background. That is safe here for a reason worth saying out loud: a link is written once and then almost never changes. So the usual problem with asynchronous replication, two regions disagreeing about the current value, barely exists. The only window is the first moment after a link is created.
That window is real, though. Someone creates a link in region A and pastes it into a group chat, and a friend in region B clicks it a fraction of a second later, before the copy has arrived. Region B finds nothing. The fix is cheap: on a miss, before answering not found, the redirect service asks the home region of that code. The miss path is rare, so this extra hop costs almost nothing overall.
How does region B know which region is home for a code? Put the answer into the key itself. The key range service gives each region its own block of ranges, so the number behind every code tells you where it was born. Two regions can create links at the same moment without ever talking to each other, and they still cannot collide.
Custom aliases are the one place where regions must agree before answering, because two people in two regions could ask for the same alias at the same instant. Route all alias claims to one primary region, which does the conditional insert. Alias creation is rare, so the extra distance is fine. This is a nice pattern to name in interviews: keep the rare, conflicting writes on a single strongly consistent path, and let the common, conflict-free ones run everywhere.
Step 12: The follow-up questions
Max asks
“A link goes viral and gets fifty thousand redirects a second. What happens to your system?”
We covered this one: the edge network caches the redirect, each redirect server keeps the hottest codes in process, and request coalescing protects the database. The key point to say is that a single hot key cannot be fixed by adding more cache nodes, because one key lives on one node. You need copies closer to the user.
Max asks
“Two users try to claim the same custom alias at the same moment. How do you make sure only one gets it?”
With a conditional write: insert only if the key does not already exist. The store makes the decision atomically, so exactly one insert wins and the other receives a conflict error, which we show to the user as alias taken. Never check first and then insert in two steps, because two requests can both pass the check.
Max asks
“Should the same long URL always get the same short code?”
It depends on the product, so say that and then pick. Reusing codes saves a little storage, but different users want separate stats and separate expiry for the same destination. So I would give each create its own code, and optionally let a single user see their existing link for a URL they already shortened.
Max asks
“How would you stop someone from walking through every code to find private links?”
Three layers. First, the scrambled codes we already have: neighbouring numbers give unrelated codes, so there is no sequence to walk. Second, the space is sparse, six billion used out of three and a half trillion, so a random guess almost always misses. Third, rate limit not-found answers per address, because a scanner produces a flood of misses while a real visitor almost never does. For links that are truly private, offer a longer code or require sign-in, since a short code alone is never a secret.
Max asks
“Your links store has a bad day and reads take two seconds. What do users see?”
Most of them see nothing, which is the point of the cache layers. Popular links are answered from the edge and from the cache cluster, which together serve the large majority of redirects. Only cold links feel it. Protect the store with a timeout of a few hundred milliseconds and a circuit breaker, so slow reads fail fast instead of piling up threads on the redirect servers, and keep serving whatever the caches hold. Say that you would rather show an error for a rare cold link than let a slow database take down the whole redirect fleet.
Recap
- 010 to 5: requirementsCreate, redirect, alias, expiry, counts. Fast and available.
- 025 to 10: estimates40 writes, 4,000 reads a second; 6 billion links; 3 TB
- 0310 to 20: API, data, boxesTwo services, a cache, a key-value store
- 0420 to 35: deep divesKey ranges with base62, the read path, 302, analytics log
- 0535 to 45: scale and failureViral link, stampede, regions, abuse
Let us put it all together as a plan for the forty-five minutes. Five minutes of requirements, ending with fast, available redirects and no collisions. Five minutes of estimates, ending with the conclusion that this is a read-heavy, cache-friendly system.
Ten minutes for the API, the data model and the high-level boxes. Fifteen minutes of deep dives, on key generation with ranges and base sixty-two, the redirect path with its cache and the three-oh-two choice, and analytics through an event log.
And the last ten minutes on scaling and failure: the viral link, the cache stampede, losing a region, serving several regions, and abuse. If you can say all of that calmly, in that order, with the trade-offs out loud, you have given a strong answer.
Watching an answer is not the same as giving one. The best way to make this stick is to say it out loud, under time pressure, to someone who pushes back. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written version of this lesson, with every diagram, is on the site too. See you in lesson two.
Now say it out loud
Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.