Scrivio Interview library
CodingIntermediate7 min read · updated 13 November 2026

A flash sale decrements stock in Redis and creates orders asynchronously. It showed sold out after 40 seconds, yet afterwards 230 of the 10,000 units were unsold: some winners never paid, some orders failed, and some users had won twice from two browser tabs.

Design the stock deduction step as one atomic Redis operation that also enforces one unit per user, and explain how unpaid and failed orders return their units without overselling.

One Lua script does the whole decision atomically: return already-won if the user is in the winners set, sold-out if stock is zero, otherwise DECR the stock, SADD the user and XADD the order request to a stream. Keys share a hash tag such as {sale:42} so they live in one Redis Cluster slot. Unpaid or failed orders are cancelled after a payment deadline and their unit returned by a second script that INCRs stock only if that reservation has not already been released, while a unique (sale_id, user_id) constraint in the database stays the final guard.

Why this question is asked

This sale did the hard part right: it never oversold. But it sold out on paper and then left 230 units on the shelf, and some people won twice. Each of those problems is about atomicity, either a check and a change that were not done together, or a return of stock that could run twice. Interviewers ask it to see whether we can write a correct Redis script and think about the lifecycle of a unit after the first decision. In this answer, we will find the three causes, see why separate Redis commands are not enough, write the attempt script, place keys correctly for Redis Cluster, return units exactly once, and finish with how the page and the database handle returned stock.

1Where the 230 Units Went

The counter reached zero after 40 seconds, so 10,000 units were assigned. Afterwards 230 were unsold, which means 230 assignments never became paid orders. There were three causes. Some winners never paid, and nothing returned their unit. Some orders failed in the asynchronous order workers, for example a payment validation error, and again the unit was never returned. And some users won twice, from two browser tabs, which used two units for one person; when the second order was cancelled as a duplicate, that unit was lost too.

So we need two things: a decision step that enforces one unit per user atomically, and a return path that gives units back exactly once when an order does not complete.

2Why Separate Commands Race

The old code checked membership and stock with separate commands from Java. Two tabs of the same user can interleave like this.

Java
// tab 1 // tab 2
SISMEMBER {sale:42}:winners u7 -> 0
SISMEMBER {sale:42}:winners u7 -> 0
DECR {sale:42}:stock -> 4120
DECR {sale:42}:stock -> 4119
SADD {sale:42}:winners u7 -> 1
SADD {sale:42}:winners u7 -> 0
// user u7 now holds two units

Each command is atomic on its own, but the sequence is not. Between tab 1's check and its write, tab 2 ran its own check and saw the same old state. This is the same check-then-act race we meet in databases, and the fix is the same: make the check and the change one indivisible step.

3One Script That Decides Everything

Redis runs a Lua script as a single unit: while it runs, no other client's command executes. So everything inside sees and changes a consistent state. We pass the keys explicitly in KEYS, as Redis requires, and the user and sale in ARGV.

SQL
-- KEYS[1] {sale:42}:stock KEYS[2] {sale:42}:winners KEYS[3] {sale:42}:orders (stream)
-- ARGV[1] user id ARGV[2] attempt id
if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then
return 'ALREADY_WON' -- second tab: no second unit
end
local left = tonumber(redis.call('GET', KEYS[1]) or '0')
if left <= 0 then
return 'SOLD_OUT'
end
redis.call('DECR', KEYS[1])
redis.call('SADD', KEYS[2], ARGV[1])
redis.call('XADD', KEYS[3], '*', 'user', ARGV[1], 'attempt', ARGV[2])
return 'OK'
-- tab 1: OK tab 2: ALREADY_WON

Notice that the order request is appended to the stream inside the same script. If the script returns OK, the unit, the winner mark and the order request all exist together; there is no moment where a unit was taken but no order was queued. We can send it with EVALSHA after loading it once, or, on Redis 7 and later, register it as a Redis function with FUNCTION LOAD and call it with FCALL, which keeps the code on the server across restarts.

4Hash Tags for Redis Cluster

In Redis Cluster, keys are spread across 16,384 hash slots on different nodes, and a script may only touch keys in one slot; otherwise Redis rejects it with a CROSSSLOT error. The slot is computed from the key name, but if the name contains a part in braces, only that part is hashed. So {sale:42}:stock, {sale:42}:winners and {sale:42}:orders all hash on sale:42 and land together.

The cost is that one sale lives on one node. That is fine here, because a single node handles well over 100,000 script calls per second, and different sales naturally spread across the cluster.

5Returning Units Exactly Once

