Video in progress
To decrement warehouse stock (high contention), how do you choose between optimistic and pessimistic locking?
If conflicts are rare, optimistic (@Version + retry): no lock is held. If many writers hit one row (a popular product, a promotion), optimistic turns into a retry storm; then a pessimistic lock or an atomic SQL update ... set qty = qty - ? where qty >= ? is more reliable.
📖 Answer
For the decision I look at the probability of conflict and the transaction length.
Optimistic: ordinary SKUs, a few sales a day. No locks, no deadlocks, fast reads. But in a "flash sale", if 500 requests per second hit one product, after every commit the other 499 transactions get OptimisticLockException, retry, and lose again. The CPU and the database are under load, and the user sees a timeout.
Pessimistic:
@Lock(LockModeType.PESSIMISTIC_WRITE)
@QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "2000"))
Optional<Stock> findBySku(String sku);
Requests wait in a queue, with no retries. But if there's an external call (a payment API) inside the transaction, the lock is held for seconds and throughput collapses. Locking several rows in different orders causes a deadlock, so always lock in id order.
Often the best option is an atomic update with no ORM involved:
@Modifying
@Query("update Stock s set s.qty = s.qty - :n where s.sku = :sku and s.qty >= :n")
int reserve(String sku, int n); // if it returns 0: not enough stock
A single statement, a short row lock, and no overselling. The downside is that the Stock in the context goes stale and @Version isn't incremented, and you have to account for that.
For very hot keys the next step is to split the stock across several "bucket" rows, or to route reservations through a queue to a single writer. But I go there only when measurements demand it.
Sign up to mark studied questions and save your progress.