Video in progress

Deadlocks show up on prod from time to time. How do you find the cause from the log, and how do you fix it?

ERROR:  deadlock detected
DETAIL: Process 4121 waits for ShareLock on transaction 99812; blocked by process 4170.
        Process 4170 waits for ShareLock on transaction 99807; blocked by process 4121.
        Process 4121: UPDATE accounts SET balance = balance - 100 WHERE id = 7
        Process 4170: UPDATE accounts SET balance = balance - 50 WHERE id = 3

The "deadlock detected" entry in the PostgreSQL log has the two processes, the locks they waited for, and the queries. Usually the cause is two code paths locking the same rows in different orders. The fix: make the lock order the same, or sort the rows to be locked up front.

📖 Answer

Reading this log: process 4121 has already updated account 3 and is now waiting for 7; 4170 has updated 7 and is waiting for 3. Two money transfers: one 3→7, the other 7→3. Each one locks the "sender" first.

PostgreSQL checks after deadlock_timeout (1s by default) and cancels one of them. The application gets SQLState 40P01.

The fix is to always take locks in the same order:

@Transactional
public void transfer(long from, long to, BigDecimal amount) {
    long first = Math.min(from, to), second = Math.max(from, to);
    accountRepo.lockById(first);   // SELECT ... FOR UPDATE
    accountRepo.lockById(second);
    // now you can update in any order you like
}

Batch updates have the same problem: UPDATE ... WHERE id IN (...) locks rows in their physical order in the table, so if two batches overlap, a deadlock is possible. First SELECT id ... ORDER BY id FOR UPDATE, then update.

Other places I check: foreign keys (an insert into a child takes FOR KEY SHARE on the parent), and hidden updates inside triggers. It's also useful to turn on log_lock_waits = on, which shows the long waits that didn't turn into a deadlock.

And always: you can't eliminate deadlocks 100%, so the application should have a bounded retry for 40P01.