Each winner gets a payment deadline, for example 10 minutes. An expiry job finds orders that are still unpaid after the deadline, or that failed, and cancels them in the database with a conditional update, so a payment that arrives at the same moment cannot also succeed. Only after that update succeeds does it return the unit to Redis.

The return must be safe to run twice, because the job may crash after returning the unit but before recording it, and run again. So we record the reservation as released in the same script that increments the stock.

Java
-- KEYS[1] {sale:42}:stock KEYS[2] {sale:42}:released (hash) ARGV[1] reservation id
if redis.call('HSETNX', KEYS[2], ARGV[1], 1) == 1 then
redis.call('INCR', KEYS[1])
return 1 -- unit returned
end
return 0 -- already returned earlier: do nothing
-- first run: 1 (stock 0 -> 1) retry after a crash: 0 (stock stays 1)
Step throughLifecycle of a won unit
  1. Script returns OKstock -1, winner marked, order queued
  2. Order created and paid within 10 minutes?order worker and checkout
    YesSold, doneNoCancel the order in the database
  3. Release script for the reservationHSETNX guards a double return
  4. Unit back in stockpage flips to available or waitlist is offered

4 steps in order. Play them, or step through them one at a time.

6Returned Units and the Final Guard

Returned units must reach buyers, or we have only moved the 230 units from 'lost' to 'sitting in Redis'. Either the page flips from sold out back to available, which means the sold-out state must come from the counter rather than being a permanent flag on the page, or returned units go to a waitlist in arrival order, or the business explicitly accepts selling the remainder later at normal price. Any of these is fine; what matters is that someone chooses.

Finally, Redis is the fast gate, not the record of truth. The database keeps a unique constraint on (sale_id, user_id), so even a bug in the script cannot create two orders for one person, and after the sale a reconciliation job compares the Redis winners set with orders and flags any user or unit that appears in one but not the other.

7Follow-up questions

Could we use MULTI and EXEC instead of a script?

MULTI and EXEC run queued commands together, but the commands cannot depend on each other's results: we cannot say 'DECR only if SISMEMBER returned 0' inside a transaction. WATCH with optimistic retries can express it, but under heavy contention most transactions abort and retry. A script expresses the condition directly and never retries.

Is a Lua script slow because it blocks Redis?

This script runs a handful of O(1) commands and finishes in microseconds, so blocking is negligible. Scripts become a problem only when they loop over large collections; we keep flash-sale scripts short and constant time.

Should a user who did not pay be allowed to try again?

That is a business rule. In our release script the user stays in the winners set, so they cannot win again in this sale, which discourages people from grabbing units they do not mean to buy. If the business prefers a second chance, the release script also removes the user from the winners set.

8Conclusion

In this answer, we traced the 230 unsold units to unpaid winners, failed orders and double wins from two tabs. We replaced separate commands with one Lua script that checks the winners set, checks stock, decrements, marks the winner and queues the order atomically, with hash tags so all keys share a Redis Cluster slot. Unpaid and failed orders are cancelled in the database first and returned by an idempotent script guarded by HSETNX, the page can flip back to available or offer a waitlist, and a unique constraint plus reconciliation keep the database as the record of truth.

What to say in the interviewAbout 100 seconds aloud

Open with

The unsold units came from three gaps: winners who never paid, orders that failed after winning, and users who won twice from two tabs because the check and the decrement were separate commands.

Then, if they want more

I would make the decision a single Lua script, or a Redis function on Redis 7: if SISMEMBER on the winners set says the user already won, return already-won; if the stock is zero or less, return sold-out; otherwise DECR the stock, SADD the user and XADD the order request to a stream, and return ok.

Redis runs the script without interleaving other commands, so two tabs cannot both pass the check. In Redis Cluster all the keys have to be in one slot, so I name them with a hash tag like {sale:42}:stock and {sale:42}:winners. Then each winner gets a payment deadline, say ten minutes.

An expiry job cancels unpaid or failed orders in the database with a conditional update and then returns the unit with a second script that does HSETNX on a released hash for that reservation and INCRs stock only if the HSETNX succeeded, so a retry never returns a unit twice.

Returned units have to reach buyers, so the page must be able to go back from sold out to available, or we use a waitlist. And the database keeps a unique constraint on sale and user as the final guard, with reconciliation of Redis winners against orders after the sale.

About this answer

Last updated
13 November 2026
Versions it names
Redis 7
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design the stock deduction step as one atomic Redis operation that also enforces one...": https://scrivio-interview-library.netlify.app/architecture/system-design-problems/7785dfccc0/