Video in progress

Two users decreased a product's stock at the same time and one decrement got lost. How does this happen, and how do you prevent it?

This is a "lost update": both transactions read the old value, computed in Java, and wrote their result, so the second overwrote the first's result. The fixes: an atomic UPDATE ... SET x = x - 1, SELECT ... FOR UPDATE, or optimistic locking with a version column.

📖 Answer

The problematic code:

Product p = repo.findById(id).orElseThrow();   // both read quantity = 10
p.setQuantity(p.getQuantity() - 1);            // both computed 9
repo.save(p);                                  // the result is 9, it should have been 8

PostgreSQL's default Read Committed level doesn't stop this.

The simplest and most reliable fix is to hand the calculation to the database:

UPDATE products
SET quantity = quantity - 1
WHERE id = :id AND quantity > 0;

This statement locks the row and works on the latest value. If the number of affected rows is 0, the stock is gone.

If the logic is complex and you have to compute in Java:

  • pessimistic: SELECT ... FOR UPDATE (in JPA, @Lock(PESSIMISTIC_WRITE)): the second transaction waits for the first to finish;
  • optimistic: add a @Version column to the entity. The second save fails with OptimisticLockException, and you retry.

If contention is low, use optimistic; if many writes hit one "hot" row, use an atomic UPDATE or pessimistic locking.