Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A Spring Boot inventory service decrements stock with this flow: read the product row, check quantity > 0, then save quantity - 1. During a flash sale, stock went negative. Explain the bug and two fixes.

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.

Java
@Transactional
public void buy(long productId) {
Stock stock = stockRepository.findById(productId).orElseThrow();
if (stock.getQty() <= 0) {
throw new OutOfStockException(productId);
}
stock.setQty(stock.getQty() - 1);
stockRepository.save(stock); // UPDATE stock SET qty = ? WHERE id = ?
}
Step throughTwo requests buying the last unit
Request ADatabaseRequest B
SELECT qty -> 1
SELECT qty -> 1
1 > 0, set qty 0
1 > 0, set qty 0
UPDATE qty = 0, commit
UPDATE qty = 0, commit
2 sold, qty fell by 1

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.

Java
@Modifying
@Query("update Stock s set s.qty = s.qty - 1 where s.id = :id and s.qty > 0")
int decrementIfAvailable(@Param("id") long id);
@Transactional
public void buy(long productId) {
int updated = stockRepository.decrementIfAvailable(productId);
if (updated == 0) { // 0: no stock left (or unknown product)
throw new OutOfStockException(productId);
}
} // last unit: A gets 1, B gets 0 -> out of stock

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.

Java
@Entity
class Stock {
@Id Long id;
int qty;
@Version long version; // incremented on every update
}
// save() now runs: UPDATE stock SET qty = 0, version = 8 WHERE id = 42 AND version = 7
// A updates 1 row. B's WHERE version = 7 matches 0 rows -> ObjectOptimisticLockingFailureException

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.

SQL
ALTER TABLE stock ADD CONSTRAINT stock_qty_non_negative CHECK (qty >= 0);
UPDATE stock SET qty = -1 WHERE id = 42; -- ERROR: violates check constraint "stock_qty_non_negative"
Choosing a fix
ApproachHow it worksBest for
Atomic conditional updatecheck and decrement in one UPDATEhot rows, simple rules
Optimistic @Versiondetect a changed row, retryricher logic, moderate contention
Pessimistic FOR UPDATElock on read, others waitshort transactions, must not retry
CHECK (qty >= 0)database rejects bad valuesalways, 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.

What to say in the interviewAbout 80 seconds aloud

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/