InterviewDryRun
Lesson 20 · 21 min video · free

Design a Flash Sale

A million people press buy at exactly 10 am for ten thousand items. This lesson designs a checkout that survives it: serving the page from the edge, a waiting room that admits buyers at a rate the back end can handle, an in-memory stock counter that is decremented atomically, short reservations that expire, an asynchronous order pipeline, never selling more than you have, and keeping bots out so real people get a fair chance.

What you will learn

  • Nearly all of the million requests must be answered without touching the database.
  • Serve the product page as static content from the edge, with the stock state as a tiny cached value.
  • A waiting room turns a one-second spike into a steady stream the back end can handle.
  • Decrement stock atomically in memory first; only winners go on to the database.
  • A reservation holds an item for a few minutes; unpaid reservations return to stock.
  • Fairness is a product decision: first come first served, a lottery, or limits per person.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: Protect the core from the crowd
  5. Step 4: The API and the data
  6. Step 5: Static pages and the edge
  7. Step 6: The virtual waiting room
  8. Step 7: The stock counter
  9. Step 8: Reservations that expire
  10. Step 9: The order pipeline
  11. Step 10: Bots and fairness
  12. Step 11: One sale, second by second
  13. Step 12: Failures and testing
  14. Step 13: The follow-up questions
  15. Recap
Practice this question with Max

The question

Welcome to lesson twenty of the system design course. Today's question is: design a flash sale. The interviewer says: design a checkout that survives a million people buying ten thousand items at exactly ten a.m.

You have seen these. A new phone launches in limited numbers. Concert tickets for a famous band. A big shopping festival where a television is ninety percent off, but only a thousand of them. Everyone knows the time. Everyone presses the button in the same second.

What makes this question special is the shape of the traffic. Most systems see load that rises and falls over hours. Here, almost nothing happens at nine fifty-nine, and then a million requests arrive in one second at ten o'clock. Then, about two minutes later, it is all over, because everything is sold.

And there is a hard correctness rule underneath the chaos: never sell more than you have. Selling ten thousand and one items, when you only have ten thousand, means a real person paid for something that does not exist. The interviewer wants to see you handle both the flood and the counting.

We will go step by step: requirements, estimates, then the main idea, which is protecting the core from the crowd, then the stock counter, reservations, the order pipeline, fairness and bots, and the follow-up questions. Let us start.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    Sale pagecountdown, price, sold out or not
  2. 02
    Buylimit per person, often one
  3. 03
    Reservehold the item for a few minutes
  4. 04
    Paywithin the hold window, or lose it
  5. 05
    Confirmorder created, email sent
  6. 06
    Sold outclear, fast answer for everyone else

Functional requirements first. Users see a sale page with a countdown. At the start time, the buy button activates. A user can buy, usually limited to one or two per person. They get a reservation, pay within a few minutes, and get an order confirmation. When stock runs out, everyone else sees sold out.

Ask the interviewer: does the user pay inside the flash sale flow, or is the item just reserved and added to a normal checkout? Usually it is the second: you win the right to buy, then you have ten minutes to pay. That split matters a lot, because payment is slow and we do not want it in the hot path.

Non-functional requirements
  1. 01
    No oversellingsold count never exceeds stock
  2. 02
    Survive the spike1 million requests in a second
  3. 03
    Fast answerswinners and losers both told quickly
  4. 04
    Fairbots and scripts do not take everything
  5. 05
    Isolatedthe rest of the shop stays healthy

Non-functional requirements. No overselling, ever: this is the one correctness rule. High availability during the peak: the page must not fall over, and losers should get a fast sold out, not an error page. Fairness: real users should get a fair chance against bots. And the rest of the shop must keep working while the sale is on.

Notice what is not required. We do not need every request to reach the database. We do not need strict first-come, first-served to the millisecond, because nobody can measure that across the internet anyway. And we do not need to keep everyone on the page forever. Those relaxations are what make the design possible.

Step 2: Back-of-the-envelope estimates

Sizing it
Users waiting1 millionpage open at 9:59
Buy clicks1 million in about 1 s10 million+ requests in the first minute
Items10,000so 99% of buyers lose
Database writesabout 10,000 ordersplus reservations that expire
Sale durationabout 1 to 2 minutesthen mostly sold out pages
Payment ratea few hundred / sspread over the hold window

