Design a Flash Sale System: No Overselling Under Extreme Load
How to sell 100 items to millions of simultaneous buyers: atomic stock decrement, waiting rooms, queues, reservations with expiry and idempotent orders.
A flash sale offers a small quantity of a product at a fixed time, for example 100 phones at noon, to a very large number of buyers. Within a second the stock is gone. The system faces two problems together: an extreme traffic spike, and the need to never sell more items than exist.
Reading the stock from the database, checking that it is greater than zero and then creating the order is the obvious implementation, and it is the one that produces 120 orders for 100 phones. These notes explain why, and how the correct design works.
1. Requirements
- Functional: a limited stock is sold starting at a fixed time; each user may buy at most one unit.
- Functional: a successful buyer places an order and pays within a time limit.
- Non-functional: no overselling, under any level of concurrency. This is the hard correctness requirement.
- Non-functional: the system stays available during the spike, and the rest of the site is not affected by it.
- Non-functional: fairness. Earlier requests should generally win, and bots should not take the stock.
2. Scale estimation
Assume 5 million users are waiting when the sale opens and most of them press Buy in the first few seconds. That is on the order of a million requests per second, for 100 units of stock. More than 99.99 percent of requests must fail, and they should fail as early and as cheaply as possible. The design is essentially a funnel: each layer rejects most of the traffic so that only a few hundred requests ever reach the order service and the database.
3. The race condition
The naive flow has three separate steps: read the stock, check that it is positive, write the decremented value. Suppose one unit remains. Two requests read the stock at the same time and both see 1. Both pass the check. Both write 0 and both create an order. Two phones have been sold and only one exists.
This is a race condition: the result depends on the timing of concurrent operations. With thousands of concurrent requests the overselling is not an edge case, it happens on every sale.
-- Request A and request B run these statements at the same time SELECT stock FROM items WHERE id = 7; -- both read: 1 -- application: if (stock > 0) ... -- both pass UPDATE items SET stock = 0 WHERE id = 7; -- both write INSERT INTO orders (...) VALUES (...); -- two orders, one phone
4. Atomic decrement
The fix is to make read, check and write a single indivisible operation. In a relational database this can be done with a conditional update: decrement the stock only where the stock is still positive, and treat 'zero rows affected' as sold out. The database guarantees that two such updates cannot both take the last unit.
At flash-sale traffic levels even this is too much load for the database, so the stock counter is moved to Redis before the sale begins. Redis executes commands one at a time, which makes each command atomic. The DECR command decrements and returns the new value in one step. If the result is zero or more, the request has won a unit. If it is negative, the stock is exhausted and the request is rejected. A short Lua script can combine the stock check, the per-user purchase check and the decrement into one atomic unit.
-- SQL: conditional update, check affected rows
UPDATE items SET stock = stock - 1 WHERE id = 7 AND stock > 0;
-- 1 row affected -> success 0 rows affected -> sold out
-- Redis Lua script: one user, one unit, no overselling
-- KEYS[1] = stock:7 KEYS[2] = buyers:7 ARGV[1] = userId
if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then
return -1 -- this user already bought
end
local stock = tonumber(redis.call('GET', KEYS[1]))
if stock <= 0 then
return 0 -- sold out
end
redis.call('DECR', KEYS[1])
redis.call('SADD', KEYS[2], ARGV[1])
return 1 -- reserved5. Protecting the system from the spike
Correct stock handling is not sufficient if the services collapse under a million requests per second. The traffic is reduced in layers before it reaches anything expensive.
- Static content from a CDN: the sale page, images and scripts are served from the edge. The countdown uses server time so that clients cannot start early.
- Virtual waiting room: users are placed in a queue and admitted in controlled batches. Only admitted users receive a token that allows them to call the buy endpoint.
- Rate limiting and bot protection at the gateway: per-user and per-IP limits, and a challenge for suspicious clients.
- Fast rejection: once stock reaches zero, a flag is set and the gateway answers 'sold out' immediately without calling any service.
- Order queue: the few requests that win a unit are written to a queue, and order workers create orders in the database at a rate it can sustain.
5,000,000 users
|
v
CDN (static sale page) <- absorbs page loads
|
Waiting room + API gateway (rate limit, bots) <- admits a small, steady flow
|
Sale service --> Redis: atomic stock decrement <- 100 succeed, the rest get "sold out"
|
Order queue (Kafka / SQS) <- buffer
|
Order workers --> Orders DB (SQL) --> Payment service
|
Reservation expiry job (returns unpaid stock)6. Reservations with expiry
Decrementing the stock reserves a unit for the user; it is not yet a sale. If the user never completes the payment, that unit would be locked forever. Each reservation therefore has an expiry time, for example ten minutes. If payment succeeds within that time, the order is confirmed. If not, the reservation is cancelled and the unit is returned to stock so that someone else can buy it.
Expiry can be implemented with a delayed message that fires after ten minutes and checks the order status, or with a periodic job that scans for unpaid orders past their deadline. The order is a small state machine: RESERVED, then PAID or EXPIRED.
7. Idempotency
On a slow network a user may press Buy twice, or the app may automatically retry a request that timed out. Without protection this could create two orders or consume two units. Each purchase attempt carries an idempotency key, a unique identifier generated by the client. The server stores the key with the result of the first request. When the same key arrives again, the server returns the stored result instead of processing the request a second time. The per-user set in the Lua script gives a second layer of protection for the one-unit-per-user rule.
8. Failure cases
- Redis failure during the sale: run Redis with replication and persistence, and treat the database as the source of truth. On recovery, recompute remaining stock as initial stock minus confirmed and active reservations. It is safer to pause the sale briefly than to risk overselling.
- Worker failure: the order message remains in the queue and is processed again; the idempotency key prevents a duplicate order.
- Payment timeout: do not assume failure. Check the payment status before releasing the reservation.
- Isolation: run the sale on separate service instances and a separate Redis so that the spike cannot bring down normal shopping.
Interview summary
- Requirements: no overselling, survive the spike, one unit per user.
- Stock: atomic decrement in Redis (or a conditional UPDATE), never check-then-act.
- Traffic: CDN, waiting room, rate limiting, then a queue in front of the order service.
- Reservation with a TTL: unpaid stock returns to the pool.
- Idempotency keys so that retries and double clicks create one order.
Summary
Overselling is caused by separating the stock check from the stock update, and it is prevented by making them one atomic operation. Everything else in a flash sale design is a funnel that rejects excess traffic early: CDN, waiting room, rate limits and a queue. Reservations expire so that unpaid stock is released, and idempotency keys make retries safe.
Puneet Tiwari
Full Stack Developer
