Datarow lockrow lockslock cycle

Deadlock

Definition

A deadlock is a cycle of lock waits between transactions; databases detect the cycle and abort one participant so the others can continue.

In practice

Row locks taken by UPDATE, DELETE and SELECT ... FOR UPDATE are held until commit or rollback. If transaction A locks row 1 then wants row 2, while B locks row 2 then wants row 1, both wait forever. Postgres checks for cycles after deadlock_timeout (1 s by default) and aborts one with error 40P01.

Deadlocks are normal under concurrency, not a sign of corruption, but they waste work. Lock rows in a consistent order (for example by ascending id), keep transactions short, and retry the aborted transaction. A rising deadlock rate after a deploy usually means a new code path locks rows in a different order.

Example

Transfer A moves money from account 1 to 2 and transfer B from 2 to 1 at the same time; sorting the ids so both lock account 1 first removes the deadlock.