Let us put numbers on it. One million users waiting on the page. Each refreshes the page or polls the countdown. In the first second at ten o'clock, say one million buy clicks. Over the first minute, with retries and refreshes, maybe ten million requests.

Now the key ratio. Ten thousand items, a million buyers. Ninety-nine percent of buy clicks will lose. That is the most useful number in the whole design. It says: the losers are the bulk of the traffic, and the cheapest possible way to tell them sold out is where most of our effort should go.

The database only needs to record about ten thousand orders. Even if we wrote them all in one second, that is ten thousand writes, which one well-sized database can handle. But a million writes in one second, one per click, would crush it. So the design goal is to filter a million clicks down to about ten thousand before anything touches the database.

Payments are spread out. Winners have, say, ten minutes to pay. Ten thousand payments over a few minutes is a few hundred per second, which a payment provider handles normally. Keeping payment out of the ten o'clock second is a big part of why this works.

Step 3: Protect the core from the crowd

The funnel
buy clickadmitteddecrementwinnersold out flagCLIENT1M usersEDGECDN / edgestatic page, cached stateSERVICEWaiting roomadmits N per secondSERVICEBuy servicelimits, checksCACHEStock counterin memory, atomicQUEUEOrder queueSERVICEOrder serviceDB writes

Here is the big idea. Think of the system as a funnel with layers. Each layer answers as many requests as it can, as cheaply as it can, and passes only the remainder inward. The database at the center sees a tiny fraction of the traffic.

The outer layer is the edge, a content delivery network. The sale page is static HTML, images and script, cached at hundreds of edge locations. A million page loads never reach our servers. Even the countdown is computed in the browser from the start time, not by asking our server every second.

Next, the waiting room. Buy clicks go here, and it admits users into the real purchase flow at a fixed rate, say twenty thousand per second. Everyone else waits in a queue, with a position and a friendly message.

Admitted users reach the buy service, which checks their limit, and tries to decrement an in-memory stock counter. If it succeeds, they are a winner, and their order goes onto a queue for the order service to write calmly to the database.

And when the counter hits zero, a sold out flag is pushed back out to the edge, so all remaining clicks get sold out straight from the edge, in milliseconds, without touching anything else. That one flag answers most of the ninety-nine percent of losers.

Step 4: The API and the data

API
GET  /v1/sales/42/state        → { status: upcoming | live | sold_out, starts_at }
POST /v1/sales/42/queue        → { token, position }
GET  /v1/sales/42/queue/{token} → { position, admitted }
POST /v1/sales/42/buy          { token, item_id, qty: 1 }
  → { reservation_id, expires_at } | { sold_out }
POST /v1/checkout              { reservation_id, payment }

Before the deep dive, sketch the API and data, because it makes the layers concrete. There are only a few calls. Get the sale state, which is cached at the edge. Join the waiting room, which returns a signed token. Poll your position. Buy, with an admitted token. And pay, with the reservation id.

Notice that buy does not take payment. It answers a single question, did you win, and returns quickly either way. The checkout call is the normal shop checkout, which already knows how to take payment and send emails. We reuse it instead of building a second, rushed payment path for the sale.

Data
WhereKeyHolds
sales (DB)sale_idstarts_at, items, limit per person
inventory (DB)sale_id, item_idstock, sold; check sold <= stock
reservations (DB)reservation_iduser, item, state, expires_at; unique (sale, user)
memorystock:sale:itemremaining count
memorybought:sale:userset once, expires after the sale

The data is small. A sales table with the start time, the items, stock per item and the per-person limit. An inventory row per item with stock and sold, and a database check that sold never exceeds stock. A reservations table keyed by reservation id, with a unique constraint on sale and user. And the in-memory keys: one stock counter per item, and one bought marker per user.

Say why the in-memory keys can be thrown away. If the memory node is lost before the sale, we rebuild the counter from the inventory row. During the sale, the database constraints still hold. After the sale, the keys expire. So memory is a fast copy of a decision the database will also enforce, never the only record of who bought what.

Step 5: Static pages and the edge

At the edge
  1. 01
    Static pagepushed to the edge hours before
  2. 02
    Countdowncomputed in the browser from a fixed start time
  3. 03
    Server timeone cached call to correct clock skew
  4. 04
    Stock statetiny JSON, cached 1 second
  5. 05
    Buy buttonenabled at start time, plus a random 0 to 2 s delay

