Design flash-sale inventory
Sell a small, fixed stock to a huge simultaneous crowd without overselling, by admitting buyers at a controlled rate, gating stock in Redis and keeping the database as the final authority.
The problem
A retailer announces 10,000 games consoles at half price, on sale at noon. By 11:59 two million people have the page open. At noon they all tap Buy.
The shop’s normal checkout does what most checkouts do: read the stock, check it is above zero, write back the stock minus one, create the order. Three things go wrong in the first second.
First, oversell. Hundreds of requests read “1 left” before any of them writes, and all of them succeed. The shop sells 10,400 consoles and has to cancel 400 orders. Second, collapse. Every request holds a database connection while it waits on the same row. The pool empties, and customers buying socks elsewhere on the site get errors too. Third, bots. Scripts that fire at exactly 12:00:00.000 take most of the stock before a person can move a finger.
Almost all of the load is from people who cannot possibly succeed. The design is mostly about telling them so cheaply.
Requirements
Functional
- The sale opens at a fixed time with a fixed stock per item.
- One unit per customer.
- A successful buyer gets a reservation and 10 minutes to pay. Unpaid reservations return to stock.
- Buyers who cannot be served are told quickly: wait, or sold out.
- Ordering among buyers is reasonably fair.
Out of scope unless asked: the catalogue, recommendations, delivery, and the details of taking the payment.
Non-functional
- No oversell, ever. Confirmed orders never exceed stock. Underselling briefly, while holds expire or counters are reconciled, is acceptable.
- Burst capacity: 2 million concurrent buyers and several hundred thousand requests a second at the start.
- Fast answers: a buyer learns “reserved”, “queued” or “sold out” in well under a second.
- Isolation: the rest of the shop keeps working throughout.
- Abuse resistance: scripts gain as little advantage as possible.
Capacity estimates
| Quantity | Working | Result |
|---|---|---|
| Buyers at the start | given | 2 million |
| Buy attempts | 2M taps spread over 10 seconds | 200,000 per second, more in the first second |
| Chance of success | 10,000 units / 2M buyers | 0.5%, so 199 in 200 fail |
| Reservations written | one per unit, plus re-released holds | a little over 10,000 in total |
| Admission rate | chosen to suit the database | 1,000 buyers per second, sold out in about 10 seconds |
| Normal site traffic | assumed | 5,000 requests per second |
The sale brings 40 times the site’s normal traffic, and 99.5% of it is destined to fail. Meanwhile the real work, about 10,000 reservation writes, is tiny. So the system is a funnel: each layer must discard as much as it can as cheaply as it can, and the transactional core only ever sees roughly as many requests as there are units.
API
POST /v1/sales/{sale_id}/queue → { "ticket": 184223, "signature": "..." }
GET /v1/sales/{sale_id}/queue/status → { "now_serving": 120000, "sold_out": false }
POST /v1/sales/{sale_id}/admission → { "admission_token": "..." }
POST /v1/sales/{sale_id}/reservations
Admission-Token: eyJ...
Idempotency-Key: 3f9a...
{ "sku": "console-black" }
201 Created { "reservation_id": "res_91", "expires_at": "2026-11-27T12:10:04Z" }
409 Conflict { "error": "sold_out" }
POST /v1/reservations/{reservation_id}/checkout
The queue status is the same for every caller, so the CDN can cache it for a second and two million polling clients cost the origin one request a second. The admission token is signed, short-lived and bound to the user, so the gateway can verify it without a lookup.
Data model
In the database, which is the system of record:
| Table | Columns | Notes |
|---|---|---|
sale_stock |
sale_id, sku, total, remaining |
one row per item on sale |
reservations |
reservation_id, sale_id, user_id, sku, status, expires_at |
unique on (sale_id, user_id) |
A reservation’s status is HELD, PAID or EXPIRED. The unique constraint enforces one unit per customer even if every other check fails.
In a Redis instance used only for the sale:
{sale42}:stock:console-black integer, units not yet claimed
{sale42}:buyers set of user ids who have claimed one
sale42:ticket, sale42:serving queue counters for the waiting room
The braces are a Redis Cluster hash tag. They force the stock and buyers keys into the same slot, which a script that touches both requires.
High-level architecture
Before the sale. The sale page and its countdown are static files on the CDN. Nothing reaches the origin.
Joining. At noon each client asks the waiting room for a ticket number, then polls the cached status. A counter called “now serving” advances at the admission rate. When it passes a client’s ticket, the client exchanges the ticket for an admission token.
Reserving. With a token, the client calls the sale service. The gateway checks the token and per-user rate limits. The sale service runs one Redis script that checks the buyer has not already claimed a unit, checks stock and decrements it. On success it puts a reservation message on a queue and replies. Workers consume the queue at a pace the database likes, and write the reservation with a conditional decrement of remaining.
Paying and expiring. The buyer checks out through the payment service, and the sale service marks the reservation PAID. A sweeper finds holds past their expiry, marks them EXPIRED and returns the units to the database and to Redis.
Deep dives
Preventing oversell
The bug in the naive code is the gap between the check and the write. The fix, at every layer, is to make them one atomic step.
Step 1 of 8
One console is left in stock. Two buyers tap Buy in the same millisecond, and their requests are handled by two threads of the sale service.
Read the steps as text
- One console is left in stock. Two buyers tap Buy in the same millisecond, and their requests are handled by two threads of the sale service.
- The naive code reads the stock, checks it in the application, then writes it back. Both requests read the row before either has written, so both see one unit available.
- Both requests write a stock of zero, and both buyers get a confirmation. Two consoles are sold and only one exists. This is an oversell.
- The first fix makes the check and the write a single statement. Reduce stock by one, only where stock is above zero. Starting again from one unit, buyer A's update changes one row.
- Buyer B's update waits for the row lock, checks the condition again against the new value and changes no rows. The service sees zero rows affected and tells B the item is sold out.
- That is correct, but in a flash sale two hundred thousand requests a second would queue on that one row lock. The database runs out of connections and the rest of the shop goes down with it.
- So a Redis counter stands in front. A short script checks the counter and decrements it as one atomic step in memory. Buyer A gets a yes and buyer B gets a no, without touching the database.
- Only winners continue to the database, which still runs its conditional update as the final authority. Redis turns the crowd away cheaply. The database guarantees the count is right.
In the database, a conditional update does it:
UPDATE sale_stock SET remaining = remaining - 1
WHERE sale_id = 42 AND sku = 'console-black' AND remaining > 0;
If one row was affected, the buyer has a unit. If none, it is sold out. At the default isolation levels of PostgreSQL and MySQL, a second transaction updating the same row waits for the first, then re-checks the condition against the new value. This is always correct. An optimistic version column is also correct, but on a row this contended nearly every attempt would fail and retry.
The weakness is throughput. Every buyer queues on one row lock, each holding a connection. That is fine for 1,000 requests a second and hopeless for 200,000.
In Redis, a Lua script is the fast gate. Redis runs a script as a single atomic unit, with no other command interleaved:
-- KEYS[1] = stock counter, KEYS[2] = buyers set, ARGV[1] = user id
if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then return -1 end
local stock = tonumber(redis.call('GET', KEYS[1]) or '0')
if stock <= 0 then return 0 end
redis.call('DECR', KEYS[1])
redis.call('SADD', KEYS[2], ARGV[1])
return 1
A single Redis node runs on the order of 100,000 simple commands a second, and with admission control it sees far fewer.
Redis is not the system of record. Its replication is asynchronous, so a failover can lose recent decrements, and its counter can then be too high. That is why the worker repeats the check with the conditional update in the database. Redis keeps the crowd away from the database. The database guarantees the count.
Reservations with expiry. A successful decrement creates a HELD reservation that expires in 10 minutes. Payment success runs UPDATE reservations SET status = 'PAID' WHERE reservation_id = ? AND status = 'HELD'. The sweeper runs the same shape of statement to set EXPIRED, and in the same transaction adds one back to remaining. Only one of the two can match, so a unit is never both sold and released. If the sweeper wins against a payment that then succeeds, the payment is refunded. Find expired holds with an indexed query on expires_at or a delayed queue. Do not rely on Redis key-expiry notifications, which are best-effort.
Admission control and the waiting room
The gate stops oversell. Admission control stops the crowd reaching the gate all at once.
A waiting room needs very little state: a ticket counter and a “now serving” counter. Joining is one increment. The status response is identical for everyone, so it is served from the CDN. A scheduler raises “now serving” by the admission rate each second, which is a form of backpressure set by what the database and payment service can take. When admitted buyers exceed stock by a margin (some will not complete), admission stops and everyone else sees “sold out, you may still get in if a hold expires”.
Fairness needs one more decision. If tickets are strictly first come, first served from the opening instant, the fastest script wins. Commercial waiting rooms often give everyone who arrived before the start a random place in the queue, and only later arrivals join in order behind them. That removes the reward for hammering the server at the opening second.
Once the script returns 0, each sale server sets a local sold-out flag in memory for a second or so and answers from it without calling Redis. After sell-out, the remaining crowd costs almost nothing.
Hot keys, bots and the rest of the site
The stock counter is one key, and a cluster cannot spread one key over several nodes. So isolate it: the sale gets its own Redis, its own service fleet, its own queue and its own database connection pool, or its own database. These are bulkheads. If the sale’s Redis saturates, only the sale suffers. Shared dependencies such as login get strict quotas, and buyers are asked to sign in before the sale opens. Capacity is provisioned in advance, because autoscaling takes minutes to react and the spike arrives within a second.
For a sale of millions of units, one counter may not be enough even with admission control. Split the stock into buckets on different nodes, route each buyer to a bucket by hashing their id, and let a buyer whose bucket is empty try another.
Bots cannot be eliminated, only made expensive. Require an account with some history, limit by account, device and payment card, apply rate limits and a challenge at queue entry, and issue the reservation URL’s token only through the waiting room so scripts cannot skip it. Afterwards, review orders for clusters sharing an address or card before shipping.
Bottlenecks and failure modes
- Redis failover mid-sale. The promoted replica may have a counter that is too high. The database’s conditional update refuses the excess, and those buyers are told it is sold out. A stricter option is to pause admission, rebuild the counter from the database and resume.
- Crash between the Redis decrement and the queue. A unit is claimed in Redis with no reservation. This undersells. After the rush, compare
remainingin the database with the Redis counter and return the difference. - A message is delivered twice. The reservation id and the unique constraint on
(sale_id, user_id)make the worker’s insert idempotent. - Payment is slower than the hold. The conditional transitions decide the winner, and a payment that arrives too late is refunded automatically.
- The sweeper stops. Abandoned holds are not released, so stock looks sold when it is not. Annoying, and safe.
- Retry storms. Clients that receive
429or503and retry at once double the load. SendRetry-After, and have clients back off with jitter. - Clock differences. The sale opens on server time. The countdown uses a server timestamp, not the device clock.
Trade-offs
| Decision | Chosen | Alternative | Why |
|---|---|---|---|
| Stock gate | Redis script, then database check | Database conditional update alone | Keeps the crowd off the hot row; two counters to reconcile |
| Burst handling | Waiting room with admission tokens | Let everyone call buy and reject | Back end sees a steady rate; buyers wait in a queue |
| Queue order | Random for early arrivals, then in order | Strict first come, first served | Blunts scripts; arriving early earns nothing |
| Stock holds | Reserve for 10 minutes | Decrement on payment | Admitted buyers can finish; abandoned units sit idle |
| Failure bias | Undersell, then reconcile | Exact counts across both stores | Never cancels an order; a few units sell late |
45-minute interview script
A pacing guide. Interviewers differ, so treat the timings as a default and follow their lead.
- 0:00 to 5:00
Requirements 5 min
Confirm stock size, crowd size, the per-customer limit and how long a buyer has to pay. Say plainly that overselling is forbidden, underselling for a few minutes is tolerable and the rest of the shop must stay up.
- 5:00 to 9:00
Capacity estimates 4 min
Derive buy attempts per second at the start and the ratio of buyers to stock. Say the conclusion, which is that the system is a funnel that must reject more than 99% of requests cheaply.
- 9:00 to 12:00
API 3 min
Join the queue, poll a cacheable status, exchange a ticket for an admission token, create a reservation with an idempotency key, check out.
- 12:00 to 16:00
Data model 4 min
The stock row and the reservations table in the database, with their unique constraint, and the two Redis keys. Say which one is the system of record.
- 16:00 to 24:00
High-level design 8 min
Draw the funnel from left to right. CDN, gateway, waiting room, sale service, Redis, queue, workers, database. Narrate one winning buyer and one who is told sold out.
- 24:00 to 32:00
Deep dive: preventing oversell 8 min
The read-then-write race, the conditional update, why one hot row cannot take the crowd, the Lua script in Redis, and why the database still checks. Then reservations with expiry.
- 32:00 to 39:00
Deep dive: admission control and isolation 7 min
The waiting room with ticket numbers and signed tokens, random order for early arrivals, the local sold-out flag, dedicated infrastructure for the sale, and bots.
- 39:00 to 43:00
Failure modes and trade-offs 4 min
Redis failover mid-sale, a crash between the Redis decrement and the queue, payment slower than the hold, the sweeper stopping. Point out that each one fails towards underselling.
- 43:00 to 45:00
Wrap-up 2 min
Summarise in three sentences and name what you would add next, such as a lottery model or splitting stock across shards for much larger sales.
Key takeaways
- A flash sale is a funnel. With 2 million buyers and 10,000 units, 199 requests in every 200 must be refused or parked before they reach anything expensive.
- Reading stock and then writing it is a race. Make the check and the decrement one atomic operation.
- A conditional update (set stock to stock minus one where stock is above zero) is always correct, but a single hot row cannot absorb the crowd on its own.
- A Redis Lua script is a fast atomic gate, not the system of record. The database repeats the check and has the final say.
- Reservations hold stock for a few minutes and expire, and every failure should lean towards underselling, which can be repaired, not overselling, which cannot.
- Run the sale on its own fleet, Redis and connection pools so that its failure does not become the whole shop's failure.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What is the simplest correct way to decrement stock in SQL?
One conditional statement, UPDATE ... SET remaining = remaining - 1 WHERE sku = ? AND remaining > 0, then check that one row was affected. Zero rows means sold out.
Why put Redis in front of the database for a flash sale?
A single stock row serialises every buyer on one lock and holds database connections. A Redis script answers yes or no in memory, so only about as many requests as there is stock ever reach the database.
What is a virtual waiting room?
A cheap holding page in front of the sale. Each visitor gets a place in a queue and is admitted at a rate the back end can handle, with a signed token proving admission.
Why reserve stock with an expiry instead of decrementing at payment?
A hold guarantees an admitted buyer can finish paying without losing the item to someone faster. The expiry returns stock from buyers who abandon checkout.
What is hot-key isolation?
Keeping the one key everybody hits (the sale's stock counter) on dedicated infrastructure, and answering from a local sold-out flag once stock is gone, so its load cannot hurt unrelated data.
Oversell or undersell: which way should failures lean?
Undersell. Stock that is wrongly held can be released later by reconciliation. A unit sold twice means cancelling a customer's order.