URL shortener
What we are building
Section titled “What we are building”A URL shortener turns a long address into a short one, such as short.example/a8Kz3Qp, and sends whoever opens the short one to the long one. It looks like a toy, and it is a good first case study for that reason: the whole system is two operations, and almost every design question in it is about numbers.
Functional requirements. Create a short link for a long URL. Open a short link and be redirected to the long URL. Optionally give a link an expiry time. Delete a link. Custom aliases, click statistics and abuse checks are real features and are left out here, so that the lesson stays on the core.
Non-functional requirements. These are the targets we choose for this lesson, not figures from a real service. A redirect answers in under 100 ms at the 99th percentile. Redirects are available 99.9% of the time, because a link printed on paper or in a book has to keep working. A link that was created is never lost.
Scale. 100 million new links a month. Every link is opened about 100 times, so 100 redirects for each link created. Links are kept for 5 years.
Mental model. A URL shortener is a very large dictionary that is read a hundred times for each time it is written. The writes are easy. The design is about answering a huge number of reads from a table that never changes once a row exists.
Estimate before you design
Section titled “Estimate before you design”The requests per second lesson gives the method: a volume per month is divided by the seconds in a month, then multiplied by how much busier the busiest moment is. Here it is for this system. The assumptions are in the table, so that you can change them and see what moves.
| Quantity | Working | Result |
|---|---|---|
| Seconds in a month | 30 × 86,400 | about 2.6 million |
| New links per second, on average | 100 million ÷ 2.6 million | about 40 |
| Redirects per second, on average | 40 × 100 | about 4,000 |
| Peak, assuming 2.5 times the average | 4,000 × 2.5, and 40 × 2.5 | about 10,000 requests per second, 100 of them new links |
| Links after 5 years | 100 million × 60 months | 6 billion |
| Storage | 6 billion × about 500 bytes a row, with its index | about 3 TB |
| Traffic out | 10,000 × about 500 bytes of response | about 5 MB/s, which is 40 Mbit/s |
| Code length | 62 to the power 6 is 56.8 billion, and 62 to the power 7 is 3.52 trillion | 7 characters |
| Cache memory, if the hottest 100 million links are cached | 100 million × about 200 bytes | about 20 GB |
The 2.5 for the peak, the 500 bytes and the 200 bytes are assumptions, and the 100 to 1 ratio is a teaching figure. Three things follow from the arithmetic whatever the exact values. Storage is small: 3 TB fits on one machine, and the storage lesson would call it a modest dataset. Bandwidth is small: 40 Mbit/s is not a constraint. The request rate is the problem: if one database answers an indexed lookup in about 5 ms, 4 at a time, it can do 800 lookups per second, and 10,000 per second is 12.5 of them. The first limit of this system is reads, not data size, and the five stages below follow that.
A 7-character code over 62 symbols has room for 3.52 trillion, which is 587 times the 6 billion links we expect. Six characters would hold the 6 billion, with room to spare, but the section on key generation shows why the extra character is worth having.
The API and the data
Section titled “The API and the data”Two calls carry almost all the traffic.
POST /links {"url": "https://example.org/a/very/long/path", "expiresAt": null}201 Created {"code": "a8Kz3Qp", "shortUrl": "https://short.example/a8Kz3Qp"}
GET /a8Kz3Qp302 Found Location: https://example.org/a/very/long/pathAn unknown code answers 404 Not Found, and a link that has expired answers 410 Gone. Because a client can time out and send the same POST again, a real service lets the client send an idempotency key; without one the retry makes a second code for the same URL, which wastes a code and does no other harm.
The data is one table, read by its primary key and by nothing else.
| Column | Meaning |
|---|---|
code |
The primary key: 7 characters of base 62. Every redirect is a lookup by it. |
long_url |
The destination. |
created_at, expires_at |
When it was made, and when it stops working (empty for never). |
owner |
Who created it, so that they can delete it. |
A lookup by primary key is the simplest query a database has. That is why the design can be carried by a cache and by replicas, and does not need anything clever in the data model.
Five stages, each forced by a number
Section titled “Five stages, each forced by a number”The lab starts with the simplest design that works and adds one thing at a time. Each stage is designed for a load, and the slider raises the load to 3 times and 10 times that, which shows where the stage runs out. Every figure is model output with illustrative inputs, and the model notes under the lab list what it leaves out.
A service that turns long links into short codes and redirects the visitors who open them. For every link created about a hundred visitors open it, so reads dominate. Step through five stages, each adding the one thing the previous stage’s numbers called for, and raise the load to see what breaks.
Start simple: one API and one database
Design load of this stage: 100 req/s
- What we add
- One API server looks the short code up in one database and answers with a redirect. A new link takes the next number from a counter kept in a database row, written as a 7-character code in base 62.
- Why: the number that forced it
- At 100 requests per second (99 redirects and 1 new link) a small database that answers an indexed lookup in about 5 ms, 4 at a time, is at 13% of its 800 queries per second. Nothing else is close to its limit.
- What it costs
- Cheap and easy to run: one application, one database, one thing to back up. The price is that every redirect is a database query, and each part is a single point of failure.
- What breaks next
- At 10 times the load, 1,000 requests per second, the lookups alone ask the database for more than its 800 queries per second: it is overloaded and a fifth of the requests fail.
Each dot stands for many requests. The numbers show the real rate.
No bottleneck: every component has headroom.
Figures at this load
- Busiest component
- DatabaseHealthy13% of its capacity
- p95, whole request
- 18 ms
- p99, whole request
- 25 ms
- Requests served
- 100%100 req/s
- Requests failed
- 0%0 req/s
- Bottleneck
- none
| Component | State | Utilisation | Offered (req/s) | Served (req/s) | Rejected (req/s) | p50 | p95 | p99 |
|---|---|---|---|---|---|---|---|---|
| Browsers and apps | Healthy | <1% | 100 | 100 | 0 | 0 ms | 0 ms | 0 ms |
| Redirect API | Healthy | 1% | 100 | 100 | 0 | 1.4 ms | 6 ms | 9.2 ms |
| Database | Healthy | 13% | 100 | 100 | 0 | 3.5 ms | 15 ms | 23 ms |
| Key counter (one database row) | Healthy | <1% | 1 | 1 | 0 | 2.1 ms | 9 ms | 14 ms |
- Traffic
- 100 req/s
- Successful
- 100 req/s
- Error rate
- 0%
- Mean latency
- 7.6 ms
All stages at a glance
Each cell is the engine’s steady state for that stage at that load: the busiest component, how much of its capacity it uses, and the share of requests that fail.
| Stage | Design load | Design load | 3× the design load | 10× the design load |
|---|---|---|---|---|
| 1. Start simple: one API and one database | 100 req/s | 100 req/sDatabase: 13%none fail | 300 req/sDatabase: 38%none fail | 1K req/sDatabase: 125%20% fail |
| 2. Add a cache for redirects | 1K req/s | 1K req/sRedirect API: 13%none fail | 3K req/sRedirect API: 38%none fail | 10K req/sRedirect API: 125%20% fail |
| 3. Run several API servers behind a load balancer | 10K req/s | 10K req/sDatabase: 74%none fail | 30K req/sDatabase: 223%3.3% fail | 100K req/sDatabase: 330%61% fail |
| 4. Add read replicas | 10K req/s | 10K req/sKey counter (one database row): 30%none fail | 30K req/sKey counter (one database row): 90%none fail | 100K req/sKey counter (one database row): 192%60% fail |
| 5. Hand out keys in ranges | 10K req/s | 10K req/sRead replicas: 28%none fail | 30K req/sRead replicas: 84%none fail | 100K req/sCache (Redis): 158%60% fail |
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Requests arrive at random, as a Poisson process, at a constant average rate.
- Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
- Service times are random with the stated mean; by default they are exponentially distributed.
- Each node is analysed separately, with the traffic it receives treated as Poisson.
- The mix is 100 redirects for each link created: 99% of the requests are lookups and 1% are new links. The ratio is a common teaching figure, not a measurement of a real service.
- Every number (service times, capacities, the cache hit ratio, the design loads) is illustrative model output, chosen to make the limit of each stage visible. None of them is a benchmark of a real database, cache or server.
Simplifications
- Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
- Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
- A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
- A request calls its dependencies one after another. Parallel fan-out is not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
- Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
- Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
- A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
- A caller’s timeout counts the mean time its dependencies take, not their full distribution.
- Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
- Each stage is shown in a steady state: the load is held and the engine says where queues build. A burst, a cold cache warming up and a deploy are not modelled.
- The cache hit ratio is fixed at 95%. A real one depends on how the clicks are spread over the links and on the size of the cache, and it moves with the load.
- The key counter is modelled as one database row updated by one transaction at a time, about 3 ms each, so about 330 new links per second. A database sequence object is much faster; the stage is about a central allocator whose limit depends on how it is built.
- Storage size and cost, expiry, abuse prevention, analytics and several regions are not modelled.
Parameter values are illustrative. They are not benchmarks of any real product.
Stage 1, one API and one database. At 100 requests per second the database is at 13% of its 800 queries per second, and nothing is near a limit. Raise the load to 10 times, 1,000 requests per second, and the lookups alone are 125% of what the database can do: a fifth of the requests fail. The number that ends this stage is the database’s 800, against a peak of 10,000.
Stage 2, a cache. A short code almost never changes after it is created, so a cache in front of the database can keep answers for a long time. With 95% of the lookups answered by the cache, the database sees about 60 queries per second at 1,000 requests per second instead of 1,000. The cache is cheap to hold, about 20 GB by the estimate above. Now the single API server is what runs out. At 10 times the load it is at 125% of its 8,000 requests per second.
Stage 3, several API servers. The API holds no data of its own, so a load balancer can spread requests over 8 servers, which gives 64,000 requests per second and leaves room to lose a server or two during a deploy. The stage is designed for the 10,000-per-second peak, and the database is already at 74% at that load, with 595 queries per second against 800. At 3 times the load, 30,000 requests per second, the API servers are at 47% and the database is at 223%: the misses and the new links ask it for 1,785 queries per second, and 3% of the requests fail.
Stage 4, read replicas. The database becomes a primary for the writes and 4 replicas that answer what the cache misses. The replicas can do 3,200 queries per second between them. The price is that every replica applies every write, so the 300 new links per second at 3 times the load make 1,200 more operations per second across them, and a replica can be a moment behind (see the failure section below). The next limit is not a database. The counter that gives out the next number is one row, updated one transaction at a time, about 3 ms each, so about 330 numbers per second. At 3 times the load it is at 90%, and at 10 times it is overloaded.
Stage 5, keys in ranges. A small key service replaces the counter. Each API server asks it for 1,000 numbers at once and uses them without asking again, so at 3 times the load the key service is called 0.3 times per second instead of 300. Creating links is no longer a limit. At 10 times the load, 100,000 requests per second, the cache is the first to run out at 158% of its 40,000 lookups per second, with the API servers at 156% and the replicas at 143%. The next steps, which the lab leaves out, are to spread the cache over several nodes by key (consistent hashing), to add servers and replicas, and to answer the most popular redirects at the edge.
Where the short codes come from
Section titled “Where the short codes come from”Stage 5 is the part of this design that people get wrong, so it deserves the longest look. A short code has three jobs: it must be unique, it should be short, and in most products it should not be easy to guess. There are three common ways to make one.
| Method | How it works | What you gain | What you pay | When to choose otherwise |
|---|---|---|---|---|
| Counter, written in base 62 | Take the next number, write it with 62 symbols | No two links ever share a code, and no check is needed | One place that hands out numbers, and codes that follow each other | When codes must be hard to guess and you cannot scramble them |
| Random code | Draw 7 symbols at random and insert; if the code exists, draw again | Nothing central, and no order to walk through | A collision check on every write | When the code space is crowded (see below) |
| Hash of the URL | Hash the long URL and keep the first 7 symbols | The same URL gives the same code, so duplicates are free | Two different URLs can collide, and the collision has to be handled | When every request for a link must get its own code, to count or delete separately |
The random method is cheap while the space is empty. With 6 billion links stored among 3.52 trillion codes, a new random code is already taken with probability 6 billion ÷ 3.52 trillion, which is 0.17%, about 1 in 590, so it takes 1.002 attempts on average. With 6 characters the same 6 billion links would fill 10.6% of the space, and about one new code in ten would collide. That is why the design uses 7 characters. The database’s unique primary key is the final guard in every method: a duplicate insert fails, and the API tries again.
The lab uses a counter, which is the only method with no collisions and so the only one whose cost the lab can show. The counter’s weakness is that it is one place that every write goes through. The stage 5 answer is the one the PostgreSQL documentation describes for sequences with the CACHE option: a session takes a block of numbers, uses them without asking again, and the numbers it did not use are lost when it ends, leaving holes. Flickr’s ticket servers are the other classic design: two databases, one handing out the odd numbers and one the even, with clients alternating between them. Here the unit is a range of 1,000. At the 100 new links per second of the peak, split over 8 servers, each uses about 12.5 numbers per second and a range lasts 80 s, so the whole fleet asks the key service for a range 0.1 times per second. A server that crashes loses the rest of its range, at most 1,000 numbers out of 3.52 trillion.
Codes from a counter follow each other, so anyone can walk through them. Scrambling the number before it is written in base 62 hides the order: multiplying it by a constant that has no factor in common with 62 to the power 7, and keeping the remainder when dividing by 62 to the power 7, sends every number to a different one. This only hides the order from a casual reader. If the links must stay secret, use random codes that are long enough, and treat the short URL as a password to the page.
What happens if the cache is lost
Section titled “What happens if the cache is lost”The final design holds 95% of the lookups in the cache. Restart it empty, or lose the node, and run the same graph with the cache’s hit ratio at 0 (the lab has no control for this, the figure is the engine’s answer for that graph): the 9,900 lookups per second of the peak go to the replicas, which can answer 3,200. With the 400 operations per second that replicating the writes adds, the replicas are asked for 10,300, which is 322% of their capacity, and 68% of the requests fail. The cache was not an optimisation, it was holding the system up, which is the point of the cache failure lesson.
What stops it: warm the cache before a new node takes traffic, or restore it gradually; make only one request per code go to the database while it refills (request coalescing); and shed some requests quickly rather than let all of them queue. The same lesson explains why a restarted cache is the most dangerous moment, not the failed one.
What happens if a replica is behind
Section titled “What happens if a replica is behind”A person creates a link and opens it at once. The write went to the primary, the lookup goes to a replica, and the replica may not have the row yet: the answer is 404 for a link that exists. This is replication lag, and a short link is the clearest case of it, because the next thing the creator does is use it. Two cheap fixes work here. Put the new link in the cache when it is created, so the first opens never reach a replica. And when a replica says a code does not exist, ask the primary before answering 404; unknown codes are rare enough that the extra queries are affordable, but a flood of bad codes would reach the primary too, so rate-limit them.
What happens if the key service forgets
Section titled “What happens if the key service forgets”The key service hands out ranges. If it restarts and forgets the last range it gave, it can give the same range to a second server, and two links get the same code. Two rules prevent this. The service writes the new high-water mark to durable storage before it hands out the range, so a restart resumes after it (the skipped numbers are the same harmless holes as before). And the primary key on code stays unique, so if the rule is ever broken, the second insert fails, the server takes a new range, and the failure is a retry instead of a wrong redirect.
Trade-offs
Section titled “Trade-offs”Each row is a decision in the lab, written with what it buys, what it costs and when the other choice is better.
| Decision | What you gain | What you pay | When to choose otherwise |
|---|---|---|---|
| Redirect with 302 (temporary) | Every visit reaches you: you can count clicks and change or remove a link at once | Every visit is a request you must serve | When you never change links and want browsers and caches to absorb the traffic: 301 is cacheable and is the cheapest redirect |
| A cache in front of the database | Most lookups never touch the database | A second system, and a stampede when it is empty | When the lookup rate is small, or the hit ratio would be low |
| Replicas for the misses | More lookups per second, and a copy if the primary fails | Lag: a new link can be missing for a moment | When a read must always see the last write, read the primary |
| Counter ranges for codes | No collisions and almost no load on the key service | Skipped numbers, a service to keep durable, codes that need scrambling | When codes must be unguessable and you would rather pay for a collision check |
On the first row, the HTTP specification says that a 301 response is heuristically cacheable, so a browser may reuse it without asking again, while a 302 is not stored unless the response says so. That saves requests and hides those visits from your statistics, which is the trade.
Defend your design
Section titled “Defend your design”An interviewer asks for this system in 45 minutes. A good answer starts with the numbers (writes are tiny, reads are the load), builds the stages in the order the numbers force them, and says out loud what each one costs. Write your answer before you read the strong one.
Interview question
Writing and reviewing an answer needs JavaScript.
The interviewer asks
Design a URL shortener: a user submits a long URL and gets a short link, and anyone who opens the short link is redirected to the long one. Walk through how you would build it and how it grows.
Assume 100 million new links a month, about 100 redirects for each link created, and links kept for 5 years.
Write your answer first. The strong answer unlocks once you have written a real attempt.
0 of 80 characters written to unlock the strong answer
- 100 million new links a month and 100 redirects per link make about 40 writes and 4,000 reads per second on average, and about 10,000 requests per second at the peak. Storage is about 3 TB: the first limit is reads, not data size.
- Stage 1 puts everything in one database: it is at 13% at 100 requests per second and at 125% at 1,000. A cache cuts its load to about 60 queries per second at 1,000 requests per second.
- Several API servers raise the limit from 8,000 to 64,000 requests per second. Read replicas take the misses (3,200 per second between 4 of them) at the price of lag.
- A counter that is one row issues about 330 numbers per second and is at 90% at 3 times the load. Handing out ranges of 1,000 brings the key service to 0.3 calls per second.
- Seven characters of base 62 give 3.52 trillion codes: a random code collides with probability 0.17% at 6 billion links, and 10.6% with six characters.
- Losing the cache puts 10,300 operations per second on replicas that can do 3,200: 322%, and 68% of the requests fail.
Next: Pastebin, which keeps large blobs and their metadata apart and makes them expire.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.