Reading preferences
Concept

Locks, Deadlocks, and Safe Retries

Trace a wait-for cycle and recover safely from a failed transaction.

database, postgresql, locks, deadlocks, concurrency, retries

Waiting is not always a deadlock

Transactions acquire locks to protect conflicting operations. A writer may wait for another writer; a wait becomes a deadlock when transactions form a cycle and none can proceed. Ordinary snapshot reads generally do not wait on row locks, although table locks and other operations can still block them.

SQL illustration

Imagine a disposable shared table items with rows 1 and 2. This is a prepared two-connection schedule, not one executable script. A and B each begin a transaction; commands are issued in the order shown. A's second update must be allowed to wait while B issues its second update:

A: BEGIN;
B: BEGIN;
A: UPDATE items SET value = value + 1 WHERE id = 1;
B: UPDATE items SET value = value + 1 WHERE id = 2;
A: UPDATE items SET value = value + 1 WHERE id = 2; -- waits for B
B: UPDATE items SET value = value + 1 WHERE id = 1; -- waits for A

PostgreSQL detects the cycle and aborts one participant; the survivor can proceed if no other blocker remains. The victim is not predetermined. A simple ordinary wait without a cycle is not automatically a deadlock.

See the reasoning

Build a wait-for graph

Follow one possible deadlock between two transactions. This is a prepared scenario, not live SQL.

Each holds a row

Transaction wait-for state
  • A: holds row 1
  • B: holds row 2

Both transactions have updated different rows and hold their row locks.

Recover without duplicating effects

Acquire shared resources in a consistent order where possible, keep transactions short, and investigate lock waits. Ordering reduces this class of deadlocks but cannot eliminate every source. After SQLSTATE 40P01, roll back the failed transaction and retry the whole transaction, including the reads and decisions, when doing so is appropriate. Use bounded retries with backoff and surface persistent failures. Serialization failures (40001) similarly require complete transaction retries.

External emails, payments, and other side effects are not undone by a database rollback. Use a suitable idempotency or transactional outbox design and handle uncertain commit outcomes rather than blindly repeating effects. Savepoints and exception handling can alter the scope of rollback; understand the actual application and database error boundary.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What happens when A updates a row already locked by B?
2. What makes this schedule a deadlock?
3. Which transaction will PostgreSQL choose as the deadlock victim?
4. What should an application retry after a deadlock failure?

References and further reading