System Design · Interview breakdown · Free article
Design a Flash Sale System
Five hundred units, two million buyers, and one number that has to be exactly right. The full interview walk through a limited inventory sale, from requirements through the deep dives, with the bar named at every level from intern to principal.
A flash sale looks like a checkout with a bigger crowd. It is not. Most systems are allowed to be a little wrong for a moment: a stale count, a link that resolves a second late, a limiter that waves four extra requests through. Here one number must be exactly right while two million people race to change it inside the same ten seconds, and being wrong costs a refund, an apology, and a seller who never trusts you again. The shape of the whole problem is a funnel: demand is unbounded, the work is not. Two million arrivals have to collapse into five hundred durable sales, and every layer you add exists to shrink the crowd before it reaches the one number that must stay correct. This breakdown walks the path a strong candidate takes: why two buyers both see "1 left" and both win it, the single move that makes a claim unsplittable, why a claim is not a sale and what has to expire it, how you charge exactly once through a retried callback, and what the drop does the second the counter node dies mid-sale.
Practise one part of it on a canvas that tests your design: Hold the Last Ticket.
The problem, made real
The interviewer slides one sentence across the table: "A seller is dropping five hundred passes on Friday at noon. Two million people already have the link. Sell exactly five hundred."
The short answer, before the walk. A flash sale is not a checkout with more traffic. It is a funnel: demand is unbounded, the work is not, and two million arrivals have to collapse into five hundred durable sales without the count ever going below zero. The mechanism is three moves. Make the claim a single atomic operation so two buyers cannot both win the last unit. Hold the unit rather than sell it, because a human still has to find their card, and expire the hold so an abandoned checkout gives the unit back. Then make the payment callback idempotent, so a retry charges once. Everything else on the page is about shrinking the crowd before it reaches that one number.
Concretely: this is the first time the product touches money, and the first time a number has to be exactly right.
Here is what makes it hard, and it is not the traffic. The crowd does not build over an afternoon. Everyone has the same link and the same clock, so two million people arrive inside the same ten seconds. Almost none of them can be served: five hundred winners, and 99.97% of the crowd leaves with nothing. And the one thing they are all racing for is a single number that must never go below zero. Get it wrong by one and you have sold a pass that does not exist, which means a refund, an apology, and a seller who takes their audience somewhere else.
What the system must do
Turn that one sentence into a list of what the drop must do, and name what it will not. The temptation on a sale problem is to reach for the whole store: recommendations, reviews, a cart, shipping. A stronger candidate notices that a drop is not a store. There is one item, one moment, and one hard promise, and every requirement either serves that promise or is scenery.
Order them most important first. Here the order is a claim about what the product is: this is not a page that happens to sell something, it is a claim that happens to have a page.
The seven things the sale must do
- Decide a claim. A buyer who taps Buy gets one of two answers: they win a unit, or it is gone. This is the product, and everything else on this list supports it. Notice what is deliberately absent: how many may be sold, and how quickly the answer arrives. Those are promises about this capability, they carry numbers, and they belong in the next list.
- Show the drop and how many are left, to everyone, for the whole sale. Two million people want the page and the number on it. They are not buying yet, but if the page falls over nobody buys at all.
- Hold a won unit for the buyer while they pay, then confirm the sale when payment succeeds. Winning is not paying, because a human still has to find their card. How long that hold lasts is the promise attached to it, and it gets its number in the next list.
- Give the unit back when a buyer walks away. Most people who win a hold never complete it. If an abandoned hold keeps its unit forever, a sold-out drop ends with stock nobody could buy, the worst possible outcome for the seller.
- Take payment for a confirmed claim and record the order against it. Kept as its own capability because stock and money fail independently. How many times a card may be charged is the promise attached to it, and it is stated, with its number, in the next list.
- Cap each buyer at one unit. Five hundred passes going to five hundred people is the drop the creator sold; five hundred passes going to one script is a story about you.
- Show the drop as sold out once stock is gone, so the crowd can see it without claiming. Once that state is visible on the browse path, most of the crowd never touches the claim path at all, which is what later lets you refuse people cheaply, a long way from your servers.
What must be true of it
Functional requirements say what the drop does. Non-functional requirements say what must be true of it while it does them. Each promise below attaches to exactly one capability from the list above, and it is stated here ONCE, because a requirement that appears in both lists is two requirements that can drift apart. This is where the interview is won or lost, because a wish is easy and a requirement carries a number. "It should not oversell" is a wish. "Units sold never exceeds stock, one hundred percent of the time, and here is the mechanism" is a requirement you can hold a design against.
Most of what follows is the usual latency-and-availability work. One of them is not, and it is worth stating first, because it is the only promise on this page that has no percentile.
The promises the drop bets a creator’s trust on
- Correctness: units sold is less than or equal to stock. Always. This is not 99.9%, because a correctness invariant does not have a percentile, and the moment you write one you have said out loud that some buyers get a pass that does not exist.
- Consistency where it is claimed, availability where it is browsed. A claim must have exactly one winner, so that path takes the strict side. Browsing takes the other side: the page stays up and the count on it may be up to about two seconds behind. Two paths, two answers, one system.
- Claim latency: a buyer learns yes or gone in under 300 ms at p99. This is not comfort. An answer slower than a person’s patience gets refreshed, and a refresh in a crowd this size is a second arrival.
- Browsing availability: 99.9% even while the claim path is saturated. The two paths must not share a fate. If the claim burst can take the page down, the creator’s whole audience sees an error instead of a sale.
- The hold has a stated life: five minutes, after which the unit provably returns to the pool. Provably is the word that matters, because "we have a cleanup job" is not the same promise as "the unit comes back".
- Money moves at most once per claim. Not usually once. At most once, through double taps, retries, and repeated callbacks from the payment provider.
Size the crowd before you draw the drop
Before a box goes on the whiteboard, size it. The goal is not precision. It is the power of ten that decides the architecture. Round hard and say so: false precision ("we expect 1,983,400 arrivals") reads as nerves, while a confident "call it two million in ten seconds" reads as fluency.
Start from what the brief gave you. Two million people hold the link, and they all have the same clock. The drop opens at noon, so they arrive inside roughly ten seconds of it. Five hundred units. Everything else falls out of those three facts, and the last two rows are where the design is actually decided.
| Question | The arithmetic | The answer |
|---|---|---|
| How many page reads a second at the peak? | 2,000,000 arrivals ÷ ~10 seconds | ~200,000 reads/s, the biggest number in the problem, and not one of them is a sale |
| How many claim attempts a second? | say 1 in 5 taps Buy → ~400,000 taps ÷ the same ~10 seconds | ~40,000 attempts/s, a fifth of the read rate, and 800 attempts for every unit that exists |
| How many claims can ever succeed? | the stock, and nothing else | 500, for the entire sale, no matter how many people arrive |
| How many durable writes for the whole sale? | ~500 claims + ~500 orders + the holds that lapse and get re-won | ~2,000 writes in total, not per second, in total |
| How much memory does the contended state need? | one number per drop + ~400,000 buyer keys × ~40 bytes | ~16 MB, so it fits on a single node with room to spare |
Refusing early saves money. It also decides whether a sale degrades or collapses. Push the offered load past what a layer can serve and watch what happens to the work that actually completes:
The interactive version of this example is available when JavaScript loads.
The smallest data model that works
Name the data before the boxes. A drop looks like a product page with a button, but the model has to carry a promise through three states, nobody owns this unit, someone is holding it, someone paid for it, and it has to survive a crash in every gap between them. Four nouns do the whole job.
The four entities
- Drop: what is being sold and the terms of the sale, so the seller, the item, the total stock, how many remain, when it opens, and what state it is in (scheduled, live, sold out, closed). The remaining count is the single most contended value in the system, and every decision from here is about protecting it.
- Claim: one buyer’s grip on one unit, so which drop, which buyer, what state it is in (held, confirmed, released), and when the hold expires. This is the entity that makes "sold" a process rather than an instant, and the expiry timestamp is what turns an abandoned checkout back into stock.
- Order: the money half, so the claim it belongs to, the amount, the payment provider’s reference, the key that makes the charge repeat-safe, and its state (pending, paid, failed). Kept separate from the claim on purpose, because a claim is about inventory and a charge is about money, they fail independently, and merging them is how a refund becomes impossible to reason about.
- Buyer: the identity a limit lands on. Thin by itself, but it is what the one-per-buyer rule is written against, and pairing it with the drop is what makes that rule enforceable rather than aspirational.
Two faces: the crowd and the claim
Write down what a buyer does, and you have the contract you can defend right now. They look at the drop, they check what is left, they take a unit, they pay for it. Four calls, and every one of them comes straight out of a requirement you have already written.
Resist the urge to enumerate the whole surface here. Nobody arrives at a finished API five minutes into a design, and a table of nine endpoints written before any of the hard decisions have been made is a table full of calls you cannot yet justify. The rest of this contract is coming, but each of those calls is the consequence of a decision further down, and it reads far better when you add it there.
| Call | Shape | Returns / status |
|---|---|---|
| Read the drop | GET /drops/{dropId} | 200 with the item, seller, terms, and when it opens, the same bytes for everyone |
| Read what is left | GET /drops/{dropId}/availability | 200 {remaining, state}, a few bytes, deliberately its own call; it has to be able to go up as well as down |
| Claim a unit | POST /drops/{dropId}/claims with an Idempotency-Key header | 201 {claimId, expiresAt} · 409 sold out · 409 already claimed · 429 from the rate limiter |
| Pay for a claim | POST /claims/{claimId}/order with an Idempotency-Key header | 200 {orderId, state}. The same key replayed returns the same order, never a second charge |
Three small choices in there say the most about you. Sold out is 409 Conflict rather than a 200 with the failure hidden in the body, because a client that has to read your prose to learn it failed is a client that will get it wrong. The claim is a POST because the server picks the winner, so the buyer cannot name the thing they want in advance. And the idempotency key is created when the buyer decides to buy, not when the request is sent; otherwise a double tap makes two keys and the whole technique does nothing at all.
Here is the rest of the contract, so you can see where it comes from. Notice that not one of these rows is something you could have justified above. Each one is owed to a decision that is still ahead of you.
| Call | Shape | Earned by |
|---|---|---|
| Give it back early | DELETE /claims/{claimId} → 204 | The hold. Once a claim has a deadline, a buyer who changed their mind can return the unit now instead of in five minutes, and in a sale lasting seconds, five minutes is the rest of the event. |
| Check on a claim | GET /claims/{claimId} → 200 {state, expiresAt} | The same hold. The checkout screen has to be able to tell the buyer whether they still have the unit while the payment settles. Only winners ever call it. |
| The provider calls you back | POST /payments/callbacks → 200, always | Charging exactly once. The provider redelivers anything you do not acknowledge, so this is answered with a success even for a repeat, and keyed on the provider’s own event id. |
The dial below is the whole argument in one control. Drag the lifetime up and the crowd stops reaching you, but the copy in front of them drifts further from the truth; drag it down and you are honest and expensive. There is no setting that is right for both calls at once, which is why they are two calls.
The interactive version of this example is available when JavaScript loads.
The shape that shrinks the crowd
Now draw it. Draw it in the order the funnel forces, which means starting with the least impressive version.
The simplest thing that could work is three boxes: a buyer, an app server, a database. The buyer asks for the page, the app server builds it, and the database holds the item and the count. When the buyer taps Buy, that same app server writes the sale into that same database. At ten people a second this is not a compromise. It is correct, it is cheap, and for a small drop it is genuinely the right answer.
Do not skip past it in an interview. Building the naive version out loud and then breaking it yourself is far more convincing than arriving with the finished picture, because it shows the interviewer the reasoning that produced the picture. An answer that starts at the end is hard to tell apart from an answer that was memorised.
So break it, with the numbers from the estimation rather than with a feeling. Two hundred thousand people a second want the page. One app server handles about two thousand requests a second. Two hundred thousand divided by two thousand is one hundred, and one hundred is the wrong number to write down. It is what you would need if every server ran at exactly its rated limit for the whole sale, and a queue at full utilisation does not settle, it grows: the first slow request delays the next one and nothing ever catches up. Leave each machine about a fifth of itself spare and the fleet is a hundred and twenty five, every one of them doing the same trivial job of handing out a page that has not changed since the drop was created.
Now look behind them. One database serves roughly four thousand reads a second. Two hundred thousand divided by four thousand is fifty, which becomes sixty three once you leave the same room to breathe. That is a hundred and eighty eight machines. And here is the part worth saying out loud: almost none of that traffic is a sale. You have sized the entire system for people who will never spend a cent.
Draw that starting point honestly before you improve it. From here on the picture grows with the argument. Every requirement and deep dive you settle adds exactly the piece that earns it, and nothing arrives before it has been paid for. Hover a promise under any diagram to see which parts of the design are keeping it:
The interactive version of this example is available when JavaScript loads.
| Where the page is answered | What it buys | What it still costs you |
|---|---|---|
| From the app server, every time | Nothing to build; always current | ~125 app instances and ~63 database copies for traffic that buys nothing. The honest starting point, and unaffordable. |
| From a cache in front of the database | The page is built once and served from memory, so one node absorbs the whole read rate | The requests still reach your app servers and your network. You have made each answer cheap, not made the crowd smaller. |
| From a copy near the buyer (chosen) | The page is identical for two million people, so it is served before it ever reaches you, and the crowd shrinks by an order of magnitude or more | It can only serve what is safe to be slightly old. Which is exactly why the number that must not be old was split into its own call. |
One detail is worth spelling out, because the arrow on the diagram hides it. When the copy near the buyer does not have the page, a miss, it does not send the buyer somewhere else. It opens its own connection to your origin, fetches the page, keeps a copy for next time, and answers the buyer on the connection they were already holding. One request from the buyer, one response, and they cannot tell a miss from a hit except by the timing.
Say that out loud, because the alternative exists and is worse. A copy could instead answer "not me, go ask over there" and let the buyer make a second request. That costs an extra round trip to the buyer and back before anything useful happens, which is exactly what you cannot afford when two million people arrive at once. It also hands out your origin address. Redirecting is reserved for cases where the second hop genuinely goes somewhere else, a signed link to blob storage being the usual one, and this is not one of them.
So every arrow from here on is the direction a request travels. The reply comes back the way it came, and the diagrams do not draw it, with one deliberate exception you will meet in a moment.
That settles the read path, and it is worth stating plainly what it now costs you. The drop page is cached far away from you, so about ninety five percent of the crowd is answered before it ever reaches your servers. The other five percent, ten thousand reads a second, still comes through, and that leftover is the number every fleet size from here on is built on. CDN edge caching is where that percentage comes from and what moves it, which is worth knowing here because if it drops to eighty the misses quadruple, and the first thing to run out is the read copies behind your servers, not the app fleet. The availability number is a separate, tiny call with a short lifetime, so it stays close to the truth without dragging the whole page along with it. Two million people can arrive, and the machines you are paying for barely notice.
That is the first of the two lanes finished. Everything from here belongs to the second one.
The interactive version of this example is available when JavaScript loads.
Now the claim path. It is the opposite problem in every way, and the arithmetic is worth walking slowly, because this is where most designs go wrong.
Forty thousand people a second are tapping Buy. Suppose each tap becomes a write to the database. A database absorbs roughly eight hundred writes a second. Forty thousand divided by eight hundred is fifty, so you would need fifty database instances. That is the same expensive answer as before, except this time you are buying it in order to write down refusals. Almost every one of those taps is going to be told no, and you would be paying full price for each no.
So stop and ask what a refusal actually requires. To turn somebody away, the system has to answer exactly one question: is the count above zero? That is not a sale. Nothing durable has happened. Nothing has to survive a crash, and nothing has to be written down at all. It is a question about a single small number.
That reframing changes what you need to buy. A number held in memory can be read and updated about a hundred thousand times a second by one node. Forty thousand is comfortably below a hundred thousand, so one node can answer every tap in the sale, with room to spare.
So move the count out of the database and into a shared in-memory store that all the app servers reach. The claim is decided there. A buyer who wins gets a unit; a buyer who loses is told immediately, and their request goes no further than that store. That last part is the one that matters most: a refusal ends its journey at the counter, and the database never hears about it at all.
The interactive version of this example is available when JavaScript loads.
Now look at what that leaves for durable storage. Only winners get past the counter, and there are five hundred of those. Add the orders they turn into, and the holds that lapse and get won again, and the whole sale produces something like two thousand writes. Not two thousand a second. Two thousand in total, across the entire event. One database handles that without noticing.
There is still one thing left to fix. As it stands, the buyer waits while that write is committed, and a durable write is the slowest step in the whole path. So take it off their wait. The app hands each won claim to a queue, and workers read from the queue and write the rows at their own pace. The buyer’s request returns the moment the decision is made.
That is the 300 ms promise paid for. The buyer waits for an answer, not for storage.
The interactive version of this example is available when JavaScript loads.
One last piece before the deep dives, and it follows the same arithmetic as everything else. Forty thousand claim attempts a second arrive at the app servers, and they do not arrive alone: the ten thousand reads a second the page copy missed land there too. Fifty thousand requests a second, at about two thousand each, with the same fifth of every machine left spare, is about thirty two app servers.
Thirty two servers with nothing in front of them is not a fleet, though. Something has to decide which server each request goes to, and without that, traffic piles onto whichever one the buyer happens to reach. So put a balancer at the door, and every instance carries an even share.
And once it is there, it fronts the app servers for everything, not just for claims. Think about the read path for a moment. The page copy answers almost every request itself, but a miss still has to reach an app server, and there are thirty two of them now. The copy has no way of knowing which one to use, and no business knowing. So a miss goes to the balancer as well, and the balancer picks. Anything that reaches your servers goes through the one thing whose job is choosing which server.
Notice what does not change here. The counter store stays a single node. It holds one number, and one node already answers far more requests a second than this sale produces, so there is nothing to gain by adding a second one, and, as the estimation warned, nothing to split across it even if you wanted to.
The interactive version of this example is available when JavaScript loads.
The claim moat: two buyers, one unit
This is the section the whole interview exists for. Everything so far has been about making the crowd smaller and cheaper, and none of it touched correctness. Now two buyers reach the counter in the same instant, one unit is left, and the system has to pick exactly one of them.
Watch the obvious code fail. Go slowly here, because the failure is invisible in the source and completely obvious in the timeline.
The app reads the count and sees 1. It checks that value: greater than zero, so this buyer wins. It writes 0 back and confirms the sale. Read, check, write. For one buyer at a time that is perfectly correct, and it will pass every test you write on your laptop.
Now run two buyers through it at once, interleaved the way real concurrency interleaves them. Buyer A reads the count and sees 1. Before A writes anything, buyer B reads the count and also sees 1. A checks the value it read: above zero, so A wins. B checks the value it read: also above zero, so B wins too. A writes 0. B writes 0.
Now count the damage. Two buyers were confirmed. One unit existed. And the count reads 0, which is exactly what it would read after one correct sale, so nothing in your data looks wrong, no error was logged, and no alarm went off. Nobody finds out until somebody is turned away at the door on Friday night holding a pass you sold them.
| Approach | Why it appeals | Where it breaks |
|---|---|---|
| Read, check, write back | It is the code you would write without thinking, and it works perfectly under no contention | Two buyers in the same gap both win the last unit. Oversells rise with contention, which means the more successful the drop, the more you break your promise. |
| Take a lock on the row, then decide | Genuinely correct: the second buyer waits for the first to finish, and nobody enters the gap | Every claim now queues behind every other claim on one row. Forty thousand attempts a second serializing on a single lock is the latency budget gone, and the database strains under lock traffic for requests that mostly end in no. |
| One conditional write the store cannot split (chosen) | A single instruction: decrement only if greater than zero. There is no gap to enter because there are no separate moments, and the store settles the order and hands back the result | It protects the count and nothing else. The money, the hold, and the one-per-buyer rule each still need their own answer, because this rung buys you exactly one guarantee, cleanly. |
Take the third rung, and be precise about what it does. The claim becomes a single instruction sent to the store that holds the count: subtract one, but only while the value is above zero, and tell me what happened.
The word carrying the weight is only. The condition and the subtraction are evaluated by the store as one indivisible action, so there is no moment between them for another request to slip into. Either you were the request that found the value above zero and took it down, or you were not, and the store tells you which one you were.
Run the two buyers through it again. Both send the instruction. The store handles one of them first: it finds the count at 1, subtracts, and reports success. Then it handles the second: it finds the count at 0, declines to subtract, and reports failure. One winner, one honest refusal. No interleaving is possible, because there are no longer separate steps to interleave.
The loser learns immediately, which is exactly the cheap no the estimation asked for.
And a second guarantee arrives at no extra cost. Because every claim is settled at one point, in the order that point receives them, the winners are decided by when they arrived rather than by which app server happened to be quickest. First come, first served stops being a hope and becomes a property of the design.
One caveat, because the instruction is not always available to you. Not every store offers a conditional write. When it does not, you buy the same guarantee a slightly longer way: read the value together with a version marker, work out the new value yourself, and write it back only if the version has not moved in the meantime. If it has moved, somebody else got there first, so you throw your work away and try again.
The cost is those retries. Under heavy contention, which is precisely what a drop is, many attempts lose the version check and go round a second or third time, and every retry is another round trip. That is why the single instruction is the one to reach for wherever you can get it. Toggle the interfering writer on below and watch a claim lose the check and repeat:
The interactive version of this example is available when JavaScript loads.
One thing worth fixing in your head before you move on, because it is a common stumble: neither of these rungs belongs to a particular product. Both are shapes. A conditional write is not a SQL feature and compare-and-set is not a Redis feature, because every serious store offers both, under its own name. So choose the store for reasons that have nothing to do with this decision, and then use whichever of the two it hands you.
The interactive version of this example is available when JavaScript loads.
A claim is not a sale
Winning is not paying. Between the two stands a person hunting for their card, and people take minutes, get interrupted, and frequently give up altogether.
That gap is the second hard problem. The instinct is to hold the unit until the payment completes, and it is worth being exact about why that fails, because it sounds so reasonable.
Holding means the unit stays claimed for as long as the buyer is deciding. But you do not control how long that is. And you cannot tell the difference between a buyer who is carefully typing a card number and a buyer who closed the tab an hour ago, because from the server both look identical: a claim that has not been paid for yet.
So a buyer who wins a unit and walks away takes that unit out of the sale permanently. Multiply by the share of people who abandon a checkout, which is never small. A drop that sells out in eleven seconds can finish the night with units nobody was ever allowed to buy. That is the worst outcome on the board for the seller, and the cruellest part is that it is invisible: from the outside it looks exactly like a successful sell-out.
| Approach | Why it appeals | Where it breaks |
|---|---|---|
| Hold it until payment completes | Simple and obviously correct while the buyer is present | The buyer is often not present. A closed tab holds a unit forever, and a sale that sold out can finish with units unsold and unbuyable. |
| Mark it held with an expiry, and run a job that releases lapsed holds | The unit does come back, and the job is easy to write and easy to reason about | The unit comes back when the job next runs. During a sale measured in seconds, a sweep that runs every minute means the unit is dead for the rest of the drop. Correctness now depends on a schedule. |
| Make the expiry itself the answer (chosen) | A unit is available when no unexpired hold exists, so the release happens by the passage of time, and nothing has to run for the stock to come back | You still want a tidy-up pass, but it is now housekeeping rather than correctness. And the returned unit is a second contended write, which has to go back through the same atomic path. |
So a claim carries a deadline, five minutes, per the requirement you wrote earlier. And the rule everything downstream follows is this: a unit is available unless there is a hold on it that has not yet expired.
Read that rule once more, because the phrasing is the whole trick. Nothing has to run for a unit to come back. The hold does not need to be deleted, and no job needs to notice that it lapsed. The moment the deadline passes, the hold stops counting, and the unit is available by definition. You will still want a tidy-up pass to clear stale rows, but it is now housekeeping: if it runs late, fails, or is switched off for an hour, not one unit is lost.
The count in memory gets the same care on the way back. When a hold lapses, the unit is added back with the same single instruction that took it away. Putting a unit back is a contended write exactly like taking one, and it can lose an update in exactly the same way if you are careless with it.
One consequence catches people out, so say it before an interviewer has to ask. Five hundred units does not mean five hundred claims. If a good share of winners never pay, the same unit can be won, abandoned, and won again, perhaps several times over. The pool churns. A buyer who arrived late and saw sold out may find stock again minutes afterwards. Which means the availability number has to be able to go up as well as down, and a design that assumes the count only ever falls will keep showing a sold-out page while units quietly return behind it.
The interactive version of this example is available when JavaScript loads.
The interactive version of this example is available when JavaScript loads.
Taking the money exactly once
The last promise is the one buyers notice most. A charge that happens twice is not a number on a dashboard. It is an email from somebody who trusted you, and it costs you a great deal more than the money you hand back.
What makes it likely is that it is caused by the most ordinary events in computing. A buyer taps Buy twice, because the first tap did not visibly do anything. A phone on a patchy connection sends the request again, because no reply came back. A payment provider calls you a second time about the same charge, because it never got a clear acknowledgement of the first call.
Look at what those three have in common. In every case the buyer formed one intention, and that one intention reached you more than once. And not one of them is a bug you can remove, because retries are how networks stay reliable, and a provider that gave up after a single unacknowledged call would be a worse provider.
So stop trying to prevent the repeats. Make the repeat recognisable instead. If the second arrival can be identified as the same intention as the first, you can answer it with the result you already produced, rather than doing the work a second time.
The three ways one payment becomes two, and the one idea that stops all three
- The buyer taps Buy twice. Two requests, one intent. The client generates a key when the buyer forms the intent rather than when the request is sent, so both requests carry the same key and the second is recognised as a replay of the first.
- The network retries. The request arrived and did the work, but the response was lost, so the client sends it again. Identical key, so the server returns the stored result of the first attempt instead of charging again. This is why the answer must be recorded, not just the fact that the key was seen.
- The provider calls back twice. Payment providers redeliver a callback they were not clearly told you received, which is correct of them. Use the provider’s own event identifier as the key and process each event at most once, and answer their callback with a success even when you have already handled it, because an error is an invitation to send it again.
Walk the three cases a real handler has to cover: a key it has never seen, a key whose work finished, and the awkward one in the middle where the same key is still in flight on another server.
The interactive version of this example is available when JavaScript loads.
And that completes the design. Notice that no box moved in this last stretch. The shape was settled once the crowd was shrunk and the claim was made unsplittable; the deep dives since then added no machinery, only responsibilities. The counter learned to lend a unit out and take it back. The durable store learned to recognise a repeated intention, and to refuse a second claim from the same buyer. Same picture, more promises kept:
The interactive version of this example is available when JavaScript loads.
Making "sold out" the cheapest thing you do
Go back to the funnel one more time, because there is a phase of this sale we have not designed for at all.
For the first second or so, the claim path is doing real work: buyers are winning units, holds are being written, the count is falling. Then the five hundredth unit goes, and the character of the traffic changes completely. Every request after that instant has exactly one possible answer, and you already know what it is before you look at anything.
That is most of the sale. If the crowd keeps arriving for another thirty seconds, then for thirty seconds your system exists only to say no, forty thousand times a second.
So make the no cheap, and make it cheap as far from your machines as you can get it. Once a drop is sold out, that fact is not going to change, which makes it the most cacheable piece of information in the entire system. Push it outward: the availability call can be answered at the copy near the buyer with a sold-out state, so the crowd is turned away before it reaches your servers at all. Edge load shedding is the concept page for this move, and it covers the part this section skips: what a refusal actually costs you at each layer you could make it at, and how to choose the layer.
And be precise about what that buys, because it is easy to overclaim. It does not make the claim path faster. It removes the claim path from the picture for people who cannot win anyway, which is a different and better thing.
Who gets in, and what fair even means
Now a question that is not really technical, which is exactly why it separates candidates. Five hundred units, two million people. Who should get them?
Notice that the design so far has already answered this without being asked. The conditional write settles claims in the order the store receives them, so the winners are whoever arrived first, measured in milliseconds, by machines. That is one definition of fair, and it is a defensible one. It is also the definition that rewards the fastest network connection and the best-written bot, which is why people who run drops for a living rarely leave it there.
There are three honest answers, and the useful thing is to know what each one optimises for.
| Approach | What it optimises for | What it costs you |
|---|---|---|
| First come, first served | Simplicity, and a reward for showing up on time. It is what the atomic claim already gives you, for free | It is a race, so it favours fast connections, fast devices, and scripts. The buyer on a train loses to a bot every time. |
| A waiting room | Orderliness and honesty. People are given a place in line and a wait time instead of a spinner, and you admit only as many as the claim path can serve | It orders the crowd, it does not shrink it. Admitting 20,000 to 500 units still ends in 19,500 refusals, now with a wait first. |
| A lottery over a window | Genuine equality of chance. Register for a few minutes, then draw, and arrival speed stops mattering entirely, as does the bot advantage | It removes the drama the creator may actually want, and it needs identity you trust, or one person enters a thousand times. |
The interactive version of this example is available when JavaScript loads.
The counter node dies mid-drop
Eleven seconds into the sale, the node holding the count restarts.
Stop and work out what has actually been lost, because the instinct is to say "the count" and the instinct is wrong. The claims are safe: winners went through the queue to durable storage, and those rows are on disk. What died is the referee, the fast number that decides who may try next.
So there are two questions, and only the second one is interesting. Can you carry on? Not safely, because with no count every arriving claim has nothing to check against, and a system that guesses here oversells. Can you rebuild it? Yes, and this is where the data model from earlier pays for itself. The count was never the truth. The truth is the claim rows, and the count is a number you can derive from them: the stock, minus the claims that are confirmed, minus the claims that are still held and have not expired. One query, and the referee is back.
The order of recovery matters more than the speed of it. Stop admitting claims first, then rebuild, then resume. A pause of a few seconds during a drop is embarrassing. An oversell is a refund and an apology, and it is permanent.
The interactive version of this example is available when JavaScript loads.
One pool, or one per region
The drop sells worldwide. Your counter is in one datacentre. A buyer in Sydney is two hundred milliseconds away from it, and every claim they make pays that round trip twice.
The reflex is to put a counter in each region. Follow it through before you say it, because this is the reversal the estimation warned about, and it is the one place where splitting a single number is genuinely on the table.
If each region has its own counter, they must own separate stock, say two hundred and fifty units in each of two regions, because two counters that both think they own five hundred will sell a thousand. And the moment stock is split, a new failure appears that could not exist before: one region sells out in four seconds while the other still has ninety units, and a buyer is refused in Sydney while stock sits unsold in Frankfurt. You have not eliminated the problem, you have traded a latency cost for an allocation cost.
So the honest default for a drop is one pool, in one place, and everybody pays the trip. Five hundred units is a small enough number that the coordination is worth more than the milliseconds. What changes the answer is scale: if the drop were five hundred thousand units, per-region pools stop being a compromise and start being obviously right, because the chance of one region starving while another sits idle falls as the pool grows.
What each level is expected to reach
The same problem is asked of an intern and a principal, and the difference is not how many boxes you draw. It is how far down each decision you can go before you run out of reasons. Here is what a passing answer looks like at each level, so you can aim at the right one.
| Phase | SDE1 | SDE2 | SDE3 | Principal |
|---|---|---|---|---|
| Requirements | Lists the obvious ones: show the drop, buy a unit, do not oversell | Produces the full list and quantifies the NFRs; separates browsing from claiming | Names the correctness invariant as having no percentile, and takes CAP per path | Raises the second-order requirements: what fairness means, what the creator is owed when it goes wrong |
| Estimation | Walks the arithmetic with prompting | Derives the read/claim split and the funnel | Derives that success is bounded by inventory, not demand, and prices the refusal | Reasons about the cost of the whole sale, and what it would take to run a thousand drops a day |
| The claim | Names the race when shown the interleaving | Reaches the atomic conditional write unprompted, and can say why a lock is worse | Handles the hold, its expiry, and the fact that the count must be able to rise | Reasons about the rebuild, the conservative direction, and what a standby copy does and does not buy |
| Money | Knows a charge can happen twice | Reaches idempotency keys | Places the key and the effect in one commit, and handles the retried callback | Owns the claim-and-charge disagreement: compensation, reconciliation, and what the buyer sees meanwhile |
| Scale & failure | Adds a cache and a queue when prompted | Shrinks the crowd deliberately at each layer, and gates the fleet behind a balancer | Survives the lost counter, and refuses cheaply once sold out | Takes the multi-region call with the arithmetic on both sides, and names what would reverse it |
The mistakes that cost the offer
Seven ways a good candidate loses this round
- Scaling everything to two million. The crowd is huge and the work is tiny; a design that sizes the claim path for the arrival rate has misread the problem at the first step.
- Stopping at the atomic claim. It is the most satisfying part and it is one third of the answer, because the hold, the money, and the per-buyer rule are three more promises with three more mechanisms.
- Holding a lock across a human. Any design where a unit stays claimed while a person types their card number ends the night with unsold, unbuyable stock.
- Treating the fast count as the truth. It is a referee, not a ledger. If you cannot say how you would rebuild it after a restart, you do not yet have a design.
- Caching the availability number as hard as the page. They come from the same field and they have opposite lifetimes: a positive count is perishable, sold-out is final.
- Assuming the count only falls. Abandoned holds put units back, so availability has to be able to rise, and a UI that cannot show that will keep saying sold out while stock returns.
- Answering "who gets in" with one word. First-come, waiting room, and lottery are three different definitions of fair, and which one is right is the creator’s call, not the engineer’s.
Questions you should be able to answer cold
If you can answer these without notes, you are ready for this round
- Two buyers tap Buy on the last unit in the same instant. What goes wrong, and what fixes it?
- Both read the count as 1, both judge themselves the winner, both write 0. That is a lost update, and the final state looks exactly like one correct sale. The fix is to stop doing it in three steps: one conditional write the store cannot split ("subtract one, but only while it is above zero"), so there is no gap for the second request to enter.
- Why not just lock the row?
- It is correct, and it is expensive in the one place you cannot afford it. Every claim for this drop queues behind every other claim on a single row, so the lock queue becomes the latency, and you are paying a transaction plus a lock for requests that will mostly end in a refusal.
- Why is a claim not a sale?
- Because a human still has to pay, and you cannot hold a lock across a person. A claim is a hold with a deadline; the unit belongs to that buyer until they confirm or their time runs out. Without the deadline, an abandoned checkout removes a unit from the sale permanently.
- A hold expires. What has to happen, and what usually goes wrong?
- The unit returns to the pool, and the good design makes that true by definition ("available unless an unexpired hold exists") rather than by a cleanup job, so nothing has to run for stock to come back. What goes wrong is the return trip: putting a unit back is a contended write exactly like taking one, and it can lose an update in the same way.
- How do you charge exactly once through a double tap and a retried callback?
- An idempotency key generated when the buyer forms the intent, not when the request is sent, so every repeat carries the same key and returns the stored result. The subtlety that decides whether it works: the key and the effect it guards must land in the same durable commit. Key first leaves a key claiming a charge that never happened; effect first leaves money taken with nothing to recognise the retry by.
- The counter node dies eleven seconds into the drop. What now?
- The claims are safe on disk; what died is the referee. Stop admitting claims, rebuild the count from the truth (stock minus confirmed claims minus unexpired holds), then resume. If the rebuild is uncertain, come back low, because a wrongly refused buyer can be given a unit later and an oversell cannot be taken back.
- Why can you not shard the count the way you sharded the rate limiter?
- The limiter had one counter per caller, so there was a key space to spread. A drop is a single number, so splitting it means allocating stock per node, which is not sharding, it is pre-assigning, and it lets one node show sold out while another sits on unsold units. At a small pool, keep one count; at a very large pool, per-region pools become right for the same arithmetic reason.
- What would you alert on?
- Oversold units, at any value above zero, paged immediately, because it is the promise. Then holds expiring on a sold-out drop (the window is too long), and the claim-to-paid ratio (a checkout problem, not an inventory one). Not request rate: 40,000 a second and a wall of refusals is the system working as designed.
By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.