Database deadlocks: why they happen and how to recover
A deadlock is a cycle in which two or more transactions wait for locks held by one another, so none can proceed. Unlike ordinary lock contention, waiting alone cannot resolve a cycle. PostgreSQL detects the cycle, cancels one involved transaction, and lets the others continue. An application must be able to retry the canceled transaction safely.
How do two transactions block each other?
Suppose two transactions transfer money between accounts. Transaction A updates account 1 and then account 2. At the same time, transaction B updates account 2 and then account 1. A waits for the lock on account 2, while B waits for the lock on account 1. Because each is waiting for work that only the other transaction can finish, the wait forms a deadlock.
This does not require an explicit SELECT ... FOR UPDATE. PostgreSQL's UPDATE automatically takes the row locks it needs, so ordinary code can deadlock when it modifies multiple rows in different orders.
-- Transaction A: account 1, then account 2
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 10 WHERE account_id = 2;
COMMIT;
-- Concurrent transaction B: reverse order
BEGIN;
UPDATE accounts SET balance = balance - 20 WHERE account_id = 2;
UPDATE accounts SET balance = balance + 20 WHERE account_id = 1;
COMMIT;This hypothetical flow illustrates concurrency; it was not run against a database. If both transactions finish their first UPDATE and then reach the second at overlapping times, each may wait for the other's row lock. Real money-transfer code needs additional balance, currency, and business-rule handling, so this example should not be copied as an implementation.
What does the database do when a deadlock occurs?
PostgreSQL checks whether lock waits form a deadlock and, when it finds a cycle, aborts one of the involved transactions. The application must not predict or depend on which transaction is chosen. The error SQLSTATE is 40P01 (deadlock_detected). Classifying by SQLSTATE is more reliable than matching a message whose language or wording can vary.
Changes made earlier in the canceled transaction are rolled back too. Do not retry only the failed UPDATE: start the transaction again and repeat its reads, decisions, and writes. Limit retry attempts and use a short randomized delay (backoff) to reduce the chance that simultaneous retries collide in the same pattern. If retries keep failing, return the error normally and retain useful diagnostic information.
An email, external payment, or message sent directly from inside a transaction cannot be rolled back. Retrying may therefore repeat that side effect. Separate such work from transaction retries and consider idempotency keys, a transactional outbox, or deduplication. These patterns do not remove every duplicate automatically; review consumer behavior and recovery paths too.
The main prevention: use a consistent lock order
When a transaction locks several rows or objects, make every code path acquire them in the same order. Updating in ascending order of a stable key, such as account ID, avoids the specific competition where A locks 1 then 2 while B locks 2 then 1. If request input can arrive in different orders, sort it before updating.
| Situation | Prevention or response |
|---|---|
| Updating several rows | Lock in one stable order, such as primary-key order, in every request. |
| A transaction waits on user input or the network | Finish the transaction before waiting; reduce lock-holding time. |
| Read-then-update logic races | Prefer a conditional UPDATE or constraint for atomicity; use row locks only when needed. |
| A deadlock cannot be fully avoided | Retry the whole transaction a limited number of times on 40P01; prevent duplicate side effects. |
| Waiting happens more often than expected | Inspect pg_locks, logs, and related queries to find long-held locks and contention. |
Consistent order lowers risk but does not guarantee that deadlocks disappear. Triggers, foreign-key checks, and code that updates other tables can add hidden locks. Keep transactions short and consider requesting the strongest needed lock mode first. Avoid unnecessarily broad or strong locks, which increase contention; use only what the actual invariant requires.
What does deadlock_timeout mean?
PostgreSQL does not repeat the relatively expensive deadlock check on every lock wait. deadlock_timeout is the time to wait before checking whether a wait is a deadlock. The PostgreSQL 18 documentation lists a default of one second. A larger value can reduce needless checks but delays reporting a real deadlock. When log_lock_waits is enabled, the setting also affects how long a lock wait must last before it is logged.
This is not a maximum allowed lock-wait duration. PostgreSQL performs a check at that point; if there is no deadlock, waiting may continue until the conflicting lock is released. To limit ordinary wait time, consider separate settings and handle their errors appropriately. First observe logs and pg_locks and assess the impact before changing server settings. No setting was changed and no database was observed for this article.
What should you check when a problem occurs?
Confirm that the application records and classifies SQLSTATE `40P01`, rather than relying on message text.
Confirm that it retries from the start only after the entire failed transaction has rolled back.
Use relevant transaction/query logs and `pg_locks` to identify the objects and acquisition order involved.
Check whether conflicting code paths lock multiple objects in different orders; standardize that order.
Verify concurrency behavior in a reproducible test environment, including retry limits and protection from repeated external side effects.
pg_locks shows current locks and waits. Once a deadlock has ended, its cycle may already be gone. To investigate the moment it occurred, preserve database logs together with the application's SQLSTATE and request correlation ID. This article does not report an investigation or test of a particular production incident.
Scope and sources
[PostgreSQL 18: Explicit Locking and Deadlocks](https://www.postgresql.org/docs/18/explicit-locking.html)
[PostgreSQL 18: Lock Management Settings and `deadlock_timeout`](https://www.postgresql.org/docs/18/runtime-config-locks.html)
[PostgreSQL 18: Lock Monitoring and `pg_locks`](https://www.postgresql.org/docs/18/monitoring-locks.html)
[PostgreSQL 18: Error Code `40P01`](https://www.postgresql.org/docs/18/errcodes-appendix.html)
The PostgreSQL 18 documentation was checked on 2026-11-22. The deadlock concept is general; detection, cancellation, settings, and the error code described here are PostgreSQL-specific. The account scenario is hypothetical and the SQL was not executed.