Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A stock reservation endpoint does: read quantity with a repository findById, check quantity >= requested, then save the entity with quantity - requested, all in one @Transactional method on PostgreSQL READ COMMITTED. Under load the stock goes negative in reports. Explain the anomaly and give three fixes with their trade-offs.

Try it yourself

Isolation levels: what a second read sees

Step through two transactions and see exactly when read committed and repeatable read give different answers.

Read this example as text

T1 at read committed

  1. T1 begins. Transaction T1 starts with isolation level READ COMMITTED. The row holds balance 100.
  2. T1 reads the balance. T1 reads 100. Under read committed each statement looks afresh at what is committed when the statement starts.
  3. T2 changes the row. A second transaction, T2, sets the balance to 150 but has not committed. The database keeps both versions: 100 is still the committed one.
  4. T1 reads again, before T2 commits. T1 reads 100 again. Neither level shows another transaction's uncommitted change, so there is no dirty read. T1 does not wait for T2 either.
  5. T2 commits. T2 commits. The committed balance is now 150.
  6. T1 reads a third time. T1 reads 150. The same query, inside one transaction, returned 100 and then 150. This is a non-repeatable read, and read committed allows it.
  7. T1 commits. T1 ends. A transaction that starts now reads 150 at either level.

T1 read 100, 100, then 150: a non-repeatable read.

T1 at repeatable read

  1. T1 begins. Transaction T1 starts with isolation level REPEATABLE READ. The row holds balance 100.
  2. T1 reads the balance. T1 reads 100. Under repeatable read this first read fixes T1's snapshot: T1 will keep seeing the data as it was committed at this moment.
  3. T2 changes the row. A second transaction, T2, sets the balance to 150 but has not committed. The database keeps both versions: 100 is still the committed one.
  4. T1 reads again, before T2 commits. T1 reads 100 again. Neither level shows another transaction's uncommitted change, so there is no dirty read. T1 does not wait for T2 either.
  5. T2 commits. T2 commits. The committed balance is now 150.
  6. T1 reads a third time. T1 still reads 100. Its snapshot was fixed at its first read, so T2's commit is invisible to it. The read is repeatable.
  7. T1 commits. T1 ends. A transaction that starts now reads 150 at either level.

T1 read 100 three times: its reads were repeatable.

What this example leaves out
  • Modelled on PostgreSQL and MySQL InnoDB, where a plain SELECT reads a snapshot and never waits for a writer.
  • SQL Server's default read committed uses locks instead: there, T1's second read would wait for T2 to finish.
  • Only reads are compared. What happens when T1 also writes the row (a lost update, or an error in PostgreSQL) is not modelled.

This is a lost update. Two requests read the same quantity, both pass the check, and the second save overwrites the first with a value computed from stale data, and READ COMMITTED does nothing to stop it. We fix it with an atomic conditional UPDATE, a pessimistic lock (SELECT ... FOR UPDATE), or optimistic locking with @Version, and we add a CHECK constraint as a safety net.

Why this question is asked

Read, check, write is the most natural way to write business logic, and it is also the most common concurrency bug in Spring services. It passes every unit test and only breaks when two requests arrive within a few milliseconds of each other, which is exactly what happens under load. Interviewers ask this because the fix is not one annotation: each option has a cost, and the right one depends on how hot the row is. In this answer, we will recap what READ COMMITTED does and does not promise, reproduce the lost update, and then compare three fixes and a safety net, ending with the flash-sale case.

1A Quick Recap of READ COMMITTED

READ COMMITTED, the PostgreSQL default, guarantees one thing: a statement never sees data that another transaction has not committed. Each statement takes a fresh snapshot, a view of all committed data at the moment the statement starts.

It does not guarantee that the value we read a moment ago is still the current value when we write. Between our SELECT and our UPDATE, another transaction can commit a change to the same row. Putting both steps inside one @Transactional method does not change that: @Transactional groups the statements so they commit or roll back together, but it does not lock what we read.

2Reproducing the Lost Update

Here is the endpoint as it is usually written with Spring Data JPA.