Let us go deeper on the edge, because it absorbs most of the load. The product page, price, images and countdown script are all static, and they are uploaded to the edge cache hours before the sale. When a million people load the page, the edge serves it.

Users' clocks are wrong, sometimes by minutes. So the page fetches the server time once, from a cached endpoint, and the browser corrects its countdown. Do not let the button enable based on the user's own clock, or people will just change their clock.

The only live data is the stock state: available, or sold out. That is a tiny document, cached at the edge for one second. A million users polling it means a million edge hits but only a few origin hits per second per edge location. One second of staleness is fine; the counter, not this flag, decides who wins.

One small trick: when the countdown hits zero, enable the button after a random delay of up to two seconds. Users barely notice, but it turns a one-millisecond spike into a two-second ramp. Every bit of spreading helps the layers behind.

Step 6: The virtual waiting room

Waiting room
click buy  → token { user, arrived_at, position, sig }
page polls → "you are number 412,330, about 40 s"

admitter: every 100 ms
  admit next 2,000 positions  (20,000 / s)
  admitted token → may call /buy for 2 minutes

stock = 0 → everyone still waiting sees "sold out"

The waiting room is the shock absorber. When a user clicks buy, they get a token with a position in the queue, issued at the edge or by a very light service. The token is signed, so it cannot be forged, and it records when they arrived.

A small admitter moves a pointer forward: every hundred milliseconds, the next two thousand positions are admitted. The rate is set to what the buy service can comfortably handle. Waiting users' pages poll their position, from cache, and show a progress bar.

Here is the beautiful part. Only ten thousand items exist. Once they are sold, we can stop admitting, and tell everyone still in the queue: sold out. So most of the million people never reach the buy service at all. They wait a few seconds and get a clear answer.

The waiting room also keeps the rest of the shop healthy. Without it, the flash sale's spike would compete with normal shoppers for the same servers and database. With it, the sale's load on the core is capped at a number we choose. That isolation is a requirement we wrote down; this is how we meet it.

Should admission be first-come, first-served? Partly. Network delays mean arrival order is somewhat random anyway. Some shops randomise the queue among everyone who arrived in the first few seconds, which is fairer for people on slow connections. That is a product decision; offer both.

Step 7: The stock counter

The race
request A: read stock = 9
request B: read stock = 9
request A: write stock = 8   (sold 1)
request B: write stock = 8   (sold 1 more, but count says 8)

→ oversold

Now the correctness core: never oversell. The naive way reads stock from the database, checks it is above zero, and writes stock minus one. Under concurrency, two requests read nine, both write eight, and you sold two items while counting one. Classic lost update.

Atomic decrement
left = DECR stock:sale42
if left >= 0:  winner → create reservation
else:          INCR stock:sale42   # undo
               loser  → sold out

per-user limit: SET bought:sale42:{user} NX  before DECR

The fix is an atomic decrement. Hold the stock count in an in-memory data store, and use a single operation that decrements and returns the new value, atomically. If the result is zero or more, you won. If it is below zero, you lost, and you add one back. No two requests can see the same value.

One in-memory node can do well over a hundred thousand of these operations per second, and the waiting room only lets twenty thousand per second through. So one counter is enough. If you needed more, you could split stock into ten counters of a thousand each, and route users by hash, at the cost of one shard selling out slightly before the others.

Enforce the per-person limit the same way: before decrementing, set a key for this user and sale, only if it does not exist. If it already exists, they have already bought. Both checks are in memory, both are atomic, and neither touches the database.

What if the in-memory node fails? Replicate it, and keep the database as the final authority. In the database, the order table has a unique constraint on sale and user, and an inventory row with a check that sold never exceeds stock. If the memory layer ever disagrees, the database refuses the extra order. The memory layer gives speed; the database gives the guarantee.

Step 8: Reservations that expire

Reservation lifecycle
StateMeaningNext
HELDitem held for this user, expires in 10 minPAID or EXPIRED
PAIDpayment succeededorder confirmed
EXPIREDuser did not pay in timestock + 1, next buyer
CANCELLEDuser gave upstock + 1

A winner has not paid yet. So what they win is a reservation: this item is held for you for ten minutes. The reservation is written with an expiry time. If they pay in time, it becomes an order. If not, it expires and the item goes back into stock.

