Independent technical referenceOfficial site
  • Software and digital services
  • Databases

40P01

PostgreSQL 40P01 deadlock_detected: transaction lock cycle

Verified with sources3 sourcesReviewed Oct 19, 2026
Technician coming? See the 2 steps they must show you
Trace

Risk level

High

Professional inspection is recommended.

Urgency

Medium

Quick answer

PostgreSQL returns 40P01 (deadlock_detected) when two or more transactions wait on each other's table or row locks and the server aborts one to break the cycle. Check the server deadlock log to see which statements collided, then issue ROLLBACK and retry the whole transaction.

Safety first

Stop and check this first

  • Never disable foreign key constraints, triggers, or row locking protections to work around 40P01, and never rely on PostgreSQL aborting a specific transaction because victim selection is not predictable.
  • Do not attempt to hold database transactions open while waiting for user input or slow external APIs; so long as no deadlock cycle exists, a transaction seeking a table or row lock waits indefinitely for conflicting locks to be released.

Safe checks you can perform

  • Extract the conflicting process IDs, relations, and queries from the server log
  • Inspect live lock waits and database deadlock counters in system views
  • Check how the victim session handles ROLLBACK and transaction retry

Leave these tasks to a qualified professional

  • Do not attempt this professional task: Enforce consistent lock acquisition order and upfront restrictive lock modes
  • Do not attempt this professional task: Configure log_lock_waits and review deadlock_timeout with the DBA

What a technician must be able to justify

Technician visit

These are the steps they must carry out and show you. Tick them as they work: if steps are skipped, do not accept a part swap.

These are not instructions for opening or handling the equipment yourself. They are the checks that should support a technical conclusion.

  1. Enforce consistent lock acquisition order and upfront restrictive lock modes

    What they doHave the development team refactor conflicting transactions so every code path locks tables and rows in the same deterministic order (for example, sorting primary keys before multi-row UPDATE or DELETE) and acquires the most restrictive lock mode needed for an object first.

    They must show youthe sorted query or transaction diff and load-test results demonstrating that concurrent runs complete without 40P01.

    In writingthe canonical table and row locking order adopted for the affected workflows and the transaction retry policy.

  2. Configure log_lock_waits and review deadlock_timeout with the DBA

    What they doHave the DBA enable log_lock_waits and verify deadlock_timeout (one second by default) so lock waits exceeding the threshold are logged with full context before or during deadlock resolution.

    They must show youthe output of SHOW deadlock_timeout, SHOW log_lock_waits, and the pg_stat_database.deadlocks trend before and after deployment.

    In writingthe exact configuration settings applied and the monitoring alert threshold for database deadlocks.

Before accepting a part or repair

Nothing has been shown yet. Do not accept a part swap based on the code alone.

Follow these steps

Note: Follow the documented order. An error code identifies the affected system, but it does not prove by itself which part has failed.

  1. Extract the conflicting process IDs, relations, and queries from the server log

    Tools required

    Who:
    Your DBA or developer with read access to PostgreSQL server logs.
    How:
    Locate the 40P01 deadlock report in the PostgreSQL log around the incident timestamp and redact any literal passwords, tokens, or personal data before copying the query text.
    Result that matters:
    The exact Process IDs, lock modes (such as ShareLock or ExclusiveLock), target tables or tuple identifiers, and SQL statements for each transaction in the cycle.
    If the log shows two UPDATE or DELETE statements touching the same table rows in reverse key order, that confirms an application row-ordering mismatch as the direct trigger.
    If the log shows DDL or maintenance commands holding ACCESS EXCLUSIVE or SHARE locks against multi-step DML transactions, that points to uncoordinated schema or index operations.
    Evidence to keep:
    Save the redacted deadlock log block showing each process ID, lock mode, and statement.

    Never share raw server logs containing unredacted customer fields or connection secrets; perform log inspection read-only.

    Evidence: PostgreSQL 18 Appendix A: Error Codes · PostgreSQL 18 explicit locking · PostgreSQL 18 lock management settings

  2. Inspect live lock waits and database deadlock counters in system views

    Tools required

    Who:
    Your DBA or developer querying read-only catalog and statistics views.
    How:
    Query pg_locks joined with pg_stat_activity where wait_event_type = 'Lock' and check the deadlocks column in pg_stat_database plus SHOW deadlock_timeout.
    Result that matters:
    Whether active backends are currently blocked on relation or tuple locks and whether pg_stat_database.deadlocks is climbing.
    If pg_stat_activity shows sessions in state idle in transaction holding granted locks in pg_locks while active queries wait, that isolates stalled client transactions as the blocker.
    If pg_stat_database shows isolated deadlock increments only during a specific batch job, that indicates contention is confined to that workload rather than server-wide saturation.
    Evidence to keep:
    Record the pg_stat_database deadlocks count, the output of SHOW deadlock_timeout, and any waiting pid and wait_event rows from pg_stat_activity.

    Do not attempt to clear lock waits by sending SIGKILL to postgres processes or restarting the cluster abruptly.

    Evidence: PostgreSQL 18 SHOW · PostgreSQL 18 cumulative statistics system · PostgreSQL 18 explicit locking · PostgreSQL 18 lock management settings

  3. Check how the victim session handles ROLLBACK and transaction retry

    No special tools

    Who:
    Your application developer reviewing error handling for SQLSTATE 40P01.
    How:
    Verify in the application code that catching 40P01 triggers a clean ROLLBACK and, where on-the-fly handling is needed, replays the entire transaction from the start.
    Result that matters:
    Whether the aborted transaction is rolled back completely before the connection is reused or retried.
    If the session reuses the connection without issuing ROLLBACK after 40P01, that confirms subsequent statements on that connection will fail with 25P02.
    If the handler rolls back and retries the complete unit of work with consistent lock ordering, that rules out broken client recovery.
    Evidence to keep:
    Keep the application exception trace and the transaction retry handler snippet.

    Evidence: PostgreSQL ROLLBACK · PostgreSQL 18 serialization failure handling · PostgreSQL 18 explicit locking