Java
@Transactional
public void reserve(long itemId, int requested) {
Stock s = stockRepository.findById(itemId).orElseThrow(); // SELECT ... quantity = 5
if (s.getQuantity() < requested) throw new OutOfStockException();
s.setQuantity(s.getQuantity() - requested); // 5 - 3 = 2
reservationRepository.save(new Reservation(itemId, requested));
} // at commit Hibernate flushes: UPDATE stock SET quantity = 2 WHERE id = ?
Step throughTwo reservations for 3 units with 5 in stock
Request 1PostgreSQLRequest 2
findById: quantity 5
findById: quantity 5
check 5 >= 3, UPDATE quantity = 2, commit
check 5 >= 3 (stale), UPDATE quantity = 2
row lock is free, update applied, commit

5 messages in order. Play them, or step through them one at a time.

Both checks were made on the same old value. 6 units were reserved from 5.

Now two requests for 3 units arrive together while the quantity is 5. Both run findById before either commits, so both read 5. Both pass the check, both compute 2, and both insert a reservation. Hibernate's dirty checking writes the absolute value it computed, UPDATE stock SET quantity = 2, so the second commit simply writes 2 over the first commit's 2. We sold 6 units out of 5.

Notice that the stored quantity can even look healthy. The damage shows up in reports that compare stock with reservations: 5 in stock minus 6 reserved is -1. The first update was not rejected; it was silently overwritten, which is why this anomaly is called a lost update.

3Fix 1: An Atomic Conditional UPDATE

The simplest fix moves the check into the UPDATE itself, so reading and writing happen in one statement under the row lock.

Java
@Modifying
@Query("update Stock s set s.quantity = s.quantity - :n where s.id = :id and s.quantity >= :n")
int reserve(@Param("id") long id, @Param("n") int n);
// in the service
if (stockRepository.reserve(itemId, requested) == 0) throw new OutOfStockException();
// request 1: 1 row updated, quantity 5 -> 2
// request 2: waits for request 1's row lock, re-checks 2 >= 3, 0 rows updated

The reason this works is the way PostgreSQL runs an UPDATE at READ COMMITTED. If another transaction holds the row, our UPDATE waits, then re-reads the latest committed version and evaluates the WHERE clause again. So the second request sees 2, fails the condition, and updates 0 rows. We check the affected row count to know whether the reservation succeeded.

This is the fastest option: one round trip, the row lock is held only for one statement, and there is no retry logic. Its limit is that the whole rule must fit in SQL. Also remember that a bulk @Modifying query bypasses the persistence context, so a Stock entity already loaded in the same transaction would be stale.

4Fix 2: A Pessimistic Lock With FOR UPDATE

If the decision needs Java logic, we can lock the row when we read it. Spring Data JPA does this with @Lock.

Java
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select s from Stock s where s.id = :id")
Optional<Stock> findForUpdate(@Param("id") long id); // SELECT ... FOR UPDATE
// request 1 locks the row and reads 5; request 2 blocks in findForUpdate
// request 1 commits quantity 2; request 2 wakes up, reads 2, fails the check

The second transaction now waits at the read instead of at the write, so it always decides on fresh data. It is correct and easy to reason about. The cost is that every request for that item queues behind the lock for the whole transaction, so a slow call inside the method slows everyone. And if one transaction locks items 1 then 2 while another locks 2 then 1, they deadlock; PostgreSQL aborts one with SQLSTATE 40P01. Locking rows in a consistent order, such as by id, avoids that, and a lock timeout (for example the jakarta.persistence.lock.timeout hint) keeps waits bounded.

5Fix 3: Optimistic Locking With @Version

Optimistic locking assumes conflicts are rare and detects them at write time. We add a version column to the entity.

Java
@Entity
class Stock {
@Id Long id;
int quantity;
@Version long version;
}
// Hibernate now writes: UPDATE stock SET quantity = 2, version = 8 WHERE id = ? AND version = 7
// request 1: 1 row updated, commit
// request 2: 0 rows updated -> OptimisticLockException
// (Spring: ObjectOptimisticLockingFailureException), retry the whole method