Why not take payment right away? Payment takes seconds, involves redirects and one-time passwords, and sometimes fails. If winning depended on finishing payment in the ten o'clock second, the payment provider would face a million requests, and we would hold the stock lock during slow external calls. Reservations decouple the race from the payment.

When reservations expire, a sweeper increments the stock counter and flips the sold out flag back to available if needed. Some shops release returned items to the people still in the waiting room, which is a nice touch: a small second chance for those who just missed out.

Keep the hold window short. Ten minutes is common. Longer holds mean bots and indecisive buyers lock up stock that real buyers would pay for right now.

Step 9: The order pipeline

After the win
winnerreservationcheckoutexpireSERVICEBuy serviceQUEUEOrder queuedurableWORKEROrder workersSTOREOrders DBunique (sale, user)EDGEPayment providerSERVICEExpiry sweeper

Winners' reservations are written to the database asynchronously. The buy service puts a message on a durable queue: user, sale, reservation id, expiry. It returns to the user immediately: you got one, pay within ten minutes. Order workers drain the queue and write rows at a steady rate.

Ten thousand rows arrive at the queue in a few seconds. The workers write them at a few thousand per second, so the database never sees a spike. And the database's unique constraint means a duplicated message just fails harmlessly on insert, so the pipeline can retry freely.

Then the user goes to pay. The payment flow is the normal checkout, using the reservation id as an idempotency key, so a double click or a retried request cannot charge twice. When the payment provider confirms, the reservation becomes a paid order.

The expiry sweeper walks held reservations whose time has passed, marks them expired, and returns the stock. That closes the loop: every item is either sold, held for a few minutes, or available again.

Step 10: Bots and fairness

Keeping it fair
  1. 01
    Accountssign in required, account age, verified phone
  2. 02
    Limitone per account, one per payment card, one per address
  3. 03
    Challengea bot check when joining the waiting room
  4. 04
    Rate limitsper IP and per device at the edge
  5. 05
    Randomiseshuffle the first few seconds of arrivals
  6. 06
    Pre-registrationregister in advance, then a lottery

Here is the uncomfortable truth: in a popular flash sale, bots try to take everything. Scripts that click at the exact millisecond, from thousands of accounts, to resell at a profit. If we do nothing, real people lose to machines.

Raise the cost of each fake buyer. Require sign-in, and give more weight to older accounts with verified phone numbers. Limit one per account, and also per payment card and per delivery address, so a thousand accounts with one card still get one item.

Put a bot challenge at the waiting room door, not at the buy button, so it does not slow down the critical second. Rate-limit per IP and device at the edge. And randomising order among everyone in the first few seconds removes the advantage of millisecond-perfect scripts.

For the very hottest sales, many shops switch to pre-registration and a lottery. People register in the days before, the system draws winners, and winners get a time slot to buy. There is no stampede at all. Mention it as the strongest option, and say it is a product decision, because it changes the experience.

Step 11: One sale, second by second

Let us run the whole sale. At nine fifty-nine, a million users have the page open. They loaded it from the edge, so our servers did almost nothing. Each page polls the tiny stock state, also from the edge, once every few seconds.

At ten o'clock, buttons enable over a two-second spread. A million clicks hit the waiting room, which hands each a signed token and a position. In the first second, the admitter lets twenty thousand through. Those users call the buy service.

The buy service checks each token and user limit, then decrements the stock counter. In half a second, ten thousand decrements succeed and ten thousand fail. The winners' messages go onto the order queue, and they see: you got one, pay within ten minutes. The counter hits zero, and the sold out flag goes out to the edge.

Within a second or two, every edge location serves sold out. The nine hundred and eighty thousand people still in the waiting room see sold out, sorry. The whole decision took about three seconds. Order workers write ten thousand reservations over the next few seconds.

Over the next ten minutes, nine thousand five hundred winners pay. Five hundred do not. Their reservations expire, the stock counter goes back up to five hundred, and the waiting room admits the next people in line for a second round. When the last of those are paid or expired, the sale is over. The database saw about ten thousand inserts and ten thousand updates in total. That is the funnel working.

Step 12: Failures and testing