Still not solved

If the error persists, stop here. See what the technician must do and show you.

Virtual technician

Does 40P01 still appear after these checks?

This guided flow uses the exact code and your answers to choose a test, an expected result and the next branch.

Where this code applies

A code is meaningful only inside the right product and version context.

Primary scope

System
Software and digital services
Brand
PostgreSQL
Product type
Databases

Known code variants

  • deadlock_detected
  • PostgreSQL 40P01
  • SQLSTATE 40P01

What it means

Appendix A assigns 40P01 to deadlock_detected under Class 40, Transaction Rollback. When a session waits on a table-level or row-level lock longer than deadlock_timeout (one second by default), the lock manager checks whether waiting transactions have formed a dependency loop and aborts one victim transaction so the others can proceed. Deadlocks occur even without explicit LOCK TABLE statements whenever concurrent UPDATE, DELETE, or SELECT FOR UPDATE commands lock rows in opposite orders. Code 40P01 reflects a lock ordering collision and never proves by itself that the PostgreSQL server or disk subsystem is defective.

Warnings and stop conditions

  • Highsource verified

    Never disable foreign key constraints, triggers, or row locking protections to work around 40P01, and never rely on PostgreSQL aborting a specific transaction because victim selection is not predictable.

    Evidence: PostgreSQL 18 explicit locking

  • Mediumsource verified

    Do not attempt to hold database transactions open while waiting for user input or slow external APIs; so long as no deadlock cycle exists, a transaction seeking a table or row lock waits indefinitely for conflicting locks to be released.

    Evidence: PostgreSQL ROLLBACK · PostgreSQL 18 explicit locking

Symptoms and causes

Probable causes · in order

  • Concurrent transactions locking rows or tables in inconsistent orderCommon

    When one transaction locks object or row A and then waits for B while a second transaction holds B and waits for A, neither session can advance until PostgreSQL aborts one with 40P01.

    Evidence: PostgreSQL 18 Appendix A: Error Codes · PostgreSQL 18 explicit locking

  • Lock escalation within a transaction from a weak lock mode to a stronger modePossible

    Acquiring a less restrictive lock on an object early in a transaction and later requesting a more restrictive lock mode on the same object while another session also holds a shared lock creates mutual waiting.

    Evidence: PostgreSQL 18 explicit locking

  • Long-running transactions holding row or table locks open across multiple stepsPossible

    Keeping transactions open for extended periods, such as while waiting for external network calls or user input, prolongs row-level and table-level locks and multiplies the chance of cyclic lock waits.

    Evidence: PostgreSQL 18 explicit locking · PostgreSQL 18 lock management settings

Sources and technical references

  1. 1

    PostgreSQL 18 Appendix A: Error Codes

    PostgreSQL Global Development Group · 2026 · official_doc

  2. 2

    PostgreSQL transaction isolation

    PostgreSQL Global Development Group · 2026 · official_doc

  3. 3

    PostgreSQL ROLLBACK

    PostgreSQL Global Development Group · 2026 · official_doc

Sources: PostgreSQL 18 Appendix A: Error Codes · PostgreSQL transaction isolation · PostgreSQL ROLLBACKreviewed 2026-10-19 · verified

Was this entry useful?