Sub topic 7
How PostgreSQL detects and resolves deadlocks
This chapter assumes you can run two concurrent psql sessions, know BEGIN, COMMIT and ROLLBACK, and have read the previous chapter on how a deadlock forms. Here you will see what PostgreSQL does after a cycle of waits exists: when it looks for the cycle, how it chooses a victim, what the error and the log say, and what your application must do afterwards.
Why a deadlock needs detection
A deadlock is a cycle of sessions where each one waits for a lock held by the next. No session in the cycle can make progress, because the lock each one needs is released only at the end of a transaction that is itself stuck. Waiting longer never resolves it.
PostgreSQL does not prevent such cycles in advance. It lets sessions wait for locks and checks for a cycle only if a wait lasts long enough. This keeps the common case cheap. Most lock waits are short and end when the holder commits, so running a graph search on every wait would waste work.
The deadlock_timeout setting
When a session has to wait for a lock, it sleeps and sets a timer. If the lock is granted before the timer fires, nothing else happens. If the timer fires first, the session runs the deadlock check.
The timer length is the deadlock_timeout setting. The default is 1s.
SHOW deadlock_timeout;Two points are easy to get wrong.
deadlock_timeoutis not a limit on how long a session may wait. It is only the delay before the check runs. A session waiting on a legitimate long transaction keeps waiting after the check finds no cycle.- The check runs in the waiting session itself. There is no separate deadlock-detector process.
Raising the value reduces wasted checks on a server with many short lock waits, but it makes real deadlocks take longer to resolve. Lowering it resolves deadlocks sooner but adds checking overhead. Most systems keep the default. Changing it needs superuser privileges, or a role that has been granted the right to set it, because a bad value can hurt the whole server.
What the check does
The check builds a picture of who waits for whom, called a wait-for graph. Each session is a node. An edge from A to B means A is waiting for a lock that B holds, or that B is queued ahead of A for.
The last point matters. PostgreSQL also counts waiters ahead in the lock queue as blockers, because a request cannot be granted ahead of a conflicting request that is already waiting. This is why a cycle can include sessions that are blocked only by queue position.
If the search starting from the current session finds a path that leads back to itself, a deadlock exists. If it does not, the session goes back to waiting.
For some cycles, PostgreSQL tries a rescue before aborting anything. Soft deadlocks, where reordering the wait queue could break the cycle, are resolved by rearranging waiters. Most cycles you will meet in application code are hard deadlocks, with no reordering that helps, so one transaction must be aborted.
Which transaction is the victim
The session whose timer fires first and finds the cycle aborts its own transaction. In practice this is usually the session that began waiting last in the cycle, since its timer started later than the others. This is not a promise. Timers and scheduling vary, so you cannot rely on a particular session being the victim.
All other sessions in the cycle continue as soon as the victim's locks are released by the rollback.
Reproducing it
Create the table and run the two sessions in order. This repeats the setup from the earlier chapter, so the output below is concrete.
CREATE TABLE accounts (
id int PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts VALUES (1, 100), (2, 100);
-- 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, so a cycle forms)
UPDATE accounts SET balance = balance + 10 WHERE id = 1;
-- After deadlock_timeout (default 1s), one session fails with:
-- ERROR: deadlock detected (SQLSTATE 40P01)Within about a second, one of the two sessions fails. The other session's blocked UPDATE completes immediately.
Reading the error and the server log
The client receives an error similar to this:
ERROR: deadlock detected
DETAIL: Process 4121 waits for ShareLock on transaction 8830; blocked by process 4140.
Process 4140 waits for ShareLock on transaction 8829; blocked by process 4121.
HINT: See server log for query details.
CONTEXT: while updating tuple (0,1) in relation "accounts"The server log contains the same text plus the statements involved, which is why the hint points you there. Read it as follows.
- Each
Process N waits for ... blocked by process Mline is one edge in the wait-for graph. Together the lines form the cycle. ShareLock on transaction 8830means the process is waiting for that transaction to finish. Row-level waits show up this way, because a waitingUPDATEwaits on the transaction ID of the session that changed the row.- The
CONTEXTline names the table and the row version being touched when the wait began. - The log also shows the query text of each process, so you can see which two statements collided.
Make sure log_lock_waits is considered as well. When it is on, PostgreSQL logs any wait that exceeds deadlock_timeout, even when no deadlock results. That gives you early warning about long lock waits before they become incidents. It is off by default.
ALTER SYSTEM SET log_lock_waits = on;
SELECT pg_reload_conf();What the victim's transaction looks like afterwards
The error aborts the whole transaction, not just the failing statement. Until the client issues ROLLBACK, every further command in that session fails with current transaction is aborted, commands ignored until end of transaction block.
Every change the victim made is undone, and all its locks are released. The surviving sessions then proceed. A session that retried a statement inside the aborted transaction would only get the aborted-transaction error, so the retry must start a new transaction.
Handling the error in application code
Because PostgreSQL resolves the deadlock by aborting one transaction, your application must expect SQLSTATE 40P01 (deadlock_detected) and retry. The error is transient: the same transaction usually succeeds when run again, since the other session has finished.
A safe retry has these properties.
- Retry the whole transaction, from
BEGIN, not just the last statement. - Re-read any data the transaction used to make decisions, because it may have changed.
- Limit the number of attempts, for example three to five.
- Wait a short random delay before each retry, so two sessions do not collide again in step.
- Make sure the transaction has no side effects outside the database, such as sending email, before it commits. Otherwise a retry repeats them.
This Python example uses psycopg 3 and follows those rules.
import random
import time
import psycopg
from psycopg import errors
MAX_ATTEMPTS = 4
def transfer(conninfo: str, src: int, dst: int, amount: int) -> None:
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
with psycopg.connect(conninfo) as conn:
with conn.transaction():
conn.execute(
"UPDATE accounts SET balance = balance - %s WHERE id = %s",
(amount, src),
)
conn.execute(
"UPDATE accounts SET balance = balance + %s WHERE id = %s",
(amount, dst),
)
return
except errors.DeadlockDetected:
if attempt == MAX_ATTEMPTS:
raise
time.sleep(random.uniform(0.05, 0.2) * attempt)Retries treat the symptom. Frequent 40P01 errors mean the code takes locks in inconsistent orders, and the next chapter covers how to fix that at the source.
Deadlocks that PostgreSQL cannot see
The detector only knows about locks that PostgreSQL manages. If the cycle includes something outside the database, no error is raised.
- An application thread that holds a database lock while waiting for a lock in your own code, such as a mutex, which is in turn held by a thread waiting for the database.
- Two services that each hold a transaction open while calling the other over HTTP.
In these cases sessions just wait. The tools that help are timeouts, which are covered in a later chapter: lock_timeout for lock waits and idle_in_transaction_session_timeout for sessions that sit idle with open transactions.
Cases that look like deadlocks but are not
Not every stuck session is a deadlock. Use this table to tell the cases apart.
| Situation | Cycle of waits? | What PostgreSQL does |
|---|---|---|
| Two sessions update rows in opposite order | Yes | Aborts one with `40P01` after `deadlock_timeout` |
| A session waits on another that is idle in transaction | No | Waits indefinitely unless a timeout is set |
| A long query holds a table lock and others queue behind it | No | Waits, forming a blocking chain |
| A migration waits for an old transaction and queues new queries | No | Waits, the queue grows |
In the last three rows there is a single chain with a blocker at the head that is not itself waiting. Detection finds no cycle, so no victim is chosen. You must find the head of the chain, which the chapter on inspecting locks covers.
Checking for deadlocks over time
PostgreSQL counts deadlocks per database. This lets you see whether the problem is occasional or constant.
SELECT datname, deadlocks
FROM pg_stat_database
WHERE datname = current_database();The counter only goes up, so sample it periodically and look at the rate of change. A handful per day on a busy system is often tolerable when the application retries correctly. A steady stream deserves a code fix.
Summary of the mechanism
- A session cannot get a lock and starts waiting.
- After
deadlock_timeout(default 1 second) it runs the check on the wait-for graph. - If the graph has a cycle that includes it, the session aborts its own transaction with SQLSTATE
40P01. - The abort releases the victim's locks, so the others proceed.
- The application retries the whole transaction.
Exercise
Two sessions deadlock. Session 2 receives ERROR: deadlock detected and session 1's blocked UPDATE then completes. (a) Why did the error not appear instantly when the cycle formed? (b) Session 2 now sends another UPDATE without any other command and gets "current transaction is aborted". What must it do, and what should a retry include?
Show answer
(a) PostgreSQL only runs the deadlock check after a lock wait lasts deadlock_timeout, which is 1 second by default, so most short waits never pay for the check. (b) It must issue ROLLBACK to end the aborted transaction. A retry should rerun the whole transaction from BEGIN, re-read any data it depends on, limit the number of attempts, and use a short random delay between attempts.
Exercise
A migration has been waiting 30 seconds for a lock on a table, and new queries on that table are piling up behind it. Will PostgreSQL abort anything after deadlock_timeout passes? Explain.
Show answer
No. The check runs, but it finds no cycle. The migration waits behind a long-running transaction that is not itself waiting for anything, so the waits form a chain, not a cycle. Without a cycle there is no victim. Setting lock_timeout on the migration, or ending the blocking transaction, resolves it.