CRE-2025-0042
PostgreSQL transaction fails with deadlock detected error in psycopg2 and DjangoCriticalImpact: 7/10Mitigation: 5/10
CRE-2025-0042View on GitHub
Description
- Applications using Django with PostgreSQL and psycopg2 may encounter `deadlock detected` errors under concurrent write-heavy workloads.
- PostgreSQL raises this error when two or more transactions block each other cyclically while waiting for locks, and one must be aborted.
- Django surfaces this as an `OperationalError`, and the affected transaction is rolled back.
Cause
A deadlock occurs when multiple transactions acquire locks in different orders, causing a cycle that PostgreSQL''s deadlock detector resolves by aborting one transaction. This is more likely during bulk inserts, updates with overlapping WHERE clauses, or transactions accessing rows in inconsistent order.
Mitigation
- Ensure that transactions access rows in a consistent order across code paths.
- Break large transactions into smaller units of work.
- Use explicit `select_for_update()` to control locking behavior and reduce contention.
- Monitor PostgreSQL `pg_stat_activity` and `pg_locks` to identify deadlock-prone queries.