Video in progress
Two parallel transactions occasionally hit a deadlock with this code. What is the cause, and how do you prevent it at the system level?
@Transactional
public void transfer(long fromId, long toId, BigDecimal amount) {
Account from = em.find(Account.class, fromId);
Account to = em.find(Account.class, toId);
from.withdraw(amount);
to.deposit(amount);
}
Each transaction locks the rows in a different order: one A then B, the other B then A. Hibernate's flush order depends on the access order. The fix is to make the lock order stable: sort by ID, order_updates, or lock the needed rows up front in a defined order.
📖 Answer
transfer(1, 2) and transfer(2, 1) are called at the same time. On flush Hibernate sends the UPDATEs. The first transaction locks row 1, the second locks row 2. Then each waits for the other's row: the database detects this as a deadlock and kills one of them.
Hibernate's hibernate.order_updates=true setting sorts UPDATEs by entity type and ID within a single flush. It helps here, but only for UPDATEs and only within one flush. If a query triggers an auto-flush in between, or the lock was taken at find time, it does not help.
More reliable is taking the locks explicitly and in order:
@Transactional
public void transfer(long fromId, long toId, BigDecimal amount) {
long first = Math.min(fromId, toId), second = Math.max(fromId, toId);
Account a = em.find(Account.class, first, LockModeType.PESSIMISTIC_WRITE);
Account b = em.find(Account.class, second, LockModeType.PESSIMISTIC_WRITE);
Account from = a.getId() == fromId ? a : b;
Account to = from == a ? b : a;
from.withdraw(amount);
to.deposit(amount);
}
At the system level, this is what I put in place:
- a team rule: transactions that change several rows take locks in ID order;
- retry on deadlock: it is a natural event and you cannot eliminate it entirely, but keep the retry bounded;
lock_timeoutanddeadlock_timeoutmetrics, andlog_lock_waits=onin the PostgreSQL log;- short transactions: the shorter the lock, the lower the chance of overlap.
Sign up to mark studied questions and save your progress.