ERROR
database
concurrency_error
ai_generated
true
psycopg2.errors.DeadlockDetected: ERROR: deadlock detected
ID: database/deadlock-detected
85%Fix Rate
88%Confidence
55Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 16 | active | — | — | — |
Root Cause
Two or more transactions are waiting on each other's locks, creating a cycle. PostgreSQL detects this and aborts one transaction. Fixing requires consistent lock ordering or reducing transaction scope.
genericWorkarounds
-
88% success Ensure all transactions acquire locks in a consistent, deterministic order
Identify the tables and rows involved in the deadlock (check PostgreSQL logs for DETAIL). Refactor transactions so they always lock resources in the same order (e.g., always lock table A before table B, or lock rows by ascending primary key).
-
82% success Retry the aborted transaction with exponential backoff
Catch the deadlock exception (sqlstate 40P01) and retry the entire transaction with exponential backoff (e.g., 100ms, 200ms, 400ms). Limit retries to 3-5 attempts. This works when deadlocks are rare and caused by timing rather than systematic lock ordering issues.
Dead Ends
Common approaches that don't work:
-
Increasing deadlock_timeout to prevent deadlock detection
95% fail
deadlock_timeout only controls how long PostgreSQL waits before checking for deadlocks. Increasing it delays detection but does not prevent deadlocks. The deadlock still occurs; it just takes longer to report.
-
Simply retrying the failed transaction in a tight loop without any backoff or lock ordering changes
70% fail
Without addressing the root cause (inconsistent lock ordering), retries will frequently deadlock again, creating a retry storm that makes the problem worse under load.
Error Chain
Leads to:
Preceded by:
Frequently confused with: