dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Home/Error Library/postgresql-deadlock-detected
PostgreSQL
PostgreSQL 14–18Locks & Concurrency
8 min read
ERROR: deadlock detected

PostgreSQL "deadlock detected" — Which Two Transactions Locked Each Other?

Investigating PostgreSQL deadlock cycles, tracing lock trees via pg_blocking_pids(), enabling log_lock_waits, ordering multi-row UPDATEs, and application retry policies.

Reviewed by:Principal SRE & Lead Database Architect
Tested Versions: PostgreSQL 18.6 & 17.11 (Alpine Linux / Docker 29.7) | Tarihsel: PostgreSQL 14, 15, 16

Operational Verification & Reliability Metadata

Last Technical Review: 29 Ekim 2026
Tested VersionsPostgreSQL 18.6 & 17.11 | Tarihsel: PostgreSQL 14.10, 15.6, 16.4
Required Privilegespg_read_all_stats or SUPERUSER for inspecting pg_blocking_pids()
Risk Assessment
HighPostgreSQL forcibly terminates victim transaction with SQLSTATE 40P01 rollback
Expected OutputElimination of cyclic wait-for graphs via deterministic ORDER BY and log_lock_waits telemetries
Rollback Procedure:Exponential backoff with jitter on 40P01 retry loops at application layer
PostgreSQL Docs: Explicit Locking & Deadlocks
First 60 Seconds Emergency Protocol:

The error string is a symptom, not the root cause. Do not restart the server blindly. Run the diagnostic queries below to pinpoint the actual failure mode.

▸Symptoms

plaintext
ERROR: deadlock detected DETAIL: Process 4821 waits for ShareLock on transaction 9102; blocked by process 9102. Process 9102 waits for ShareLock on transaction 4821; blocked by process 4821. HINT: See server log for query details.

▸Diagnostic Query

sql
SELECT pid, pg_blocking_pids(pid) AS blockers, state, left(query, 100) AS query FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0;

Deterministic locking:

sql
UPDATE hesap SET bakiye = bakiye - 10 WHERE id IN (SELECT unnest(ARRAY[42, 17, 99]) ORDER BY 1);

Other Database Error Triage Playbooks

Other battle-tested diagnostic guides for high-severity database errors.

All Errors (50)