Failures
  1. 01
    Counter nodereplica takes over; database constraint is the backstop
  2. 02
    Order queue lagusers already told they won; rows land seconds later
  3. 03
    Payment outageextend hold windows; do not release stock
  4. 04
    Edge cache stalea few extra clicks reach the waiting room; harmless
  5. 05
    Load testrehearse with 2× expected traffic before the day

What can go wrong? The in-memory counter node fails mid-sale: a replica takes over, but it may be a few operations behind. That is why the database constraint exists. In the worst case a few buyers are told they won and then, seconds later, that it fell through. Rare, honest, and much better than overselling.

The order queue falls behind: that is fine, users have already been told the result, and the rows arrive a few seconds later. A payment provider outage: extend everyone's hold window rather than releasing stock, so winners are not punished for our provider's problem.

The most important practice is rehearsal. Flash sales are scheduled, so you know the date. Load test the whole path with twice the expected traffic, a week before. Pre-scale the services. Pre-warm the edge cache. Freeze deployments that day. Many flash sale failures are not design failures but missing rehearsals.

And monitor the right numbers live: waiting room size and admit rate, counter value, buy service latency, order queue depth, and the gap between counter sales and database rows. If that gap does not close within seconds, something is wrong, and someone should be looking at it during the sale.

Step 13: The follow-up questions

Now the follow-up questions interviewers like to ask.

Max asks

“Why not just lock the inventory row in the database?”

Row locks serialise every buyer on one row. At a million attempts, the lock queue becomes enormous, connections run out, and the database falls over for the whole shop. The in-memory atomic counter makes the same decision without holding locks, and the database only sees winners.

Max asks

“What if there are many different items on sale at once?”

Give each item its own counter, and shard counters across memory nodes by item id. The waiting room can still be one queue for the sale event, and admitted users then buy any item. Very hot items can be split into several counters as we discussed.

Max asks

“How do you stop the same user winning twice through two devices?”

The per-user key is set atomically before the decrement, so the second device finds it already set and is refused. The database's unique constraint on sale and user is the final backstop if the memory layer ever misses.

Max asks

“Could the stock counter go negative and stay wrong?”

It goes briefly negative when losers decrement, but each loser immediately adds one back. If a server crashes between the two, the counter is off by one. A reconciler compares the counter with the database every few seconds and corrects it. The database stays the source of truth.

Max asks

“How would you handle a sale with a hundred million users?”

The same funnel, with more edge capacity and a bigger waiting room. The core does not need to grow, because the admit rate and stock size, not the crowd size, set its load. That is the main point of the design: the crowd is absorbed at the edge.

Max asks

“How do you test this before the real sale?”

Run a full rehearsal with synthetic users against a staging copy, and then a small real sale, perhaps a hundred items, a week before. Watch the counter, queue depth and the database gap. Also run a game day: kill the counter node and a worker mid-sale and confirm nobody is oversold.

Max asks

“What does the user see when they lose?”

A fast, clear sold out page, ideally with something useful: join the waitlist for returned items, or get notified about the next sale. A quick honest answer keeps trust far better than a spinner that times out after a minute.

Max asks

“Where would you run the waiting room itself?”

As close to the edge as possible. The token is signed, so any edge server can issue and check one without asking a central service. Only the admit pointer is shared: one small number, the highest admitted position, published every hundred milliseconds and cached everywhere. That is how a million people can wait without a million connections to one server.

Recap

Recap
  1. 01
    Edgestatic page, tiny cached stock state
  2. 02
    Waiting roomadmit at a fixed rate
  3. 03
    Atomic counterdecrement in memory; database as backstop
  4. 04
    Reservationshold for minutes, expire back to stock
  5. 05
    Async ordersqueue, steady writes, idempotent
  6. 06
    Fairnesslimits, bot checks, maybe a lottery

Let us recap. A flash sale is a funnel. Serve the page and the stock state from the edge. Let a waiting room admit buyers at a rate the core can handle, and tell the rest sold out without ever touching a server.

Decide winners with an atomic in-memory decrement, with per-user limits, and keep a unique constraint and a stock check in the database as the final guarantee against overselling.

Give winners a short reservation, write orders asynchronously, take payment with an idempotency key, return expired holds to stock, and keep bots out with limits, challenges and, for the hottest sales, a lottery.

The insight to say out loud is the ratio: ninety-nine percent of buyers lose, so the whole design is about telling them cheaply. Practice saying that, and drawing the funnel, with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson twenty-one.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.