Sub topic 8
Avoiding Deadlocks in Application Code
Prerequisites and the main rule
This chapter assumes that you know basic SQL, transactions, primary keys, foreign keys, and how to use two concurrent PostgreSQL sessions.
A deadlock occurs when transactions wait for one another in a cycle. The most reliable prevention is consistent lock ordering: every transaction must lock shared resources in the same order.
For example, a money transfer needs two account rows. If every code path locks the account with the smaller ID first, transactions queue instead of forming a cycle.
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;The ORDER BY id is important. Without it, PostgreSQL is free to acquire row locks in another order. Apply the same ordering rule to transfers, batch updates, inventory reservations, and any operation that touches multiple rows.
Keep transactions short
Locks acquired by a transaction normally remain until COMMIT or ROLLBACK. A transaction should therefore do only the work that must be atomic.
Do not hold database locks while you:
- Call an external service.
- Wait for user input.
- Process a large file.
- Perform slow calculations.
- Sleep or retry inside the transaction.
Instead, gather external data before the transaction when possible. Then begin the transaction, lock the required rows, change the data, and commit quickly.
A shorter transaction reduces both the time other sessions wait and the chance that it will overlap with another transaction holding a conflicting lock.
Choose and document a lock order
Lock ordering can be based on a stable value such as:
- Numeric primary key.
- Alphabetical resource name.
- Account ID followed by ledger ID.
- Parent table before child table.
Document the rule near the data-access code. A later feature can reintroduce deadlocks if it locks the same resources in the opposite order.
For example, these two operations are unsafe if they run concurrently:
- Transaction A locks account 1, then account 2.
- Transaction B locks account 2, then account 1.
A safe design makes both operations lock account 1 and then account 2, even when the business operation moves money in the opposite direction.
Retry transient failures
Good ordering prevents most deadlocks, but it cannot prevent every conflict. PostgreSQL detects a deadlock and aborts one transaction with SQLSTATE 40P01. Serializable transactions can also fail with SQLSTATE 40001.
The application must retry the entire transaction, not only the failed statement. A retry should use a limit and a small backoff so that a busy system does not create an endless retry storm.
| Failure | Application response |
|---|---|
| `40P01` deadlock detected | Roll back and retry the whole transaction |
| `40001` serialization failure | Roll back and retry the whole transaction |
| Constraint violation | Usually fix the input; do not blindly retry |
Never continue using a transaction after PostgreSQL reports an error. The transaction is aborted until it is rolled back.
Test concurrent code deliberately
Run the same operation in multiple sessions. Add a controlled pause after the first lock to expose ordering mistakes. In production, log the SQLSTATE, operation name, retry count, and transaction duration. Avoid logging sensitive values.
Prevention is better than retrying. Use retries as a safety net for short, idempotent operations whose effects can be safely repeated.
Exercise
Two transactions update the same two accounts. What single design rule most directly prevents a deadlock?
Show answer
Make both transactions acquire the account row locks in the same stable order, such as ascending account ID, and retry the whole transaction if PostgreSQL still reports SQLSTATE 40P01.