Sub topic 2
Waiting for locks: the queue and how blocking chains form
This chapter assumes you know basic SQL, transactions (BEGIN, COMMIT, ROLLBACK), and how to run two psql sessions at once.
Waiting for locks: the queue and how blocking chains form
When a session requests a lock that another session holds in a conflicting mode, PostgreSQL places the request in a wait queue. The request waits until the holder commits or rolls back. Waiters are generally served in arrival order, so a new request can also wait behind an earlier request that is itself blocked. These waits chain together: session C waits for B, and B waits for A.
CREATE TABLE accounts (id int PRIMARY KEY, balance numeric NOT NULL);
INSERT INTO accounts VALUES (1, 100), (2, 100);
-- Session A
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- no COMMIT yet
-- Session B (blocks until session A ends its transaction)
UPDATE accounts SET balance = balance + 5 WHERE id = 1;How a deadlock happens
A deadlock occurs when two transactions each hold a lock that the other needs. Neither can proceed, and waiting never ends the situation.
-- Session 1
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
-- Session 2
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 2;
-- Session 1 waits for session 2
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
-- Session 2 waits for session 1, closing the cycle
UPDATE accounts SET balance = balance + 10 WHERE id = 1;How PostgreSQL detects and resolves deadlocks
PostgreSQL does not check for deadlocks on every wait. When a waiting session has waited for deadlock_timeout (default 1 second), it checks the wait graph for a cycle. If it finds one, it aborts one session in the cycle:
ERROR: deadlock detected
DETAIL: Process 4312 waits for ShareLock on transaction 741; blocked by process 4398.The error has SQLSTATE 40P01. The server log records the full detail. The aborted transaction must be rolled back, and the other session can then continue.
Avoiding deadlocks in application code
Use these habits to prevent deadlocks:
- Lock rows in one fixed order in every transaction, such as ascending
id. - Keep transactions short, and never wait for user input inside one.
- Retry the transaction when it fails with SQLSTATE
40P01.
BEGIN;
SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
UPDATE accounts SET balance = balance + 10 WHERE id = 2;
COMMIT;Exercise
Session 1 locks row 1 and then requests row 2. Session 2 locks row 2 and then requests row 1. What happens, and how do you prevent it?
Show answer
The sessions form a deadlock cycle. After deadlock_timeout, PostgreSQL aborts one session with SQLSTATE 40P01. To prevent it, have every transaction lock rows in the same order, such as ascending id.