Sub topic 13
Deadlocks: Detection and Avoidance
The deadlock pattern
This chapter assumes basic SQL, transactions, primary keys, constraints, and concurrent database sessions.
A deadlock occurs when transactions wait for one another in a cycle. Each transaction holds a lock that another transaction needs, so none can continue.
For example:
- Transaction A locks account 1 and requests account 2.
- Transaction B locks account 2 and requests account 1.
- A waits for B, while B waits for A.
Neither transaction can finish without outside intervention. The database must detect the cycle and abort at least one transaction.
A deadlock in practice
Run the following setup once, then run the two transaction sections in separate database sessions. Pause after each first UPDATE so both sessions acquire their first lock.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12, 2) NOT NULL
);
INSERT INTO accounts (id, balance)
VALUES (1, 100.00), (2, 100.00);
-- Session A
BEGIN;
UPDATE accounts SET balance = balance + 10 WHERE id = 1;
-- After Session B updates account 2:
UPDATE accounts SET balance = balance - 10 WHERE id = 2;
COMMIT;
-- Session B
BEGIN;
UPDATE accounts SET balance = balance + 20 WHERE id = 2;
-- After Session A updates account 1:
UPDATE accounts SET balance = balance - 20 WHERE id = 1;
COMMIT;The second update in one session waits. After the database detects the cycle, one transaction usually receives a deadlock error and rolls back. The other transaction can then continue.
The exact error and detection delay depend on the database system. A lock timeout is different from deadlock detection: a timeout may abort a transaction simply because it waited too long, even when no cycle exists.
Avoiding deadlocks
The most effective prevention is to acquire locks in a consistent order. If every transfer locks the account with the smaller ID first, two transfers cannot form the opposite-order cycle.
BEGIN;
-- Always lock accounts in ascending ID order.
SELECT id, balance
FROM accounts
WHERE id IN (1, 2)
ORDER BY id
FOR UPDATE;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;Other practices reduce the chance and cost of deadlocks:
- Keep transactions short.
- Access tables and rows in a documented order.
- Do not wait for network requests or user input inside a transaction.
- Lock only the rows that the transaction needs.
- Add indexes so updates find target rows efficiently.
- Avoid mixing multiple independent workflows in one transaction.
Retrying safely
A deadlock victim loses its uncommitted changes. Application code should catch the database's deadlock or serialization error, wait briefly, and retry the entire transaction from the beginning. Do not retry only the failed statement, because the transaction may already be aborted or its earlier assumptions may no longer hold.
Use a small retry limit and randomized backoff. Log the failure without exposing sensitive data. If retries continue to fail, report an operational error instead of looping forever.
Exercise
Transaction A locks row 1 and then requests row 2. Transaction B locks row 2 and then requests row 1. What caused the deadlock, and what design change is the simplest prevention?
Show answer
Each transaction held a lock needed by the other, creating a cycle. Make both transactions lock rows in the same order, such as ascending primary-key order.