Video in progress

What is a deadlock? Explain it with two transactions and say what PostgreSQL does about it.

A deadlock is when two transactions each wait for a resource the other has locked, so neither can move forward. PostgreSQL detects this after deadlock_timeout (1 s by default) and aborts one of the transactions with an error, and the other continues.

📖 Answer

-- T1                                      -- T2
BEGIN;                                     BEGIN;
UPDATE accounts SET ... WHERE id = 1;      UPDATE accounts SET ... WHERE id = 2;
UPDATE accounts SET ... WHERE id = 2;      UPDATE accounts SET ... WHERE id = 1;
-- waits for T2                            -- waits for T1 -> a cycle

After a second, one of them gets:

ERROR: deadlock detected
DETAIL: Process 4121 waits for ShareLock on transaction 9001; blocked by process 4188.

In real life this usually happens with money transfers: when an A→B and a B→A transfer arrive at the same time.

The main way to prevent it is to always lock resources in the same order:

long first = Math.min(fromId, toId);
long second = Math.max(fromId, toId);
accountRepo.lockById(first);    // SELECT ... FOR UPDATE
accountRepo.lockById(second);

Additional measures: keep transactions short, and don't touch more rows than needed in one transaction.

You can't always eliminate deadlocks completely, so the application should catch this error (SQLState 40P01) and retry. In Spring it arrives as CannotAcquireLockException (or the PessimisticLockingFailureException family), and Spring Retry or a simple loop is enough for the retry.