Quick revision
The short answer
The first step is to shorten the time each transaction holds the lock, with one atomic conditional update: update stock set qty = qty - 1 where id = ? and qty > 0. If that is still not enough, I would split the stock into several counter rows and pick one at random, reserve stock in a fast store such as Redis with atomic operations and reconcile with the database, or queue purchase requests and process them in order with clear feedback to the user. Which one fits depends on how much oversell and delay the business accepts, which must be agreed up front.
What to remember
In this answer, we saw that a flash sale turns one stock row into a queue whose throughput is the inverse of lock hold time. An atomic conditional update with the slow work moved outside the lock is the first and cheapest fix. Bucketed counters spread the lock across rows, Redis reservations with reconciliation raise throughput much further, and a queue per product removes contention entirely, each with more complexity, and all governed by oversell and compensation rules agreed with the business.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The first step is to shorten the time each transaction holds the lock, with one atomic conditional update: update stock set qty = qty - 1 where id = ? and qty > 0. If that is still not enough, I would split the stock into several counter rows and pick one at random, reserve stock in a fast store such as Redis with atomic operations and reconcile with the database, or queue purchase requests and process them in order with clear feedback to the user. Which one fits depends on how much oversell and delay the business accepts, which must be agreed up front.
Why this question is asked
A flash sale concentrates thousands of buyers on a single row in the database for a few minutes. Normal designs break because every purchase must update the same stock counter, and row locks make them run one at a time. Interviewers ask this scenario to see whether we can reason about lock hold time, contention and business trade-offs rather than just adding hardware. In this answer, we will see why latency explodes, then go through the options from the simplest to the most involved, with what each costs.
1Why One Row Becomes a Bottleneck
Every purchase decrements the same stock row. The first transaction to update it holds a row lock until it commits; every other transaction that wants to update it waits in a queue. Throughput is therefore one divided by the lock hold time. If a typical purchase transaction reads the product, checks stock, inserts an order, calls a payment provider and then commits, the lock may be held for 200 milliseconds, which allows only 5 purchases per second. With 5,000 buyers arriving in the first minute, the queue grows by thousands, connections run out, and latency explodes for the whole shop, not just this product.
| Lock held per purchase | Max purchases per second | Typical cause |
|---|---|---|
| 200 ms | 5 | Remote call inside the transaction |
| 20 ms | 50 | Read, check, update, insert, commit |
| 2 ms | 500 | Single atomic update, then commit |
| Spread over 10 rows at 2 ms | About 5,000 | Bucketed counters |
2Option 1: An Atomic Conditional Update
The cheapest fix is to make the critical section one statement. Instead of reading the stock, checking it in Java and writing it back, we let the database do all three at once.
The condition qty > 0 makes overselling impossible: when stock reaches zero, the update matches no row and returns 0. The key is to commit this tiny transaction straight away, and do everything slow, the payment call above all, afterwards. If payment fails, a compensating update gives the unit back. This alone often raises throughput by a factor of 50 or 100, and it should always be the first step.
3Option 2: Split the Counter Into Buckets
If one row is still too hot, we spread the stock across several rows. For 1,000 units we create 10 bucket rows of 100 each. Each purchase picks a bucket at random and decrements it with the same conditional update. Ten rows mean ten independent locks, so up to ten purchases can proceed at once.
The cost is complexity. When buckets run low, some are empty while others still have stock, so a purchase must try other buckets before saying sold out. Showing the remaining count means summing all buckets. It is a good fit when database consistency is required and throughput needs to go up about ten times.
4Option 3: Reserve in a Fast Store and Reconcile
For much higher rates, we move the counter to memory. Redis executes each command atomically on a single thread, so DECR on a stock key is safe without locks and takes microseconds. A small Lua script or a check of the returned value refuses when stock would go below zero. The purchase is accepted in Redis, and the order is written to the database afterwards, asynchronously or in a short transaction.
The cost is that we now have two sources of truth. If Redis loses data in a failover, or an order write fails after the Redis decrement, the counts drift. So we reconcile: a job compares sold units in the database with the Redis counter and corrects it, and the business accepts that in rare failure cases a few units may be oversold or held back and fixed afterwards.
5Option 4: Queue the Requests
Another approach is to stop competing for the row. Purchase requests go into a queue, such as a Kafka topic partitioned by product, and a single consumer per product processes them in order, decrementing stock with no contention at all. The user sees you are in line, then a confirmation or a sold-out message a few seconds later. This gives fairness, first come first served, and protects the database completely, at the price of an asynchronous user experience and more moving parts.
- Is a single atomic update fast enough?YesUse it and stop thereNoContinue
- Must stock stay exactly right in the database?YesSplit into bucket rowsNoContinue
- Can users wait a few seconds for confirmation?YesQueue requests per productNoReserve in Redis and reconcile
- Agree oversell and compensation rulesWith the business, before the sale
4 steps in order. Play them, or step through them one at a time.
Each step down buys throughput with more complexity.
6Decide the Rules With the Business
Every option above has an edge case, so the technical choice depends on rules only the business can set. May we oversell by a few units and apologise with a voucher, or never? How long may a reserved unit wait for payment before it is released? Is first come, first served required, or is any fair outcome acceptable? We agree these before the sale, load test the chosen design with realistic traffic on one product, and plan what the page shows when stock runs out, because a clear sold-out message also reduces load.
7Follow-up questions
Would SELECT ... FOR UPDATE help here?
No. It makes the problem worse, because it takes the lock at the read and holds it for the whole read-check-write sequence. The atomic update holds the lock only for the update itself.
Can optimistic locking solve a hot row?
Not well. With thousands of concurrent attempts on one version, almost all fail and retry, and the retries collide again. Optimistic locking suits rare conflicts; a flash sale is the opposite.
How do you stop one hot product from affecting the rest of the shop?
Give the sale its own connection pool or bulkhead, rate limit purchase requests for that product, and put a cache in front of the product page. Then exhaustion on the hot path does not take connections away from other products.
8Conclusion
In this answer, we saw that a flash sale turns one stock row into a queue whose throughput is the inverse of lock hold time. An atomic conditional update with the slow work moved outside the lock is the first and cheapest fix. Bucketed counters spread the lock across rows, Redis reservations with reconciliation raise throughput much further, and a queue per product removes contention entirely, each with more complexity, and all governed by oversell and compensation rules agreed with the business.
Open with
The root cause is that every purchase updates one stock row, and row locks serialise them, so throughput is one over the lock hold time. If the transaction holds the lock for 200 milliseconds because it also calls payment, we get five purchases a second.
Then, if they want more
So the first fix is always to shorten the lock: a single atomic update, update stock set qty = qty minus one where id = ? and qty > 0, committed immediately, with the order and payment done afterwards and a compensating increment if payment fails. That can take us from five to hundreds per second and cannot oversell.
If that is not enough, I would split the stock into, say, ten bucket rows and pick one at random, which gives ten independent locks at the cost of trying other buckets near the end. For far higher rates, I would reserve in Redis with atomic decrements and reconcile against the database, accepting rare drift.
Or I would queue purchase requests per product and process them with a single consumer, telling users they are in line, which is fair and protects the database. Which one depends on the business: how much oversell is acceptable, how compensation works, and whether users can wait, so I would agree those rules before the sale and load test it.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "A flash sale on one product causes thousands of transactions to queue on a single row...": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/c5c3163a5e/