Full answer
Typical cause: a transfer from A to B locks A then B, while a transfer from B to A locks B then A. Each holds one lock and waits for the other. PostgreSQL detects the cycle after deadlock_timeout and aborts one transaction with SQLSTATE 40P01.
Fixes:
- Consistent ordering: update the lower account id first, or lock both rows up front with
SELECT ... FROM accounts WHERE id IN (a, b) ORDER BY id FOR UPDATE. - Short transactions: no network calls or user waits while holding row locks.
- Retries: deadlocks can never be ruled out entirely, so the application should retry the whole transaction a few times with a small random delay.
- Investigation: PostgreSQL logs both statements involved in the deadlock, which shows the conflicting order.
Indexes matter too: an UPDATE without a supporting index can lock more than expected in some engines, widening the conflict.
Key points
- Deadlocks come from opposite lock orders
- Lock rows in a consistent order
- Keep transactions short
- Retry on deadlock errors
- Read the deadlock log details
Common mistakes
- Raising lock timeouts, which only delays the failure
- No retry logic for serialization and deadlock errors
Follow-ups
- How does a deadlock differ from a long lock wait?
- What is SQLSTATE 40001?
Tips
- Describe the opposite-order cycle