Video in progress

Senior 🌱 Spring

In production you occasionally get "Deadlock found when trying to get lock" (or "deadlock detected" in PostgreSQL). How do you analyze and fix it?

Two transactions lock the same rows in different orders. Find the queries in the database's deadlock log, make the lock order consistent, shorten the transaction and add a retry that is safe for deadlocks.

📖 Answer

A deadlock is a database-level condition: transaction A holds row 1 and waits for row 2, while B holds row 2 and waits for row 1. The database sacrifices one of them. In Spring it surfaces as CannotAcquireLockException (or DeadlockLoserDataAccessException).

  1. Gather the facts.
  • PostgreSQL: log_lock_waits = on, and the deadlock message appears in the server log with both queries.
  • MySQL: SHOW ENGINE INNODB STATUS, the "LATEST DETECTED DEADLOCK" section.
  • On the application side: find which endpoint/consumer the error came from by trace id.
  1. Typical causes in Spring applications:
  • Money transfer: transfer(A, B) and at the same time transfer(B, A). Each one locks "its own" account first.
  • Hibernate flush order: you wrote the order the same way in code, but the flush sends the UPDATEs in a different order.
  • UPDATE ... WHERE status = ? where there is no index: the database locks many rows (in MySQL, with gap locks).
  • An HTTP call inside a long transaction: locks are held for seconds, which raises the chance of collisions.
  1. The fix:
@Transactional
public void transfer(long from, long to, BigDecimal amount) {
    long first = Math.min(from, to), second = Math.max(from, to);
    Account a = repo.lockById(first);   // PESSIMISTIC_WRITE, the smaller id always first
    Account b = repo.lockById(second);
    ...
}
  • Always acquire locks in the same order (by id).
  • hibernate.order_updates=true: the UPDATEs in a flush are sorted by entity and id.
  • Shorten the transaction and add the indexes you need.
  • A deadlock is a transient error, so retrying the whole transaction is right (Spring Retry @Retryable(retryFor = CannotAcquireLockException.class) or Spring Framework 7's @Retryable). The retry must sit outside @Transactional, otherwise you retry inside a dead transaction.

Watch the number of deadlocks as a metric: retry hides them, but a growing trend is a sign of a design problem.