OwlTheEngineer
Engineering MistakesEpisode 58 · Backend

Database Deadlocks Explained: Why Two Transactions Freeze and How to Fix SQLSTATE 40P01

How circular lock waits happen in PostgreSQL, why the deadlock detector kills one transaction with 40P01, and how deterministic lock ordering prevents deadlocks completely.

Owl · 1 min read · 1 views
– comments
Ep 58 · Backend
60s VISUAL BREAKDOWN
Episode 58
Watch the fast visual breakdown or discuss on social:

A database deadlock happens when two concurrent transactions lock two rows in opposite order—so each transaction waits forever for the lock held by the other.


1. How a Circular Wait Happens

Imagine Alice (Account #1) transfers $50 to Bob (Account #2) at the exact same millisecond Bob transfers $20 back to Alice:

  1. Transaction A runs SELECT ... FOR UPDATE on Row #1 (acquires exclusive lock on #1).
  2. Transaction B runs SELECT ... FOR UPDATE on Row #2 (acquires exclusive lock on #2).
  3. Transaction A now tries to update Row #2 $\to$ blocked waiting for Transaction B!
  4. Transaction B now tries to update Row #1 $\to$ blocked waiting for Transaction A!

Neither transaction can proceed. They are stuck in a Wait-For Graph cycle (Tx A ⇄ Tx B).


2. How PostgreSQL Detects and Breaks Deadlocks (SQLSTATE 40P01)

PostgreSQL waits deadlock_timeout (default 1000ms), wakes up its background Deadlock Detector, and traverses the Wait-For Graph. When it finds a cycle:

  • It aborts one transaction as the victim with ERROR: deadlock detected (SQLSTATE 40P01) and rolls back its changes.
  • The surviving transaction immediately acquires the freed lock and commits cleanly.

3. The Permanent Fix: Deterministic Lock Ordering (ORDER BY id ASC)

A cycle in a Wait-For Graph is mathematically impossible if every transaction acquires row locks in the exact same sorted order:

BEGIN;

-- Always lock both rows sorted by primary key ASC before updating:
SELECT id, balance
FROM accounts
WHERE id IN (1, 2)
ORDER BY id ASC
FOR UPDATE;

UPDATE accounts SET balance = balance - 50 WHERE id = 1;
UPDATE accounts SET balance = balance + 50 WHERE id = 2;

COMMIT;

Because both transactions try to lock Row #1 first, the second transaction simply waits in a normal queue at Row #1 instead of creating a circular deadlock.

SYSTEM DESIGN CHECK

Test Your Understanding

Quick architectural scenario challenge based on this breakdown.

SCENARIO

A 3rd-party payment gateway starts timing out with 504 errors during peak traffic.

Q1.How should a downstream dependency failure be handled to protect upstream service availability?

Comments –