Video in progress
In a flash sale, 200 thousand people want to order 1000 units of a product within a minute. How do you build the system so you don't oversell or take down the database?
Decrementing stock with an UPDATE on a single DB row turns into a lock queue under this load. You count stock atomically in Redis (DECR or Lua), write the successful reservations to the DB through a queue, and reject the excess requests as early as possible — at the edge and the gateway.
📖 Answer
The simple solution is UPDATE stock SET qty = qty - 1 WHERE product_id = ? AND qty > 0. It's correct and doesn't oversell. But 200 thousand transactions line up for the same row lock: latency goes to seconds, the connection pool runs out, and the entire store (other products too) stops.
I approach it in layers:
-
Cut traffic early. Before the sale starts, the page is static and on the CDN. Against bots and repeated clicks, a per-user rate limit, and sometimes a queue page ("you're number 15,230 in line") — it lets requests in at an even rate.
-
Stock in Redis.
-- KEYS[1] = stock:sku, KEYS[2] = buyers:sku, ARGV[1] = userId
if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then return -1 end -- one per person
local left = redis.call('DECR', KEYS[1])
if left < 0 then
redis.call('INCR', KEYS[1])
return 0 -- sold out
end
redis.call('SADD', KEYS[2], ARGV[1])
return 1
Redis, in a single thread, performs more than 100 thousand such operations per second. Once stock runs out, the key is 0 and the remaining requests get a "sold out" answer in a millisecond. Even better: the sold-out flag is spread to the local cache and the CDN too, so requests don't even reach Redis.
-
Write the order asynchronously. If the reservation succeeds, a
ReservationCreatedevent goes to Kafka, and the user gets "reserved, pay within 10 minutes". Consumers write to the DB at their own pace — 1000 orders are easy for the database. -
Releasing the reservation. An unpaid reservation is cancelled after 10 minutes and the unit is returned to Redis (
INCR) — this return must be idempotent too, otherwise a unit returned twice leads to overselling.
Risks. Redis isn't the source of truth, but here it temporarily acts as one. During a Redis failover, asynchronous replication can lose a few DECRs — which results in one or two extra reservations. So a final check stays when writing to the DB (the qty > 0 condition), and the small number of extras is covered with "sorry, sold out" plus compensation. Agree on this with the business in advance. And run a load test before the sale — at at least 2 times the real volume.
Sign up to mark studied questions and save your progress.