Design a URL shortener
Read first: Load balancing, Caching, Choosing a database, Back-of-the-envelope estimation
Redirects dominate a short-link service, and they have to stay fast while still counting. A 301 lets caches hide the click, so you use a 302 when the count matters, mint keys from a counter, and cache the mapping. One hot link is a single key, and extra database partitions do not split it.
People remember a short link as a create call. The traffic is the redirect. Creates are a slow trickle next to clicks, one link can be most of the clicks for an hour, and the status code you return decides whether you even see those clicks. Design the redirect first. The key generator is a small problem you settle on purpose, not the architecture.
Requirements
Two people use this. A marketer, or the backend that sends a receipt, creates a short key for a long link. A stranger who taps that key must be sent to the current destination. The marketer later reads a click count. Those are different requests, with different latency and different failure rules.
Functional requirements:
- Create returns a short key for a long link. The caller may ask for an expiry and may propose a custom key.
- Redirect sends the holder of the key to the destination that is current at request time.
- A count of redirects is available to the owner. It can lag by seconds. It is not a bill.
- The owner can replace the destination or disable the key. The next redirect that misses cache observes the change.
Non-goals, said out loud so you do not design them:
- You do not fetch the destination on create. Fetching a caller-supplied link is how a server-side request forgery bug shows up. You store the string and redirect to it later.
- You do not build a warehouse of campaigns, browsers, and funnels on the redirect path. The redirect records that a click happened. Aggregation is elsewhere.
- You do not shorten secrets that must be unguessable, such as a password reset, with the same keys you use for a public campaign. That is a different product with a different id.
- You do not promise multi-region active-active writes. One region, one primary for creates.
Product assumption you state: a redirect that hits cache should have a p99 under 50 ms inside the region. That number is a budget you picked, not a measured service level. It leaves room for one cache lookup and a tiny response, and it does not leave room for a synchronous analytics write.
Estimation
Say the assumptions before the arithmetic. This is a product that shortens every transactional message and a smaller number of campaigns.
- 8 million new links per day. Assumption.
- 120 million redirects per day. Assumption, counted separately, not as a magic read-to-write ratio.
- Peak redirects are 4 times the average, during a morning send. Assumption. Creates peak at 2 times, and not in the same minute. Assumption.
- A stored row is about 256 bytes: the key, a long link averaging 180 bytes, owner, timestamps, expiry, status. Assumption.
- A redirect response is about 400 bytes, mostly the status line and a location header. Assumption.
- You keep links for 2 years. Assumption.
A day has 86,400 seconds. The interview shortcut is 1e5 seconds. Show both.
creates 8,000,000 / 86400 = 92.6 per second
shortcut 8,000,000 / 1e5 = 80 per second
redirects 120,000,000 / 86400 = 1,389 per second
shortcut 120,000,000 / 1e5 = 1,200 per second
peak redirects, 4x assumption = about 5,600 per second
peak creates, 2x assumption = about 185 per second
Dividing by 1e5 undershoots the true average by about 14 percent, because 86,400 / 1e5 = 0.864. Say you used the shortcut, then keep the exact figure if the design sits near a limit. Neither figure is near a limit for writes.
One million requests a day is 1,000,000 / 86,400, about 12 per second. You are two orders of magnitude above that on reads and still nowhere near a write problem. About 90 creates per second is a bored primary. About 1,400 redirects per second is a cache problem plus a careful miss path. The ratio of the two daily assumptions is 15 reads per create. That ratio is an output, not an input you memorized.
Storage and bandwidth, so you can see they are not the bottleneck:
8e6 links/day * 256 bytes = about 2 GB/day
2 years * 365 * 2 GB = about 1.5 TB raw
replication factor 3 = about 4.4 TB
1,389 redirects/s * 400 B = about 0.6 MB/s average
5,600 redirects/s * 400 B = about 2.2 MB/s at the assumed peak
Sending 1 KB across a 1 Gbps link is about 10 microseconds on Jeff Dean’s teaching list. The bytes of the redirect are noise. A same-datacenter round trip is 0.5 ms, and that is the unit that matters when the cache misses. You do not shard this database on day one to “be ready.” You shard when a real limit shows up. The limit that shows up is one key, and partitioning does not split one key.
Cache working set, a second assumption: 70 percent of links are never clicked, and the clicks that do happen land on about 15 million distinct keys in a day. An entry is the key, the destination, and the expiry, about 200 bytes. 15 million times 200 bytes is 3 GB. The fleet holds that. Capacity is not the hot-link problem. Placement is.
High-level design
flowchart LR
clicker[Person clicking] --> lb[Load balancer]
lb --> redirect[Redirect service]
redirect --> localhot[Local hot key cache]
redirect --> shared[Shared mapping cache]
redirect --> store[Link primary]
redirect --> clicklog[Async click log]
creator[Creator] --> api[Create API]
api --> counter[Atomic counter]
api --> store
The load balancer in front of the redirect service is stateless round robin or least connections. Redirect processes hold no session. A create goes to the primary, which allocates a key and inserts the row. A redirect reads a cache and almost never the primary. The click log is appended after you have decided the destination, and the user does not wait for it.
Create path. The API checks auth, rejects a disabled or oversized destination, and either inserts the caller’s custom key or takes the next integer from the counter. The integer is encoded in base 62 so the key is short. The row is committed, then the cache is filled. If the cache fill fails, the create still succeeds. The next redirect will fill it on a miss.
Redirect path. Look in the process-local hot cache, then the shared cache, then the primary. If the key is missing or expired or disabled, return a not-found and do not write a click. If it is live, write the click asynchronously and return the redirect. Cache-aside is the read pattern: the app reads the cache, and on a miss reads the database and fills the cache.
The click path is a log or a counter increment on a buffer that flushes in batches. If that buffer dies with the process, you lose a few seconds of counts. For this product that is acceptable. You would not accept it for a charge. Keep that sentence in your pocket, because an interviewer will ask why the click is allowed to vanish when the row is not.
Deep dive
301 versus 302, if you count clicks
A 301 means “this moved permanently.” Browsers, and any CDN in front of you, are allowed to remember the destination and skip you next time. Your count flatlines while the campaign is clearly being tapped, and a destination you changed an hour ago is still being served from someone else’s cache. You cannot invalidate a stranger’s browser.
A 302 means “for this request, go here.” A well behaved client asks you again next time. You see the click, and a destination change takes effect on the next uncached request. A link in a message is fetched with GET, so 302 is the status to name. Use 307 if you must preserve a method other than GET. Do not spend the interview on the rest of the 3xx table.
If you put a long cache lifetime on the 302, intermediaries store it and you have rebuilt the 301 problem. When the product counts clicks, the response tells shared caches not to store it. Your own mapping cache is a different layer. It caches key to destination for a short time so your database survives. It does not tell the browser to skip you. Those two caches answer different questions. Mixing them up is the bug.
Assumption: the shared mapping cache uses a 60 second TTL, and an update deletes the key. The TTL is the bound for a lost invalidation. A marketer who changes a destination waits up to a minute for every redirect server to notice, sooner if the delete lands. Say that tradeoff. It is honest and it is small.
Recording the click is not on the user’s clock. A latency budget of 50 ms at p99 fits a local cache hit. It does not fit a remote write to an analytics system that might be slow or down. The redirect returns, then the process appends “this key was used” to a buffer. A consumer adds it up. The count the marketer reads can be a few seconds behind. If the analytics consumer is down, redirects still work and the count pauses. That split is the design.
Keys, counter versus hash
The counter is one row: an integer you increment atomically, then encode. At about 90 creates per second, one primary does this without a queue, a range allocator, or a second system. Base 62 is an alphabet of 62 symbols, so the key stays short and does not include characters that break in a path.
62^6 = 56,800,235,584
8e6 creates/day * 365 = 2.92e9 keys per year
56.8e9 / 2.92e9 = about 19 years at 6 characters
Six characters covers this assumption for well over a decade. Seven characters is the number you pick if you want slack and custom keys in the same table without sweating. This is a derivation from the create assumption, not a universal constant.
The counter’s weakness is predictability. The next campaign key is near the last one. For a public link on a poster, that is fine. For a link that itself authorizes something, it is not fine, and that case is in the non-goals. If a later product asks for unguessable keys, you switch that product to random keys. You do not pretend one generator serves both.
A hash of the long link looks stateless and dedupes “the same destination.” It is the wrong dedupe here. Two marketers who shorten the same page would share a key and share a click count, and one of them could not change the destination without changing it for the other. If you salt the hash with the owner id you are back to a uniqueness check, plus collisions. A 7 character slice of a hash is not unique. You must read the table, and on a collision you rehash with a different salt or take more characters. The counter has no collision branch. The hash has one on every create, and it buys you a dedupe this product does not want.
Custom keys are a unique insert of the caller’s string. If it exists, create fails. The counter can in theory land on a custom key someone reserved. The insert checks the primary key and skips to the next integer if it hits. At this size that branch is rare. One table, one primary key, both kinds of key. Do not run two namespaces and then forget to check one of them.
Range allocation, a block of a thousand integers handed to each app server, is what you add when creates no longer fit one row. At 90 per second you are not there. Mention it as the next step so the interviewer knows you are not attached to a single row forever. Do not build it in the first diagram.
The cache and one hot link
Steady state is easy. The interesting hour is one launch link. Assumption for that hour: the link takes 40 percent of peak redirects. 0.4 times 5,600 is about 2,200 reads per second of one key. A shared cache serves that from one slot without drama. The failure is the miss.
Cache-aside on a popular key expires, and every redirect process misses at once. That is a stampede. For a second or two the primary sees thousands of identical point reads, plus the ordinary misses. A single-flight lock fixes the stampede: one process reads the database, the others wait for that fill. The Facebook memcache paper does the same job with a lease. A miss returns a token, the filler must present the token to write the cache, and a stale token is rejected so a slow filler cannot overwrite a newer destination. You do not need to rebuild that paper. You need to say that one filler populates the key and a late fill must not resurrect an old destination.
The shared cache still pins the hot key to one cache process, because the cache is hashed by key. Two thousand reads a second is fine. The interviewer’s follow-up is “now it is 100 times larger.” At 220,000 reads a second of one key, that cache process is the bottleneck, and adding cache nodes does not move the key. The fix is a local cache on each redirect process for keys that cross a threshold.
Assumption: a redirect process that sees more than 50 reads per second of one key pins it in process memory for 5 seconds, with jitter so the fleet does not expire together. Twenty processes (a sizing assumption for this peak) then refresh the shared cache a handful of times per 5 seconds, not 2,200 times per second. The primary sees a fill only when the shared entry is missing, and single-flight collapses that fill to one read. Jitter matters. If every local entry expires on the same second, you rebuilt the stampede one tier up.
Probabilistic early refresh is the extra step when a synchronized expiry has burned you. As the local entry nears expiry, a process refreshes a bit early with rising probability, so one refresh lands before the rest expire. Describe that idea. Do not invent a formula for it.
More database shards do not help this key. Hash partitioning spreads different keys across machines. The hot key is one row on one primary. The copies that save you are caches in front, including the process-local one, not another partition of the same row.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| 302 and do not let shared caches store it | Every click can be counted, and a destination change is visible | You stay on the path for the life of the link |
| 301 | Browsers stop asking, and your read QPS falls | The count lies, and old destinations stick |
| Counter key | Unique, short, no collision branch, trivial at this write rate | Keys are guessable and a single counter is a thing you will later range-allocate |
| Hash of the destination | Identical public links can share a key with no coordination | Collisions, and a shared count across owners who did not agree |
| Synchronous click write | The count matches the redirect that just happened | Analytics latency and downtime become redirect downtime |
| Local cache for hot keys | One key cannot pin a single cache node or the primary | A few seconds of extra staleness, and a per-process policy to get wrong |
The row to defend out loud is the 302 plus the asynchronous count. You gave up a perfectly fresh, perfectly durable click number. You kept the redirect inside the budget when analytics is sick.
Failure modes
- Cache fleet down. The primary receives the full redirect rate, about 5,600 reads per second at the assumed peak, with one key a large share of it. A primary sized for 90 writes per second can fall over on that read spike. Redirect processes that still hold a local entry should serve it even if it is slightly past its TTL, and treat “cache down” as “use the stale local entry.” A broken link in a receipt is worse than a destination that is ten seconds stale. A destination that has been disabled for fraud is the exception: if the local entry says disabled, honor it. If you have never seen the key, fail the redirect. Do not guess.
- Primary down. Creates fail. Redirects of keys you have cached keep working. The cache is buying availability on the read path as well as latency. Failover of the primary needs fencing, a generation or a lease, so the old primary cannot keep issuing counter values. Two primaries double-allocate integers, two destinations end up fighting for one key, and redirects flap. Replication is the lesson that covers fencing. Name it here in one sentence.
- Wrong status code. Symptom: the campaign dashboard stops counting while the short link still works on phones that have cached a 301, and a changed destination never shows up for those phones. The fix is the status and the cache headers, not a bigger database.
- Click log backed up or dead. Counts lag or freeze. Redirects stay fast only if you did not put the log write on the path. If a retry of the click append is unbounded, the buffer grows without a limit and the process runs out of memory. Bound the buffer. Drop and count a metric when it is full. A lost click is the failure you already accepted. A dead redirect process is not.
- Redirect retries. A client that gets a 500 will tap again. During a cache miss storm that multiplies the hot key. Single-flight has to hold for those retries too. A rate limit on creates stops someone minting millions of keys. The redirect path rate-limits an abusive source, not a legitimate campaign, or you will shed the launch you exist to serve.
- Custom-key squatting is an abuse problem, not a storage problem. It belongs on the create API as an auth rule and a limit. Do not design a reputation system in this interview unless they ask.
In the interview
The first five minutes are four questions. Who creates, who clicks, do you count, and can the destination change. Counting plus a changeable destination is a 302, an async count, and a short TTL. The create rate you just estimated is about 80 per second with the shortcut, so the key is a counter, not a distributed id project. The redirect rate is about 1,200 per second average, so you draw a cache. The bottleneck is not the counter. It is a miss on one popular key.
Skip multi-region consensus, a tour of every hash function, and any analytics product. Say you are not fetching the destination.
The question that usually follows is “one link just got most of the traffic.” You say: one key, local pin with jitter, single-flight on the shared fill, and no, more partitions do not split it. The tradeoff you admit is a count that can lag or drop a little, and a destination change that takes the TTL to reach every process.
Check yourself
What is 120 million redirects a day in requests per second, exactly and with the 1e5 shortcut?
120,000,000 divided by 86,400 is about 1,389 per second. Divided by 1e5 it is 1,200 per second. The shortcut is about 14 percent low because a day is 86,400 seconds, not 100,000. Either number says the same thing: this is a cache-sized read rate, and the create rate an order of magnitude smaller is not the design.
You count clicks, and the owner must be able to change the destination. Why is a 301 the wrong status?
A 301 may be stored by the browser and by any shared cache in front of you. Later clicks never reach your server, so the count stops, and a destination you updated is ignored until that foreign cache expires. You cannot delete it from their cache. A 302 that shared caches are told not to store still lets you cache the mapping in your own fleet for a short TTL.
One key is 40 percent of redirect traffic and the primary is melting. Why does adding database partitions not fix it?
Partitions spread different keys across machines. This is one key, so it hashes to one partition and stays there. The reads have to be absorbed by caches, including a process-local cache on each redirect server, with a single filler on a miss so the primary sees one read rather than a stampede.
Two customers shorten the same long link and each needs a private click count. What is wrong with hashing only the long link?
Both customers get the same short key, so they share a row, a destination, and a count. Either one can change the destination for the other. A counter, or a hash salted with the owner, gives each of them a key. The pure hash is a dedupe they did not ask for.
The shared cache process restarts during the peak. What do you want each redirect server to do?
Serve a local hot entry if you have one, even if it is a few seconds stale, and collapse the refill of a missing popular key to a single database read. Failing every redirect because the cache is cold turns a cache restart into broken links. A key you have never cached still has to hit the database, which is why the local pin has to exist before the restart, not after.
Based on: Jeff Dean, Numbers Everyone Should Know; Facebook memcache paper, Nishtala and others; Designing Data-Intensive Applications, Kleppmann and Riccomini; Alex Xu, ByteByteGo volumes.