Quick revision
The short answer
The bug is a lost update: two requests read the same quantity, both see it is above zero, and both save their own quantity - 1, so one decrement is lost and stock oversells. Fix 1 is an atomic conditional update, UPDATE stock SET qty = qty - 1 WHERE id = ? AND qty > 0, checking that one row was updated. Fix 2 is optimistic locking with @Version, retrying when the save fails with an optimistic lock exception; pessimistic locking also works but holds locks longer, and a CHECK (qty >= 0) constraint is the last line of defence.
What to remember
In this answer, we saw that reading the quantity, checking it in Java and saving the result causes a lost update, because READ COMMITTED lets two transactions read the same value. We fixed it with an atomic conditional UPDATE that checks and decrements in one step and with optimistic locking via @Version and retries, compared pessimistic locking, which is correct but holds locks longer, and added a CHECK constraint so the database refuses negative stock whatever the code does.
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 bug is a lost update: two requests read the same quantity, both see it is above zero, and both save their own quantity - 1, so one decrement is lost and stock oversells. Fix 1 is an atomic conditional update, UPDATE stock SET qty = qty - 1 WHERE id = ? AND qty > 0, checking that one row was updated. Fix 2 is optimistic locking with @Version, retrying when the save fails with an optimistic lock exception; pessimistic locking also works but holds locks longer, and a CHECK (qty >= 0) constraint is the last line of defence.
Why this question is asked
Overselling during a flash sale is one of the most common and expensive concurrency bugs in Spring applications. The code looks correct when we read it line by line, and it passes every test that runs one request at a time. Interviewers ask this question because explaining it requires understanding what a transaction does and does not protect, and the fixes show whether we can choose between database-level and application-level solutions. In this answer, we will reproduce the race, see why @Transactional does not prevent it, fix it with an atomic update and with optimistic locking, look at pessimistic locking, and add a database constraint as a safety net.
1Reproducing the Bug
Here is the service as it was written. It reads the product's stock row, checks the quantity, and saves the new value.
7 messages in order. Play them, or step through them one at a time.
Both requests decide from the same stale value; the second write silently replaces the first.
With one request at a time, it is fine. Now picture the last unit, qty = 1, and two requests arriving within the same millisecond. Request A reads qty 1. Request B reads qty 1. Both pass the check. A writes qty 0 and commits. B writes qty 0 and commits. Two customers bought the item, but the quantity only went down by one. In a sale with thousands of concurrent requests, this happens again and again. The same race is what drives stock below zero: if the write is a relative decrement, such as a native query SET qty = qty - 1 run after the check in Java, both decrements are applied to the last unit and 1 becomes -1.
2Why @Transactional Does Not Prevent It
Many developers expect the transaction to protect them. It does not, because of the isolation level. PostgreSQL and many other databases default to READ COMMITTED, which means each statement sees data committed before it started, and plain reads take no locks. So both transactions can read qty 1 at the same time, and nothing stops either of them from writing afterwards.
The pattern of read, decide in Java, then write a computed value is called a read-modify-write, and under concurrency it causes a lost update: the second write is based on a value that is no longer true. To fix it, we must make the decision and the write happen with knowledge of the current value, either in one atomic statement or by detecting that the value changed.
3Fix 1: An Atomic Conditional Update
The simplest and fastest fix moves the check into the UPDATE itself. The database evaluates the WHERE condition and applies the change as one atomic step on the row, and concurrent updates on the same row are serialised by the row lock the UPDATE takes. Then we look at how many rows were changed.
Notice what happens with our two requests now. A's update takes the row lock and sets qty to 0. B's update waits for that lock; under READ COMMITTED, PostgreSQL then re-checks B's WHERE condition against the newly committed row, finds qty > 0 is false, and updates nothing. B gets 0 rows and a clear out-of-stock error. There is no retry, no extra read, and the lock is held only for the moment of the update.
4Fix 2: Optimistic Locking With @Version
Sometimes the logic is too rich for a single UPDATE, for example when the decision depends on several fields or other tables. Then optimistic locking fits. We add a version column to the entity, and Hibernate adds it to every update's WHERE clause.
When B's update finds no row with the expected version, Hibernate throws an OptimisticLockException, which Spring translates into ObjectOptimisticLockingFailureException. B then retries the whole transaction: it reads qty 0, fails the check, and reports out of stock. We can retry with a small loop or Spring Retry's @Retryable, three attempts with a short random delay.
But there is a catch for flash sales. Optimistic locking assumes conflicts are rare. With thousands of buyers for one product, most attempts conflict, retries pile up, and latency grows. For a hot single row, Fix 1 is the better choice; optimistic locking shines when contention is moderate.
5Pessimistic Locking, and a Constraint as the Safety Net
A third option is pessimistic locking: lock the row when reading it, so the second request waits until the first commits. With Spring Data JPA, we annotate the finder with @Lock(LockModeType.PESSIMISTIC_WRITE), which issues SELECT ... FOR UPDATE. It is correct and easy to understand, but each request holds the lock for its whole transaction, including any Java work, so under heavy load requests queue up behind each other, and holding locks across several rows can lead to deadlocks.
Whatever fix we choose, we add a database constraint as the last line of defence. If any code path, a batch job or a manual script, ever tries to make stock negative, the database rejects it instead of silently corrupting the data.
| Approach | How it works | Best for |
|---|---|---|
| Atomic conditional update | check and decrement in one UPDATE | hot rows, simple rules |
Optimistic @Version | detect a changed row, retry | richer logic, moderate contention |
| Pessimistic FOR UPDATE | lock on read, others wait | short transactions, must not retry |
| CHECK (qty >= 0) | database rejects bad values | always, as a safety net |
6Follow-up questions
Would SERIALIZABLE isolation fix it?
In PostgreSQL, yes: one of the two transactions would fail with a serialization error and could be retried. But that applies to every transaction using that level, adds retries everywhere, and costs throughput. The targeted fixes are simpler and cheaper for this case.
Why does the atomic update not need a retry?
Because the database re-evaluates the condition after waiting for the row lock. The second request sees the committed quantity and simply updates zero rows, which we report as out of stock.
Should stock for a flash sale even live in one row?
For very hot products, teams sometimes split the stock into several rows, such as ten buckets of 100 units, and decrement a random bucket, which spreads lock contention. It adds complexity, so we only do it when one row really becomes the bottleneck.
7Conclusion
In this answer, we saw that reading the quantity, checking it in Java and saving the result causes a lost update, because READ COMMITTED lets two transactions read the same value. We fixed it with an atomic conditional UPDATE that checks and decrements in one step and with optimistic locking via @Version and retries, compared pessimistic locking, which is correct but holds locks longer, and added a CHECK constraint so the database refuses negative stock whatever the code does.
Open with
This is a lost update caused by a read-modify-write. Two requests read the row at the same time, both see quantity 1, both pass the check in Java, and both save quantity 0, so two units are sold but stock drops by one; in a flash sale that repeats until stock goes wrong or negative. @Transactional does not help, because under READ COMMITTED plain reads take no locks.
Then, if they want more
My first fix is an atomic conditional update: UPDATE stock SET qty = qty - 1 WHERE id = ? AND qty > 0, and check the row count. If it is zero, the item is sold out.
The database serialises the two updates on the row lock and re-checks the condition for the second one, so no retries are needed. That is the best fit for a hot product.
My second fix is optimistic locking: a @Version field, so the update includes WHERE version = the one we read, and a conflicting save throws an optimistic locking exception that we retry. It suits richer logic but retries a lot under heavy contention. Pessimistic locking with PESSIMISTIC_WRITE also works, but holds the lock for the whole transaction. And I would add CHECK qty >= 0 as a final safety net.
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 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 "A Spring Boot inventory service decrements stock with this flow: read the product row...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/06939ba1ec/