The losing request learns that someone changed the row since it read it, and must retry in a new transaction, which then reads the new quantity. No lock is held while the code thinks, so it scales well when conflicts are rare. On a hot item, though, most requests lose and retry, and the retries add load exactly when the system is busiest. So optimistic locking suits low contention, and the conditional update or a pessimistic lock suits hot rows.

6The Safety Net and the Other Options

Whatever we choose, we should let the database refuse an impossible state with ALTER TABLE stock ADD CONSTRAINT stock_non_negative CHECK (quantity >= 0). With the conditional update or any relative update (quantity = quantity - :n), an oversell now fails loudly with a constraint violation instead of passing silently. Notice that a CHECK cannot catch the original bug on its own, because the lost update wrote 2, a perfectly valid value.

Running the method at REPEATABLE READ in PostgreSQL would also detect the conflict: the second transaction's UPDATE would fail with SQLSTATE 40001 because the row changed after its snapshot. That is correct too, but it is really optimistic locking done by the database, so it needs the same retry handling.

Comparing the fixes
FixStrengthCost
Conditional UPDATEone statement, no retries, fastestrule must fit in SQL
FOR UPDATEfresh data for Java logicqueues on hot rows, deadlock risk
@Versionno locks held, great at low contentionmany retries on hot items
REPEATABLE READdatabase detects the conflict40001 retries, like @Version
CHECK (quantity >= 0)last line of defenceonly catches negative values

7Follow-up questions

How would you handle a flash sale where one item gets 5,000 requests per second?

At that rate any design that funnels every request through one row lock becomes a queue, even the conditional update. I would take the contention out of the row. One option is to split the stock into, say, 20 bucket rows of 50 units each and let each request decrement a random bucket with a conditional update, trying another bucket if one is empty. Another is to keep the live counter in memory, such as an atomic decrement in Redis, and write confirmed reservations to PostgreSQL asynchronously. A third is to put requests for that item on a queue and let a single consumer allocate units in order. Each moves the hot spot away from one row while the database constraint still guards the final numbers.

Why does the conditional UPDATE not need REPEATABLE READ?

Because the read and the write happen in one statement. At READ COMMITTED, PostgreSQL re-evaluates the WHERE clause against the latest committed row version after waiting for any concurrent writer, so the condition is always checked against current data.

8Conclusion

In this answer, we saw that read, check and write in one @Transactional method at READ COMMITTED allows a lost update: two requests read the same quantity and the second save overwrites the first. A conditional UPDATE that checks the affected row count is the simplest and fastest fix, FOR UPDATE suits logic that must run in Java at the cost of queuing, and @Version suits low contention at the cost of retries. A CHECK constraint is the safety net, and very hot items need the contention designed away.

What to say in the interviewAbout 80 seconds aloud

Open with

This is a lost update. Two requests read the same quantity with findById, both pass the check, and Hibernate writes the absolute value each one computed, so the second commit overwrites the first.

Then, if they want more

READ COMMITTED only stops dirty reads; it doesn't lock what we read, and @Transactional doesn't either. I'd fix it in one of three ways.

The simplest is a conditional update, update stock set quantity = quantity - n where id = ? and quantity >= n, and I check the row count; PostgreSQL re-checks the condition on the latest version after any concurrent writer, so it can't oversell, and it's one round trip.

If the decision needs Java logic, I'd use a pessimistic lock, @Lock PESSIMISTIC_WRITE, which is select for update; it's correct but queues requests on hot items and can deadlock if rows are locked in different orders.

Or I'd use optimistic locking with @Version, where the loser gets an optimistic lock exception and retries; that's good when conflicts are rare and poor on hot items. In every case I'd add a check constraint quantity >= 0 as a safety net. REPEATABLE READ would also catch the conflict, but it needs the same retry handling.

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.
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 stock reservation endpoint does: read quantity with a repository findById, check...": https://scrivio-interview-library.netlify.app/databases/acid-and-isolation/10ddb09f2c/