A transfer endpoint may work for every isolated request and fail when two callers move resources in opposite directions. Each transaction can hold a lock the other needs. Diagnose the acquisition cycle before increasing timeouts or adding retries that leave the same conflict pattern intact.
The PostgreSQL 18 example uses two resource records with immutable numeric IDs. Trace the original acquisition cycle, then change both writers to a shared order. The exercise describes a controlled two-session test; canceling live database sessions belongs to the database owner's incident procedure.
Separate ordinary waiting from a dependency cycle
A lock wait does not necessarily indicate a deadlock. One transaction may simply be waiting for another to finish useful work. A deadlock involves a cycle: each participant waits for a resource held by another participant in that cycle.
The PostgreSQL locking documentation explains deadlock detection and the abortion of a participating transaction. It also notes that applications cannot reliably predict which participant will be selected. Design callers around a recoverable failed transaction rather than depending on a preferred winner.
For the synthetic transfer, use immutable resource IDs 10 and 20. Both operations transfer between the same pair, in opposite directions. The following conceptual two-session schedule exposes the cycle:
- Session A begins a transaction and acquires a row lock on resource 10.
- Session B begins a transaction and acquires a row lock on resource 20.
- A requests the lock on 20 and waits because B holds it.
- B requests the lock on 10 and waits because A holds it.
- PostgreSQL detects the cycle and aborts a participant's transaction. The other can then progress.
At step 3 there is only a wait; at step 4 there is a cycle. The application should identify the resulting database error by SQLSTATE 40P01, roll back the failed transaction through its driver, and decide whether the entire operation can be retried. It must not continue issuing business writes inside the failed transaction.
Preserve sanitized diagnostic evidence before retrying repeatedly. Record the operation type, database error classification, and timing needed to correlate the event in a controlled diagnostic system. Avoid copying raw statement parameters or user data into a public incident summary.
Trace the full transaction path
Inspect the application path from transaction start to commit. Include implicit database work performed by constraints, triggers, cascading operations, and framework behavior. The order of explicit application statements may not describe every lock acquisition relevant to the cycle.
Compare both participants' paths. A background reconciliation job can conflict with an interactive request even when each uses a consistent order internally. The required protocol must be shared across all writers that can touch the same resource set.
Separate long transaction duration from acquisition order. A remote HTTP call inside the transaction may extend how long a lock is retained without being the original cause of the cycle. Remove unnecessary waiting where the business semantics allow it, while preserving the atomic local change.
Use the smallest synthetic fixture that still reproduces the conflict. Include the actual constraints and triggers that influence locking. A simplified table without the relevant foreign key can make a proposed fix appear effective while leaving the deployed behavior unexplained.
Establish a stable acquisition order
For transfers between known resource records, acquire the required locks in a shared canonical order, independent of transfer direction. With IDs 10 and 20, both operations acquire 10 first, then 20. If A holds 10, B waits before holding 20, allowing A to acquire 20 and finish. That removes the reproduced two-row cycle.
Implement the two-record protocol with explicit ordered lock acquisitions after validating and deduplicating the IDs. A self-transfer should be rejected or handled as a separately defined no-op. If either resource is missing or unauthorized, roll back rather than applying one side. Lock selection order and update direction are different: the A-to-B and B-to-A business operations still debit and credit their respective source and destination after both locks are held.
Do not infer this protocol from an ORM call containing an unordered set of IDs. Inspect the emitted statements and their behavior. For larger sets, decide how ordering is enforced and tested; the row order visible in a result is not a universal guarantee about every lock acquired by triggers, foreign keys, or concurrent changes.
Define the order precisely. If identifiers have multiple representations, normalize them through the same validated application type before comparison. If records span resource classes, document an order across classes as well as within each class. An ambiguous instruction to lock consistently is hard to verify.
Treat this as a coordination rule, not a claim that sorting arbitrary queries prevents every deadlock. Database plan choices, newly introduced writes, and other lock types can alter the interaction. Check the actual acquisition paths and retain deadlock recovery even after addressing a known cycle.
Review batch operations separately. A job that touches hundreds of resources can hold a broader lock set than a two-record transfer. Choose bounded batches and a clear transaction scope so one maintenance operation does not unnecessarily block ordinary traffic for its entire run.
Recover the failed transaction without repeating side effects
Classify deadlock failures from the database's structured error information. The PostgreSQL retry guidance identifies SQLSTATE 40P01 for deadlock detection and advises care in deciding which errors warrant retry.
When retry is appropriate, rerun the complete business transaction with fresh reads. Bound attempts and total time. A transaction that repeatedly loses contention should eventually return a controlled retryable outcome rather than occupy application capacity indefinitely.
Do not repeat irreversible remote work as part of an automatic database retry. If the transfer also notifies another system, separate durable notification intent from the local transaction and use a supported downstream delivery protocol. Keep the transaction's database result distinct from the delivery result.
If the event is causing immediate user harm, follow the database owner's incident procedure for containment. Canceling an unfamiliar session can interrupt unrelated business work. Preserve evidence about the blocked operation and choose a target deliberately rather than turning a diagnostic guide into a bulk session-termination script.
Verify contention and recovery together
Use barriers in the integration harness instead of sleeps. The first barrier releases both sessions only after each has acquired its first lock in the original protocol. The second allows both to request the remaining lock. Observe a deadlock classification and the surviving transaction's outcome without asserting which session loses.
For the ordered protocol, the harness must change: B cannot reach a barrier after acquiring 10 while A still holds it. Waiting for both sessions at that point would deadlock the test harness itself. Instead, observe B waiting, let A acquire 20 and commit, then let B proceed. Assert the committed resource totals and each transfer's business result. This tests the repaired schedule without requiring an impossible synchronization point.
Create a repeatable integration exercise using independent sessions and synchronization at the two acquisition points. First demonstrate the original conflict in the isolated fixture. Then test both transfer directions under the proposed common order and inspect the final committed state.
Include a writer that initially violates the order, a canceled request, and a retry that exhausts its budget. Those cases verify the protocol boundary and user-visible failure behavior. A single successful concurrent run does not establish that all schedules are covered.
Track deadlock frequency alongside transaction duration and lock-wait signals using bounded operation labels. If deadlocks decline but long blocking grows, investigate whether the change merely serialized too much work. The connection budget guide helps assess the application capacity consumed by waiting transactions.
Keep the original and repaired schedules with the regression fixture. When a new maintenance writer, trigger, or resource class is introduced, use those schedules to review the acquisition order again. A lower deadlock count is useful operational evidence, but the fixture explains which specific cycle the change removed.
Was this guide useful?
Your rating helps us prioritize clearer, more practical technical content.
Review diffs, run checks, and prepare the release in Arezgit.
Keep Git review, security scanning, API checks, database inspection, and release preparation together in one local desktop application.
Explore Arezgit