Deadlocks
Overview and setup
A deadlock is a cycle of transactions waiting for resources held by each other. In PostgreSQL A can lock row 1 and B row 2, then each request the other row. PostgreSQL detects the cycle and aborts one transaction with SQLSTATE 40P01; do not assume which victim is selected. A common prevention strategy is acquiring locks in a consistent order across all code paths. This reduces risk but does not eliminate all deadlocks.
Use a fresh disposable file database initialized with versions/v56/locking-fixture.sql. Enable WAL with PRAGMA journal_mode=WAL; before opening two independent private-cache connections A and B. Use driver autocommit, no implicit transaction, zero busy timeout, and fully fetch each query result. Follow steps in order; the included Python validator automates this. Never use production data.
First two-session example
Run each numbered statement in the indicated connection; do not paste the whole schedule into one session.
1. Session A
BEGIN IMMEDIATE;2. Session A
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=1;3. Session B
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=2;Observed error: SQLITE_BUSY
4. Session A
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=2;5. Session A
COMMIT;6. Session B
SELECT id,qty,version FROM lock_item ORDER BY id;Observed rows: [[1, 11, 2], [2, 21, 2]]
How it works
The SQLite examples intentionally do not reproduce a PostgreSQL deadlock. Because only one writer is admitted, B fails before acquiring a second independent write lock. Rollback releases A’s writer transaction and B can retry. A busy error alone does not establish a wait-for cycle. In PostgreSQL handle the victim error by rolling back and retrying the complete transaction with bounded backoff and safe external side effects. See the separate unexecuted native schedule.
Second two-session example
Run each numbered statement in the indicated connection; do not paste the whole schedule into one session.
1. Session A
BEGIN IMMEDIATE;2. Session A
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=1;3. Session B
BEGIN IMMEDIATE;Observed error: SQLITE_BUSY
4. Session A
ROLLBACK;5. Session B
BEGIN IMMEDIATE;6. Session B
SELECT qty,version FROM lock_item WHERE id=1;Observed rows: [[10, 1]]
7. Session B
UPDATE lock_item SET qty=qty+1,version=version+1 WHERE id=1;8. Session B
COMMIT;9. Session A
SELECT qty,version FROM lock_item WHERE id=1;Observed rows: [[11, 2]]
Practice and mistakes
Practice: draw A→B and B→A for the native deadlock scenario; redesign both sessions to acquire item 1 before item 2. Hint 1: a blocked session cannot issue the next statement on the same connection. Hint 2: consistent order removes this particular cycle. Mistake: calling every long wait a deadlock.