Design a URL Shortener
How to design a URL shortener in an interview, covering short-code generation, caching, click counting, and what to say about failures.
On this page
A URL shortener takes a long link and returns a short one, such as sho.rt/008sudj. When anyone opens the short link, the service redirects them to the long one. The design has several parts that interviewers like to probe: a workload where reads far outnumber writes, a way to create unique codes on many servers without collisions, a cache that serves most of the traffic, and a database that must not lose a link once it has been created.
This case study follows the steps in A Framework for Any Design. Try each "Your turn" box before you read the section after it.
Clarify the problem
The prompt is one sentence long, so the interviewer first checks whether you ask about scope before drawing anything. Ask about features, then scale, then what must keep working when something fails.
Design a URL shortener.
Users submit a long URL, get a short one back, and opening the short one redirects to the long one. Can users choose a custom alias? Do links expire? Do we need to count clicks?
Custom aliases are required. Links live forever unless the user sets an expiry. A click count per link is enough, and there is no need for dashboards.
How many links are created, and how often is each one opened?
About 100 million new links a month, and reads are about 100 times the writes.
Then the system is read-heavy and the redirect is the path to protect. I will aim for a redirect that adds under 20 ms on our side and keeps working even when link creation is down. A link that was created must never be lost. I will leave out user accounts, spam scanning and dashboards unless you want them included.
Write the agreed requirements down.
- Functional requirements: create a short link for a long URL with an optional custom alias and expiry date, redirect a short code to its long URL, and count the clicks on each link.
- Non-functional requirements: redirects add under 20 ms and are highly available, created links are never lost, and codes are short.
- Out of scope: user accounts, abuse scanning and analytics dashboards.
Estimate the scale
Convert the interviewer's monthly numbers into rates per second and into bytes. A month has about 30 × 86,400 ≈ 2.6 million seconds.
- Writes: 100 million ÷ 2.6 million ≈ 40 new links a second on average. Assuming peaks of 5 times the average, that is 200 a second.
- Reads: 100 times the writes is 4,000 redirects a second on average and 20,000 at peak.
- Code length: with 62 characters (0-9, a-z and A-Z), 6 characters give 626 ≈ 57 billion codes and 7 characters give 627 ≈ 3.5 trillion. Five years of writes is 6 billion links, so 7 characters leave plenty of room.
How much storage do the link records need after five years?
- 100 million new links a month
- About 500 bytes per record (code, long URL, timestamps)
- Nothing is deleted
Show the working
- 100 million × 12 months × 5 years = 6 billion links
- 6 × 109 × 500 B = 3 × 1012 B = 3 TB
- With 3 copies for durability, that is about 9 TB of disk
Estimate 3 TB (anything from 1 TB to 10 TB is a good answer)
This is too much for one machine but small for a cluster, so the data needs partitioning eventually but not on the first day.
Write the two endpoints with their method, path, request body and response, including the error cases.
Compare with a model answer
One endpoint creates a link (POST /api/links with the long URL and an optional alias and expiry, returning the code). The other is the redirect (GET /{code}, returning a redirect status with a Location header). The decision worth discussing is which redirect status to use.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
POST /api/links
body: { "long_url": "https://...", "alias": "spring-sale"?, "expires_at": "2027-01-01"? }
201 Created { "code": "008sudj", "short_url": "https://sho.rt/008sudj" }
400 Bad Request the URL is not valid
409 Conflict the alias is taken
GET /{code}
302 Found Location: https://the-long-url...
404 Not Found no such code, or it has expiredThe redirect can use status 301 (moved permanently) or 302 (found). Browsers cache a 301, so repeat clicks from the same browser never reach your servers. That reduces load, but you cannot count those clicks and you cannot change the target later. A 302 is not cached, so every click comes through. The requirements include click counts, and the estimate shows that the extra traffic is small, so use 302.
What does one record hold, how is it looked up, and which kind of database fits?
Compare with a model answer
There is one record per code. Every read is a lookup of the row for one code, every write is an insert, and nothing needs a join. That is a key-value access pattern.
Model the data
code VARCHAR(32) PRIMARY KEY -- "008sudj" or a custom alias such as "spring-sale"
long_url TEXT -- up to 2 KB
created_at TIMESTAMP
expires_at TIMESTAMP NULL
clicks BIGINT -- updated in batches, not on every clickThe hot path looks up one row by primary key. It has no joins and no range scans, and a row never changes except for its click count. A key-value or wide-column store, such as DynamoDB or Cassandra, fits this pattern, and it partitions by key without extra work, which is what we need at 3 TB and beyond. A relational database with read replicas also works at this size, and it is a reasonable choice if the team already runs one.
Custom aliases are stored in the same table as generated codes. Because code is the primary key, an "insert if absent" operation makes alias claims safe. If two users try to claim spring-sale at the same moment, only one insert succeeds and the other receives the 409 response.
Expired links are not served, because the redirect service checks expires_at, but the rows still take up space. A background job deletes rows whose expiry time has passed, or the store's built-in time-to-live feature does it if it has one. A custom alias can also equal a code that the generator would produce later, such as an alias typed as 008sudj. The generator therefore uses the same insert-if-absent operation and takes the next number when the insert fails.
Sketch both paths. What sits between a browser and the database on a redirect, and where does a new code come from?
Compare with a model answer
Separate the read path from the write path so that each can scale on its own. A stateless redirect service reads through a cache in front of the store, and a create service produces the codes.
High-level design
Redirects outnumber creates by 100 to 1, so they get their own service and their own cache. Every new link needs a code that no other server will produce, so a small ID allocator gives each create server a block of numbers to use.
1A user submits a long URL. The load balancer sends
POST /api/linksto any create server.2This server reserved the numbers 125,000,000 to 125,000,999 earlier, so it takes the next unused one without asking anyone. That number is 125,000,017.
- code
- 008sudj
3The server writes the number in base 62 and pads it to 7 characters, which gives the code
008sudj.- code
- 008sudj
4The server inserts the row. The store replicates the row to other nodes before it confirms the write, so the link survives the loss of a disk.
- code
- 008sudj
5The short URL goes back to the user. The whole write needed one store insert and no other coordination.
- code
- 008sudj
6Someone opens
sho.rt/008sudj. The load balancer sends theGETrequest to a redirect server.- code
- 008sudj
7The redirect server asks the cache for the code. The link is new, so the cache does not have it.
- code
- 008sudj
8The server reads the row by primary key and stores a copy in the cache. A link's target never changes, so the copy cannot go stale.
- code
- 008sudj
- status
- 302
9The browser receives
302 Foundwith the long URL in theLocationheader and follows it.- code
- 008sudj
- status
- 302
10The next click on the same link is a cache hit. Most redirects end this way, which is why the store can stay small.
11If the allocator goes down, each create server keeps using the numbers left in its block. With 40 writes a second spread over 10 servers, a block of 1,000 lasts about 4 minutes, which is time to fail over.
Deep dives
Interviewers usually push on three parts of this design: how the codes are generated, how redirects stay fast, and how clicks are counted without slowing the redirects down.
Generating short codes
Many create servers run at once, and each must produce a code that no other server will produce, without a slow check against the database on every request. There are three common approaches.
Hashing the long URL. The server computes a hash of the URL and encodes the first 7 characters. The same URL always produces the same code, so duplicates are easy to detect. The problem is that a truncated hash collides, so every insert needs a check and a retry. If two users submit the same URL they also share one code, which means one user's deletion or expiry affects the other. This approach makes sense only when deduplication is a requirement.
Random codes with a retry. The server picks 7 random characters and inserts the row with "insert if absent". If the code already exists, it picks another. No servers need to coordinate, and the codes cannot be guessed. With 6 billion links stored out of 3.5 trillion possible codes, a new code collides with probability 6 × 109 ÷ 3.5 × 1012 ≈ 0.2%, which is about one retry in every 600 creates. Choose it when codes must not be guessable.
Counter blocks encoded in base 62. A small allocator service hands each create server a block of 1,000 consecutive numbers. The server uses the numbers one at a time, converts each to base 62 and pads it to 7 characters. Codes never collide, and each server contacts the allocator only once for every 1,000 links. The costs are that the allocator must be highly available and that the codes are sequential, so anyone can step through them. If guessability worries the interviewer, scramble each number with a reversible function before encoding it.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Hash the long URL | The same URL always gets the same code, so duplicates are cheap to detect. | A truncated hash collides, so every insert needs a check and a retry, and two users share one code. | Use it when deduplication matters more than anything else, which is rare. |
| Random code, retry on collision | It needs no coordination between servers, and the codes cannot be guessed. | Every create needs an insert-if-absent, and collisions become more frequent as the table fills. | Use it when codes must not be guessable. |
| Counter blocks in base 62 Usual default | Codes never collide, and each server calls the allocator only once per 1,000 links. | Codes are sequential unless you scramble them, and the allocator must be highly available. | Use it for public links where guessable codes are acceptable. |
Keeping redirects fast
A small share of links receives most of the clicks, so a cache with least-recently-used (LRU) eviction in front of the store serves most redirects in about a millisecond. Because a link's target never changes, writes do not need to invalidate anything. There are two exceptions. When a link is deleted, delete its cache key as well. And because a cached entry could outlive the link's expiry time, the redirect service checks expires_at on every redirect, so an expired link is never served from the cache. When a link suddenly goes viral, many requests can miss the cache at the same moment and reach the store together, which is the cache stampede problem described in Caching.
Counting clicks without slowing redirects
Updating a counter on every click puts a database write on the hot path. A viral link would also make one row the busiest in the database. Instead, the redirect service publishes a click event to a queue and returns the redirect immediately. A worker adds up the events for each code and writes one update per link every few seconds.
request and replyasynchronous message
The trade-off to state in the interview is that the counts lag by a few seconds, and events lost from the queue make them slightly too low. That is acceptable for a click count. If clicks were billed, you would make the events durable and make the processing idempotent so that a retried event is not counted twice.
Bottlenecks and failures
At 10 times the load, the system must handle 200,000 redirects a second at peak and 30 TB of data after five years. Each part scales in a different way.
- Redirect servers hold no state, so you add more of them.
- The cache becomes a cluster that splits keys with consistent hashing, so adding a node moves only a small share of the keys.
- The store is partitioned by a hash of
code, so that sequential codes from the same allocator block do not all land on one partition. - The allocator is barely affected. Blocks of 1,000 at 2,000 writes a second mean only 2 requests a second.
The table lists what happens when each component fails and what you do about it.
| Component that fails | What happens | What you do |
|---|---|---|
| A redirect or create server | Requests sent to it fail. | Health checks remove it from the load balancer within seconds, and the other servers absorb its share. |
| A cache node | The keys it held are read from the store instead. | Size the store for the extra reads, or run replicas of each cache node. |
| A store node | One partition loses one of its three copies. | The other replicas keep serving, and the failed node is rebuilt from them. |
| The ID allocator | Create servers cannot get new blocks. | Servers keep working from their current blocks. Run the allocator on three nodes that agree through a consensus store so that it rarely goes down. |
| The click queue | Click counts stop updating. | Nothing changes for redirects, which is the reason counting is asynchronous. |
What a strong answer sounds like
The levels differ in how much the numbers drive the design and in how well the trade-offs are argued.
| Level | What the answer does |
|---|---|
| Junior | Proposes a service and a database, builds the code from a hash of the URL, and reaches a working design after the interviewer asks about collisions. |
| Mid-level | Estimates traffic and storage, separates reads from writes, adds a cache and explains why, and compares two ways of making codes. |
| Senior | Starts from the read-to-write ratio, chooses 302 because of click counts, moves counting off the hot path, and says what fails first at 10 times the load and what the design leaves out. |
Why not just hash the URL?
A 7-character piece of a hash collides, so I would still need a check and a retry on every insert, and two users who submit the same URL would share one code. Counter blocks never collide and cost one allocator call for every thousand links. The cost is that the codes are guessable. If that matters, I would scramble each number before encoding it.
What happens to creates if the allocator goes down?
Each create server keeps using the numbers left in its block. At 40 writes a second over 10 servers, a block of 1,000 lasts about 4 minutes, which is enough time to fail over. Redirects are not affected at all.
Follow-up questions
How would you run this in several regions?
Serve redirects in every region from a local cache and a local replica of the store. Replication lag delays a brand-new link by a second or two at most. Give each region its own range of numbers so that creates never coordinate across regions.
What if the same long URL is submitted twice?
By default each submission gets its own code. Returning the same code would need an index on the long URL, and it would let one user's expiry or deletion affect another user's link. If the interviewer wants deduplication, offer it per user, so that each user gets one code for each URL.
How do you stop abuse?
Apply a rate limit to creates per API key and per IP address, and check each new URL against a blocklist of known bad domains. Scan new URLs asynchronously as well, so that a link found to be malicious later can be disabled.
How do you delete a link quickly?
Mark the row as deleted in the store and delete its key from the cache. Because the redirect is a 302, browsers have not cached it, so the next click sees the change and gets a 404.
What if one link gets a million clicks a minute?
That is about 17,000 requests a second for a single key, and all of them land on the one cache node that holds it. Each redirect server can keep a copy of that link in its own memory for a few seconds, so most requests are answered locally and the cache node is not overloaded.
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".