Video in progress
OptimisticLockException keeps showing up on prod. How do you analyze it, and how do you design the retry?
First I find out which entity and which threads are colliding. The retry has to rerun the whole transaction with a fresh persistence context, a limited number of attempts and jitter; if it's a hot row, the model has to change.
📖 Answer
OptimisticLockException (StaleObjectStateException in Hibernate) means the version you read is no longer in the database at UPDATE time. It is not a bug, it is a signal: two flows are changing the same row at the same time.
I start the analysis from the logs: the exception carries the entity name and ID. If one ID shows up in 90% of the cases, that is a hot row, for example a shared counter or the stock of a single product in a warehouse. A retry does not cure that, it only adds load.
For the retry to be correct:
- the whole transaction is rerun; you cannot
savethe old entity again, because it is already stale; - the retry sits outside the transaction boundary, otherwise you end up spinning inside a single rollback-only transaction;
- 3-5 attempts, exponential backoff and jitter.
@Retryable(retryFor = ObjectOptimisticLockingFailureException.class,
maxAttempts = 4, backoff = @Backoff(delay = 50, multiplier = 2, random = true))
public void reserve(long productId, int qty) {
tx.executeWithoutResult(s -> stockService.reserve(productId, qty));
}
For a hot row there are other options: an atomic UPDATE stock SET qty = qty - :n WHERE id = :id AND qty >= :n, splitting the counter across several rows, or a pessimistic lock. Excluding fields that should not affect the version with @OptimisticLock(excluded = true) also reduces conflicts.
Sign up to mark studied questions and save your progress.