A deadlock report names a victim, which is a slightly unfair way to begin: the aborted transaction is often only half the story. Another transaction held a resource the first needed while waiting for a resource the first held. The loop, rather than either worker alone, is the problem to untangle.
A deadlock is a cycle of conflicting waits between transactions. PostgreSQL detects such a situation and aborts one participant so the others can proceed. Its locking documentation explains that the choice of which transaction is aborted is not something an application should rely on. The aborted transaction needs appropriate error handling; the database cannot decide whether the business operation should be retried.
That distinction matters. Retrying can be correct, but only if the application knows which operation it is repeating and what happened outside the transaction. A deadlock error is not permission to resend an email, payment or shipment without checking the surrounding workflow.
Draw the circle before changing a setting
Use a fictional warehouse with two rows, A and B. Transaction one updates A and holds its row lock. Transaction two updates B and holds that lock. Now transaction one asks to update B and waits. Transaction two asks to update A and waits. The picture is A → transaction one → B → transaction two → A: each participant is waiting for a lock held by another participant in the cycle.
If one transaction were simply waiting for a long-running transaction to finish, there might be blocking without a deadlock. Waiting can still hurt users and exhaust a connection pool, but it calls for a different diagnosis. A cycle is the defining feature here. An application timeout, a slow query or a connection error does not by itself prove that a deadlock occurred.
PostgreSQL can resolve the cycle by aborting a transaction. Which work rolls back depends on the transaction boundary and application behavior. Capture the error, transaction identifiers where available, time and safe diagnostic context. Avoid logging secrets or private customer records merely to get a larger incident artifact.
Consistent order removes one common route to a cycle
Suppose every worker that needs both A and B updates A first, then B. One worker may still wait for A, but it cannot hold B while waiting for A if it follows that order. Once the first transaction completes, the next can continue. This is the intuitive reason PostgreSQL recommends acquiring locks on multiple objects in a consistent order where practical.
The order must cover all code paths that touch the same resources. Sorting IDs in one endpoint does not help if a scheduled job updates the rows in the reverse order. Triggers, foreign-key checks and operations on related tables can introduce locks that are less obvious than the two statements visible in a service method. Build the ordering rule from the actual transaction and test it against concurrent activity.
Consistent ordering is not a promise that all lock contention disappears. Two workers may legitimately need the same row and one may wait. Nor should a team broaden locks without understanding throughput and consistency consequences. The aim is to prevent a particular circular wait while preserving the correctness of the operation.
Now add a reservation row.
Imagine the warehouse application also keeps a reservation row. A worker updates inventory A, then the reservation, then inventory B. A second service updates the reservation first and then inventory A. Sorting the two inventory IDs alone cannot solve every possible cycle because the reservation is another lockable resource. The team needs a shared ordering rule that accounts for both kinds of row and the actual statements that touch them.
That rule must be documented in terms developers can apply. “Always lock things in the same order” is hard to enforce when one library loads rows individually, another uses a bulk update and a trigger touches an additional table. An investigation should identify the order the database actually acquires locks, not just the order of IDs in a request. A test that runs the two code paths together can reveal whether the proposed rule holds under the real query shape.
Where every path cannot share an order, retain a bounded retry strategy and measure how often it fires. A rare retry can be an acceptable part of a correct concurrent design; repeated aborts that consume the entire pool deserve a deeper change. Agree on that operational threshold with the people who own the affected service and its correctness requirements.
Keep the lock-holding interval small
A transaction that waits for a human response or an external service while holding database locks gives other transactions more time to collide with it. Move work outside the transaction where correctness permits, and keep the protected section focused on the data that must change together. That does not mean splitting every operation into separate commits: doing so can destroy the atomicity the business rule needs.
For example, validating a user’s request before opening a transaction may be reasonable if the validation does not depend on data that can change. Checking an account balance and updating it as if no other operation can intervene is a different matter. The boundary should follow the invariant, not a target number of milliseconds.
PostgreSQL documents that a transaction waiting on a conflicting lock can wait until that conflict is released when no deadlock is detected. Timeouts and monitoring can help bound or identify long waits, but a timeout is not a repair for the transaction pattern that caused them. Measure the duration and frequency of waits alongside user-visible failures.
Identify the database error before retrying
PostgreSQL assigns SQLSTATE 40P01 to deadlock detected. Its error-code reference recommends testing the code rather than relying on the text of a message, which can vary by version or language. The application’s database driver determines how that code is exposed; check the driver’s documentation rather than assuming a particular property name.
Do not classify every failed request as a deadlock. PostgreSQL lists 40001 separately for a serialization failure, and a connection failure can leave a different question about what completed. Identify the actual error and transaction state, then apply the business operation’s bounded recovery rules. If the outcome of an external action or a commit is unknown, reconcile it before repeating the action.
Retry the whole unit, not a convenient line
After PostgreSQL aborts a transaction because of a deadlock, application code should handle the failure at the transaction boundary. A retry that repeats only the final SQL statement may run without the earlier reads and writes that gave the statement meaning. The appropriate recovery is usually to start the intended transaction again from a clean state, subject to the application’s business rules.
Use bounded retries and controlled delay rather than an endless loop. If two identical workers retry in perfect synchrony, they can collide repeatedly. A short randomized spread can reduce synchronized attempts, but it does not replace a fix for recurring lock-order problems. Record retry counts and surface a failure when the limit is reached.
External side effects need particular care. If the application charged a card outside the database transaction and then the database transaction aborted, blindly repeating the entire application request could charge twice. A transactional record, stable operation identifier and provider-supported idempotency mechanism may be part of a sound design, but each system’s actual contract controls. Our idempotency guide separates a repeated request from a repeated business action.
Look at the transaction, not only the victim
The error appears in one worker because PostgreSQL aborted that participant; the other side of the cycle is equally relevant to diagnosis. Review the database’s deadlock report and the application operations active at the same time. Identify the resources requested, the statements involved, the order of acquisition and whether a common code path appears across incidents.
Reproduce the pattern in a safe nonproduction environment with representative concurrency and bounded test data. A single successful run cannot prove the cycle is gone. A useful check runs the competing operations repeatedly, confirms the intended data invariant and observes whether deadlocks or long waits remain. Keep the test isolated from real orders, customer messages and payments.
If the fix changes transaction isolation or lock scope, review its consequences separately. Isolation levels control what concurrent transactions can observe and which anomalies must be handled; they are not interchangeable performance switches. The isolation guide explains why a stronger guarantee can also require retries.
Leave an incident note that the next engineer can use.
Write down the affected operation, approximate time window, frequency, observed error and the user-visible effect. Then add the two or more transaction paths, their lock order and the confirmed change. Separate what the database report actually showed from a suspected trigger. If the evidence is incomplete, say so; a plausible diagram is not a reconstruction of a specific incident.
After a release, watch both the deadlock rate and the backlog or wait time for the same workload. A change that removes the error by serializing all work may create a new throughput problem. Conversely, a faster transaction that no longer protects a required inventory constraint is not an improvement. A lock-order rule that protects the inventory invariant and lets both orders finish is worth more than an error chart with a flat line.
Explore Infinite Upside
For Vijay Sheth’s personal accounts, read Infinite Upside: Building Wealth With Room to Live, published by Sheth Capital, Inc.
Explore a related guide
What Does Database Transaction Isolation Change?