System Design · Interview breakdown · Free article
Design a URL Shortener
A short link service turns a long URL into a six character code, then serves the redirect back in milliseconds at enormous read volume. The full interview walk, from requirements through the deep dives, with the bar named at every level from intern to principal.
A URL shortener looks like the easiest interview you will ever get: store a code, return a link. It is a trap. The whole difficulty hides in one sentence, that reads outnumber writes about a thousand to one, and every real decision falls out of it: how you mint a code that stays unique at a billion links, how a redirect stays instant when one viral post lands a stampede on a single row, and where the money goes when the spike becomes the baseline. This breakdown walks the exact path a great candidate takes, phase by phase, and shows you the reasoning an interviewer is silently grading at each step.
The problem, made real
The interviewer slides one sentence across the table: "People paste giant links. Give them tiny ones that never break." That is the entire brief. No schema, no scale numbers, no hints, just a product and a promise.
The short answer, before the walk. A URL shortener stores one mapping, long URL to short code, and then serves that mapping back a very large number of times. You need three things: a way to mint a code that is unique forever, somewhere durable to keep the mapping, and a read path fast enough that a redirect feels like no step at all. Everything else in the hour is a consequence of one ratio, reads outnumber writes by roughly a thousand to one.
Concretely: someone pastes a long destination like https://example.com/collections/spring-drop/limited?ref=story&utm=bio and gets back something a person can type or print, sho.rt/x7Gk2f. Tap the short one, land on the long one. That is the whole product a visitor ever sees.
What makes it a real interview, and not a five minute toy, is what lives under that one tap. Every profile link, every story swipe, every printed QR code is a redirect you serve. The links are read constantly and written rarely. A single post from the right account can compress a normal day of traffic into sixty seconds. And the one thing a shortener can never do is send a person to the wrong page. A slow redirect annoys; a wrong redirect betrays. Hold those three facts, because the rest of the design is just answering to them.
What the system must do
The first move is to turn that one sentence into a short list of things the system must do, and, just as important, to name what it will not do. A weaker candidate tries to build everything: accounts, analytics dashboards, team permissions, link editing. A stronger one scopes down on purpose. In a one-hour round the flex is not breadth. It is picking the two or three requirements that actually carry the product, and defending the cut.
State them most-important first. The order itself is a signal: it tells the interviewer you know which sentence the traffic hangs off.
The four things the shortener must do
- A creator submits a long destination URL and receives a short link for it. This is the write path, and without minting there is no product.
- A visitor opening a short link is sent to the original destination. This is the read path, and every gram of traffic lives here. Caching, the edge, the bill: every later phase hangs off this one sentence.
- A creator can choose their own word as the code, a vanity link like
sho.rt/spring-drop. Cheap to state, and it quietly plants a collision question: chosen words and generated codes share one namespace, so one of them has to give way. - A link can carry an expiry date and stop working after it passes. Also cheap, and it sets up two later conversations: how long a cache is allowed to hold a mapping, and what a redirect returns once a link is dead.
What must be true of it
Functional requirements say what the system does. Non-functional requirements say what must be true of it while it does them: how fast, how reliable, how correct. This is where interviews are won and lost, because a wish is easy and a requirement carries a number. "It should be fast" is a wish. "A redirect returns in under a hundred milliseconds at the ninety-ninth percentile" is a requirement, and you can hold a design against it and watch it pass or fail.
Put a number on everything you can. Three promises matter here, and one of them is a number so important we are going to make you earn it in the next phase rather than hand it over here.
The promises the product bets its name on
- Correctness: every code maps to exactly one destination. This is the non-negotiable. A collision sends a stranger to the wrong page, the one failure a shortener can never ship. No number here; it is a hard invariant, and it seeds the entire unique-codes deep dive later.
- Latency: redirects feel instant, a p99 under about 100 ms. The redirect sits between a person’s tap and every page on the internet, so its latency is added to everything. Naming the number is the point; a redirect you cannot measure is a redirect you cannot defend. Say p99 rather than average on purpose, and be ready to say why: percentiles is where that answer lives, and interviewers do ask.
- Availability: highly available, think 99.9% or better, favouring availability over strict consistency on the read path. A link printed in a magazine cannot retry. If the cost of staying up is that a just-edited destination takes a few seconds to propagate, a shortener happily pays it.
Size the beast before you draw it
Before a single box goes on the whiteboard, size the system. The goal here is not precision. It is order of magnitude, the power of ten that decides your architecture. Ten gigabytes and ten petabytes are different systems; ten requests a second and ten thousand are different systems. Keep the arithmetic honest and round hard. False precision ("847.3 GB") reads as insecurity; a confident "call it a hundred gigs" reads as fluency.
Start from what the interviewer can tell you and reason outward. Say steady-state traffic is around 4,000 redirects a second, and writes run about a thousand times rarer. Three numbers fall out, and each one is worth doing on the board rather than in your head.
| Question | The arithmetic | The answer |
|---|---|---|
| How many new links are minted per day? | 4,000 redirects/s ÷ 1000 = 4 mints/s, × 86,400 s/day = 345,600 | ~350,000 links/day, so the write path is a stroll |
| How much storage for 200M stored links? | 200,000,000 rows × ~500 bytes/row (code, destination, owner, expiry, headroom) = 100,000,000,000 bytes | ~100 GB, so one healthy disk holds the whole product |
| What peak must a viral post survive? | 4,000 redirects/s × 10 (a creator with millions of followers) | ~40,000 redirects/s, the number the design must not fold under |
Say each of those out loud as you write it, including the boring middle step. Four thousand redirects a second divided by a thousand is four mints a second; four a second times the 86,400 seconds in a day is 345,600, so call it three hundred and fifty thousand links a day. Two hundred million rows at about five hundred bytes each is a hundred billion bytes, which is a hundred gigabytes. And a creator with millions of followers is worth roughly ten times the usual traffic, so forty thousand redirects a second is the number a design has to survive rather than the number it runs at.
One more, because it decides how much trouble you are in on the worst possible day: a viral link landing while your cache happens to be cold is not forty thousand a second, it is closer to a hundred thousand. Hold that number; it is the one the principal-level answer sizes for.
What it stores
The data model for a shortener is almost embarrassingly small, and that is the point: a short list beats a long one. List the handful of things the system stores, with their key fields, and resist inventing more. The whole system really is one row, written once and read a million times.
| Entity | Key fields | Why it exists |
|---|---|---|
| Link | code (the short slug), destination (the long URL), expiresAt (optional), creatorId | The system IS this row. Everything else exists to write it once and serve it constantly. |
| Creator | creatorId (a reference, not a full user record) | Even with accounts parked, a link needs an owner reference: expiry, vanity words, and future quotas all hang off it. |
The contract between client and server
The API is the contract: what a caller sends, what they get back. The rule of thumb is roughly one endpoint per functional requirement, and for a shortener the two core requirements collapse into two endpoints. Say the verb, the path, what goes in, what comes out, and be ready to defend the small decisions, because this is where an interviewer probes whether you actually know REST or just gesture at it.
| Endpoint | Request | Response |
|---|---|---|
POST /urls | { destination, alias?, expiresAt? } | 201 Created with { shortUrl }. A new resource is born, so POST, and the optional alias and expiry make the phase-one nice-to-haves real |
GET /{code} | the short code as a path parameter | an HTTP redirect (a 3xx with a Location: header pointing at the destination), the busiest GET you will ever design |
The interactive version of this example is available when JavaScript loads.
The design, one requirement at a time
Here is where most candidates reach for a memorised box diagram, the client, load balancer, app servers, cache and database all drawn at once. Resist that. A diagram drawn from memory proves you have seen one; a diagram built one requirement at a time proves you understand why each box is there. So start with the smallest honest system and let each requirement pull the next component onto the canvas, saying out loud what breaks without it.
The smallest honest system is almost embarrassing: a client, one application server, and a place to keep the mapping. It is fine to seed exactly that and get moving, because the interesting part is what forces you off it.
So here is the whole system at the start of the conversation: a client, one application server, and the code-to-destination map kept in that server’s own memory. One picture, and it is going to grow under you eight times before the article is over, every box arriving because a sentence in the requirements demanded it, and the ticked promises underneath filling in as the design earns them. These are the same component kinds you use in the lab. The article sizes capacity with round-number examples. The lab executes finite queues and actual cache keys over a 20-second scenario, then checks the resulting latency and availability. Its catalogue capacities and prices are teaching assumptions, not vendor benchmarks or quotes.
The interactive version of this example is available when JavaScript loads.
Sit with that for a second, because starting here is a choice and interviewers read it as one. A candidate who opens with the full architecture has told you they memorised a diagram. A candidate who opens with two boxes has told you they intend to earn every box after them, and has quietly made the rest of the hour easier, because from now on every component arrives attached to the failure it prevents.
So name this one’s failure out loud. The map lives inside one process, which means a deploy erases the product. Not a crash, not a datacenter fire. A deploy, the most routine thing that ever happens to a service. Every link anyone has ever minted is gone because you shipped a logging change on a Tuesday afternoon.
The interactive version of this example is available when JavaScript loads.
Both paths end at that one store for now, and it is worth noticing how little slack there is. The lab gives a database capacity of 5,000 requests a second. Roughly 4,000 redirects already consume 80% of it before counting new links. That leaves 1,000 requests a second of nominal headroom, and slower individual requests still create queues. A larger burst can use the remaining headroom quickly.
That is worth saying out loud rather than fixing quietly, because the interviewer is watching for whether you notice. A tier near its capacity needs a plan for the next surprise, and the next surprise in this problem is guaranteed, since the whole product is one creator away from ten times the traffic. Hold the observation; the cache is going to be the answer, and it is worth two more requirements first.
The next of them is the one a shortener cannot get wrong. Every code maps to exactly one destination, forever, and a collision does not degrade the product, it sends a stranger to somebody else’s page. How you actually mint such a code is the first deep dive, and it is the most interesting arithmetic in the problem. But the shape it leaves in the picture is small, and that gap between a hard idea and a small drawing is worth pointing at: the app server mints, and the store keeps a uniqueness rule on the code column as the net under whatever the generator does.
The interactive version of this example is available when JavaScript loads.
Next, the traffic itself, and this is the first place the design is decided by division rather than by taste. One app server handles about 2,000 requests a second. You have 4,000 redirects a second arriving. 4,000 ÷ 2,000 is two servers running absolutely flat out, which is not a design, it is a coin flip: the first slow request queues behind the second, and a queue at full utilisation does not recover, it grows. Run three, and each one carries about 1,300, about two thirds of its nominal capacity. Losing one leaves two at their ceiling, so surviving a failure with headroom would require more capacity.
Saying the division rather than the conclusion is the whole trick here. "I would add a few app servers" is a sentence anyone can say. "Two thousand each, four thousand arriving, so three" is a sentence that tells the interviewer you would size the next tier the same way, without being asked.
And it immediately buys a second problem, which is a good habit to model out loud: fixes create requirements. Three servers with nothing in front of them do not share anything. Traffic goes wherever the client happened to point, so two sit idle while the third saturates, and you have paid for three servers to get the reliability of one. A load balancer is what turns three machines into one fleet, and from here every request crosses it, including, later on, the ones that miss at the edge and come back looking for an origin.
The interactive version of this example is available when JavaScript loads.
The same walk, as a reference. Functional requirements first, then hardening the non-functional promises:
| The requirement (as a design prompt) | What it pulls onto the canvas | The failure it prevents |
|---|---|---|
| A creator mints a link and it stays minted. | A database that owns the code-to-destination row. | Without durable storage, every link dies on the next restart. |
| A visitor opens a short link and lands on the destination. | The read path: GET /{code} resolves one row and returns a 302. | This is the sentence all the traffic hangs off. Get it working, then get it fast. |
| Every code maps to exactly one destination. | A code-minting strategy (deep dive 1) plus the database’s uniqueness guarantee. | Without it, two links collide and a visitor lands on a stranger’s page. |
| No single server carries the whole read rate. | Three app servers (4,000 ÷ 2,000 each) behind a load-balancer. | Without the balancer, three servers are not a fleet: traffic piles onto whichever one gets asked. |
| Redirects feel instant, even under load. | A cache in front of the database, then a cdn at the edge (deep dive 2). | Without them, roughly 4,000 reads a second land on a store rated for 5,000, leaving little room for a burst. |
| The design survives a viral spike, on a defensible budget. | Read replicas for the miss storm, and a fleet sized to the load (deep dive 3). The lag they carry is exactly the staleness this design already agreed to accept. | Without headroom, one popular link takes the whole product down, or the bill does. |
Minting a code that stays unique at a billion links
This is the deep dive interviewers reach for most, because it hides a genuine tension. The code has to be short, since a code as long as the original URL defeats the product, and it has to be unique forever, since two links must never share one. Those two goals pull against each other: the shorter the code, the fewer codes exist, and the sooner two of them collide. Every strategy below is a different way to buy both at once.
Start with the budget, because the math is friendlier than it looks. Pick a generous alphabet (base62 is the favourite: a-z, A-Z, 0-9, all URL-safe) and a code of length L gives you 62 to the power L possible codes. Six characters is about 56.8 billion; seven is about 3.5 trillion. Seven base62 characters covers the whole internet for years, so length is never the hard part. How you pick each code is.
The interactive version of this example is available when JavaScript loads.
With the budget settled, walk the strategies in the order the industry actually discovered them, each one fixing the flaw in the one before. (This is the same arc the Short Codes pattern walks in depth; here we tie it to the interview and to what each level is expected to reach.)
| Strategy | How it works | Where it breaks | Expected by |
|---|---|---|---|
| Carve letters off the URL | Take the first few characters of the destination as the code. | Two destinations sharing a prefix mint the same code. This is not shortening; it is a collision factory. Mention it only to reject it. | Nobody |
| Hash the URL and trim | Hash the destination, base62-encode the digest, keep the first seven or so characters. | Trimming shrinks the space, so collisions reappear far earlier than intuition says (the birthday paradox). Needs a uniqueness constraint plus bounded retry. | SDE1 (accepted, then taught the collision math) |
| An atomic counter, base62-encoded | Keep one counter; every mint increments it and encodes the value. Unique by construction, with no collision checks, ever. The increment has to be genuinely atomic, because two writers that read the same value and both add one mint the same code: atomic counters shows that lost update happening and the three ways to close it. | One point of coordination: every mint pays a hop to it, and a scaled-out write tier queues on one number. Also sequential, so codes are enumerable. | SDE2 |
| Writers lease disjoint ranges | Each writer leases a block of the counter (say ten thousand values) and mints locally; regions get disjoint bands, so no cross-region agreement is needed on the write path. | A crashed writer abandons the tail of its range, leaving harmless gaps, since uniqueness never needed continuity. Near-sequential codes stay enumerable, so a keyed shuffle before encoding hides the order. | SDE3 / Principal |
The birthday paradox is the trap worth internalising, because it is deeply counter-intuitive. Run it in the tighter of the two spaces above, the six character one: with 56.8 billion possible codes you would swear collisions are years away. The first clash among random codes appears after only about the square root of the space, roughly 240,000 links, not billions. Collisions are normal and early, which is why the database’s uniqueness guarantee is never optional: it is the safety net every strategy above still relies on. Drag the space toward full and watch how quickly a new code needs a retry.
The interactive version of this example is available when JavaScript loads.
The interactive version of this example is available when JavaScript loads.
Keeping a redirect instant
The latency promise was "p99 under about 100 ms." A weak candidate asserts it; a strong one derives it from where the answer physically lives. A redirect is one tiny lookup, so its speed is decided almost entirely by how far the reader is from the copy of the mapping that answers them. Put the real hardware numbers on the table and the design draws itself.
| Where the answer lives | Rough time to read it | What that means for a redirect |
|---|---|---|
| Main memory (a cache hit) | ~100 nanoseconds | Effectively free; the lookup is lost in the noise of the network. |
| Same-datacenter round trip | ~500 microseconds (0.5 ms) | A cache in your own datacenter answers in well under a millisecond. |
| SSD random read (a database miss) | ~150 microseconds per read, but with queueing under load it climbs fast | Fine occasionally; ruinous if every redirect hits disk. |
| Rotational disk seek | ~10 milliseconds | A hundred times slower than memory. Never serve hot reads from spinning disk. |
| Cross-continent round trip | ~150 milliseconds | This alone blows the 100 ms budget, which is why distant readers need an answer close to them. |
That gives you a ladder, each rung nearer the reader and further from disk than the last:
The read-path ladder
- Index the read key. The code is the primary key; a lookup by primary key is a fast index probe, not a table scan. This is the floor, not the finish. If you cannot say why a probe beats a scan, database indexing is the page to read before the interview, not after.
- Put an in-memory cache in front of the database. A handful of codes are hot, so a cache-aside layer answers the vast majority of reads from memory, and the database only ever sees the miss fraction. Set the cache’s time-to-live no longer than a link’s expiry, so a dead link cannot outlive itself in the cache.
- Push the hottest answers to a CDN at the edge. For a viral link, the identical redirect can be served from a point of presence near the reader, cutting out the cross-continent round trip entirely and never touching your origin.
Walk the ladder below and watch the honest split. A redirect’s p99 is a network hop to the answer plus the lookup at it. The lesson hides in rung two: a cache at the origin kills the disk, not the distance, so the reader an ocean away, the p99 tail, only gets under budget once the answer moves to the edge.
The interactive version of this example is available when JavaScript loads.
Rung two is also the moment the store stops being frightening, and it is worth doing the arithmetic rather than saying "the cache absorbs it." A handful of codes carry most of the traffic, so suppose a cache in front of the database answers nine requests in ten. This is a sizing assumption; the lab measures hits from the actual keys and cache state. Nine in ten of 4,000 leaves 400 a second still reaching the store, a tenth of what it was, against a capacity of 5,000. With that assumed hit rate, the database goes from about 80% of capacity to 8%, and nothing about the database changed.
This is also where the two paths stop being one system. Everything from here, the cache, the copies behind it, the edge, is machinery only a redirect ever touches. A mint still walks straight to the store, four times a second, exactly as it did on the first picture.
The interactive version of this example is available when JavaScript loads.
The interactive version of this example is available when JavaScript loads.
The viral spike, the cold cache, and the invoice
The steady state is solved. Now the interviewer breaks it three ways, and how you respond is where staff-level thinking shows. Each break is a different lesson, and the third one is about money, which references almost never touch.
The three ways it breaks
- The cold cache. A config deploy restarts the cache fleet and it comes back empty. Initially, requests for uncached keys miss and increase database load; repeated keys become hits as the cache refills. The lesson: the database’s standing headroom must be sized for the miss storm, not the steady-state 10% miss rate. A design that only survives when the cache is warm is not resilient; it is lucky. Read replicas or request coalescing (identical concurrent misses collapsing into one lookup) absorb the flood.
- The hot link. A creator with millions of followers drops one link and its traffic multiplies tenfold in ninety seconds, all of it on one code. Scaling the database for traffic that should never reach it is the wrong answer; the identical redirect belongs at the edge, where a CDN serves the stampede and your origin keeps seeing the old, calm load. (This is the hot-key problem in miniature, one key taking all the traffic.)
- The bill. The spike never ends. The new normal is tens of thousands of redirects a second, and the CDN that saved launch night now bills per request, which at this volume is the whole invoice. The lesson: per-request edge pricing is cheap for spikes and expensive for steady baselines. Trade it for owned capacity: a load balancer fronting a horizontally scaled app fleet, sized to keep every tier below the queueing knee. Show the arithmetic, per-request price times monthly volume against instance count times unit price, and the answer picks itself.
Take each break in turn below, then flip from the failure to the fix: the miss storm sized for, the hot key pushed to the edge, the invoice traded for owned capacity.
The interactive version of this example is available when JavaScript loads.
Now put numbers on each of them, because "the cache absorbs it" and "the CDN handles it" are the two sentences an interviewer has heard most often and believes least.
Start with the cold cache. Warm, the store sees 400 requests a second. Empty, it sees all 4,000, the full redirect rate, against a store rated for 5,000 requests a second. Its load rises from 8% to 80% before counting writes, and its response times need checking under the burst. Two read replicas, each rated for 5,000 requests a second, give the redirect path 10,000 a second of nominal capacity, and the mints keep the primary to themselves. That is what "sized for the miss storm, not the steady state" actually means in boxes.
The interactive version of this example is available when JavaScript loads.
There is a cheaper half to the same fix, and it costs no hardware at all. In a miss storm the 4,000 requests a second are not 4,000 different questions. They are the same few hot codes asked over and over, and every one of them starts its own trip to the store. Let the first one do the work and make the rest wait for its answer, and thousands of identical lookups collapse into one. Watch the collapse happen:
The interactive version of this example is available when JavaScript loads.
Then the hot link. This is a hot key, and it has its own playbook worth knowing by name: hot key mitigation walks what you can do when one row carries traffic no single machine can. As a napkin example, suppose traffic goes from 4,000 to 40,000 a second with one code dominating. The lab uses a skewed distribution across 1,000 keys instead of assuming every request has one key. An identical answer is exactly what an edge is for. Assuming nine in ten are served near the reader, 10% of 40,000 is 4,000 a second arriving at your balancer, which is the load this design has been handling since the fleet stage. The spike lands on a network you rent rather than on the store you own.
Mints bypass the edge. In the lab the tenfold injection multiplies the whole workload, so about four writes a second also become forty. The read-heavy ratio remains the same.
The interactive version of this example is available when JavaScript loads.
The interactive version of this example is available when JavaScript loads.
And then the bill, which is the break that separates a design from a decision. The spike does not end: 40,000 redirects a second is the new baseline. Forty thousand a second times 86,400 seconds is about 3.5 billion requests a day, times thirty days is roughly 104 billion a month. Using the lab’s teaching tariff of sixty cents per million that is 104,000 × $0.60, or about $62,000 a month, for a service whose whole dataset fits on one disk.
Now price the other side, with the same load and no edge in front of it. 40,000 ÷ 2,000 per app server is twenty servers at full stretch, so run twenty-four at $45 each: $1,080. Cold-cache redirect reads need 40,000 ÷ 5,000 = eight read replicas at full capacity. Run twelve for headroom at $90 each: another $1,080. Add $18 for the balancer, $30 for the cache and $120 for the primary. The fixed capacity bill is $2,328 a month, against about $62,000 in CDN request fees alone. That is roughly twenty-seven times cheaper under these teaching prices, for traffic that no longer needs the elasticity you were paying for.
The interactive version of this example is available when JavaScript loads.
In the lab, remove the edge from the steady high-volume path to stop paying its per-request tariff. The article diagram keeps an edge available for a separate spike route; it is not on the normal path. A real deployment needs an explicit routing policy to make that distinction true. "Rent the surprise, own the routine" is the whole rule, and the arithmetic above is how you defend it in the room.
One last number for the worst day, because an interviewer at the senior end will ask for it: a viral spike arriving while the cache is cold is about 100,000 redirects a second with nothing warm to help. 100,000 ÷ 2,000 is fifty app servers, so sixty; 100,000 ÷ 5,000 is twenty read replicas at full capacity, so thirty for headroom; and even the balancer tier stops being one box, since 100,000 ÷ 50,000 is two at full stretch, so three. Nothing new is invented on the worst day. Every tier is the same arithmetic, run against a bigger number.
What each level is expected to reach
The same problem is graded against four different bars. What moves between them is not the diagram. It is breadth, depth, and how much of the conversation you lead without being prompted. This is exactly how the lab calibrates the substance of your submitted reasoning. Choose your practice level at the start. Work through requirements and APIs before building on the canvas, then explore the deeper extensions. Your chosen level guides the reviewer; it does not guarantee a passing assessment. A reviewer-assessed ladder answer can support a level bar; self-placement and an unreviewed answer cannot.
| Level | What you are expected to reach |
|---|---|
| SDE1 | A working design: mint and redirect, a mapping table in a durable database, and a 302. You know uniqueness matters and can propose at least one code strategy (hashing with a uniqueness constraint). You recognise a cache helps reads, often once prompted. The interviewer drives the later stages; you keep up. |
| SDE2 | You lead with the read-heavy asymmetry up front and structure the whole design around it. You articulate the code-generation trade-offs unprompted and reach the atomic counter; you size the cache and name a hit ratio; you defend the 302; and you can sketch the latency budget from where the answer lives. |
| SDE3 | You go genuinely deep in two or three places with real numbers: the distributed counter with leased ranges, cold-cache headroom sized for the miss storm, the enumeration mitigation, and the cost arithmetic that defends your fleet sizes line by line. You are running most of the conversation. |
| Principal | You interrogate the requirements themselves ("is the complex version even needed here?") and choose the simplest design that meets the numbers (no sharding at 100 GB). You reason about blast radius and the marginal cost of resilience, name an explicit degradation contract for the worst day, trace second-order effects (what the miss storm does to everything sharing the database tier), and say plainly what you chose not to pay for. |
Common pitfalls
The traps that cost candidates the round
- Boiling the ocean in requirements, adding accounts, analytics, editing and teams, instead of scoping down to the two paths that carry the product.
- Serving redirects from application-server memory, which loses every link on restart. "It works" is not "it is durable."
- A redirect via a query parameter (
?code=x7Gk2f) instead of a path parameter. The short code has to BE the URL, because that is what people share. - Verb endpoints (
POST /shorten) instead of resource nouns (POST /urls). - Choosing
301for the free redirect speed and going blind to expiry and analytics, without naming the trade. - Sharding a 100 GB dataset because "it is a big system". The bytes were never the problem; the request rate is.
- Sizing the database for the steady-state 10% miss rate and calling it resilient, then falling over the first time the cache restarts cold.
- Keeping the CDN as traffic becomes a steady high baseline, where per-request pricing quietly becomes the entire bill.
- A per-tap click-event row in the core data model. That firehose belongs to the analytics system you parked.
- Sequential, enumerable codes that let a stranger walk every link you have ever minted.
Interview cheat-sheet, from intern to principal
- What are the two core functional requirements, really?
- Mint a short link for a long URL (the write path), and redirect a short link to its destination (the read path). Everything else, vanity codes and expiry included, is optional; accounts and analytics are out of scope for the hour.
- What is the single most important property of this system?
- It is read-heavy, roughly a thousand reads per write. State it first; it drives caching, database choice, where you scale, and where the money goes.
- How do you generate a short, unique code?
- Base62 gives ~3.5 trillion codes in seven characters, so length is never the issue. Climb the ladder: hashing with a uniqueness constraint and bounded retry (junior), an atomic counter for guaranteed uniqueness (mid), leased counter ranges for coordination-free distributed writes (senior). Keep a uniqueness constraint on the code column as the final net regardless.
- Why does the first collision come so early?
- The birthday paradox: the first clash among random codes appears after about the square root of the space, a few hundred thousand links for a 56-billion space, not billions. That is why the uniqueness constraint is never optional.
- Why 302 and not 301?
- Use 302 for a temporary destination, with explicit cache directives. A 301 can be cached heuristically; a 302 can be cached explicitly. Browser revalidation and a bounded shared-cache lifetime preserve expiry control. Status alone does not guarantee a server visit.
- How do redirects stay under 100 ms?
- A redirect is one tiny lookup; the latency is network and TLS, not the read. Keep the answer in an in-memory cache (a ~100 ns hit), size the cache TTL under the link’s expiry, and push hot links to a CDN at the edge so distant readers avoid the cross-continent round trip.
- A single link goes viral. What happens?
- The whole spike is one hot code, so serve the identical redirect from the edge (CDN). The origin keeps seeing its old, calm load; you never scale the database for traffic that should never reach it.
- What breaks when the cache restarts cold?
- Every read becomes a miss at once and the full rate hits the database. Size the database’s standing headroom for the miss storm, not the steady 10% miss rate; read replicas or request coalescing absorb the flood.
- SQL or NoSQL, and do you shard?
- Either works, because the access pattern is a keyed lookup with no joins. At 100 GB you do not shard: the dataset fits in memory and a single replicated database serves it. The request rate, not the byte volume, is the real constraint.
- How do you expire links, and what does an expired one return?
- Store an expiry timestamp; check it on read (lazy) and sweep dead rows in the background. An expired link returns 410 Gone rather than 404, because it legitimately existed and is now over, which is different from never having existed.
Takeaway
By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.