# Deadlock

## What it is

A deadlock occurs when several operations each hold a resource and wait for
another member of the same group to release something. The requests form a
cycle. Two database transactions provide a small example. One has locked
inventory item A and needs item B. The other already holds B and needs A.
Neither operation can finish using its current sequence because the lock would
only be released by another operation that is also waiting.

The resource can be a row, a table, or another kind of lock. The same structural
problem appears in an application with several mutexes or in a workflow that
holds one shared resource while requesting another. In a database, the lock
types and their compatibility guide which requests can wait. A statement that
takes lock A might create a cycle through several transactions that are working
on different statements. Looking only at the last query issued by each
connection can miss the earlier statement that acquired its first lock.

PostgreSQL checks for cycles after a lock has been waiting long enough to
warrant the cost of a check. When it detects a database deadlock, it aborts a
transaction to let the other transactions proceed. Its error code for that
condition is `40P01`. Waiting for a busy item whose current holder can finish is
ordinary contention. That can still create a serious service problem if the
queue grows. Establish which pattern you have before choosing whether to change
ordering, reduce transaction time or cap the amount of concurrent work.

## Why it matters

A service can look healthy through thousands of individual calls and still have
a reproducible cycle once two operations overlap. The problem can appear only at
an unusual boundary, such as a background adjustment touching the same two
accounts as a user action. Each path looks reasonable on its own. The relative
order of acquired resources gives them a shared constraint that neither path can
enforce alone.

Deadlocks can trigger work after the initial incident. A worker may have
completed application calculations or a network request before the database
aborts its transaction. If several workers immediately repeat the same order and
timing, retries can increase pressure on the locks. Treat the retry as part of
the operation's design. Establish what gets repeated, which effects are durable,
when the client gives up, and what diagnostics remain available when the attempt
is abandoned.

Lock duration matters even where ordering prevents a cycle. Acquiring rows
consistently does little for a waiting buyer if the holder keeps those rows
locked while it calls a slow partner. A transaction boundary should give the
protected decision enough time to commit. Connection usage, queue length and the
time spent waiting on locks give useful evidence about whether the current
boundary suits the workload. Long tails and occasional deadlock errors can have
different causes even when the same route reports them.

## What it looks like in practice

Imagine stock items A and B are bundled in a sale, and a separate adjustment
process can also affect both. Record what each transaction touches as it runs.
In a test, let the sale lock A and the adjustment lock B. Then let each ask for
its second item. Confirm that the database detects the cycle and that whichever
transaction was aborted leaves no partial stock changes. Run the same schedule
with both paths acquiring keys in the same deterministic order. One transaction
should wait, then complete once the holder commits or rolls back. The test can
show that waiting remains possible and that the cycle is gone for these paths.

Engineer's
[engineering note on selling limited stock](/notes/selling-limited-stock-without-overselling/)
examines how much work happens while an inventory lock is held. Its advice to
move network calls out of the locked part of the transaction is relevant to both
testing and diagnosis. Real traffic will produce more useful lock reports when
the protected work has clear boundaries. The two-item example extends that
reasoning to a common bundle workflow.

For diagnosis, connect the wait back to the operation that held the lock.
PostgreSQL exposes lock state and blocked sessions through its monitoring views
and functions. A trace or structured log can record the request or job type,
transaction outcome, and the logical resource keys involved. Pick identifiers
and sampling carefully so the diagnostic remains useful without copying customer
data into a long-lived log.

## Where it goes wrong

A common recovery design repeats a single failed update after a deadlock. In
PostgreSQL the transaction has been selected for abort, and a whole operation
may depend on several earlier reads and writes. Roll it back, establish a new
attempt, and re-evaluate the work as one unit. Keep retries bounded and use
delay or admission limits to reduce waves of similar requests. Decide whether an
external payment, notification or file operation can already have taken effect
before retrying.

Ordering can drift as the codebase grows. A sorting rule in one application
handler is effective only when the other writers that acquire the same
combination follow it. A background job, administrative repair tool or trigger
can add a lock acquisition the handler author never considered. Write down the
ownership and ordering rule near the shared write path. Add an integration test
for a real pairing of paths when a new operation touches more than one protected
resource.

Timeouts give callers a way to stop waiting, and database lock diagnostics give
operators a way to ask why the wait happened. A short timeout can fire before
the database checks for cycles. The client will then observe a timeout and the
relevant evidence can disappear unless the operation was already instrumented.
Collect the error code and the wait information while the incident is active.
Test the reported outcome as well as the database state. A buyer who saw an
error may try again even when the first attempt reached an external service.
After a connection drops, look up the result using the operation's stable
identifier.

## Further reading

- [PostgreSQL explicit locking and deadlocks](https://www.postgresql.org/docs/18/explicit-locking.html#LOCKING-DEADLOCKS).
  Describes lock compatibility and how the database detects a cycle.
- [PostgreSQL lock management settings](https://www.postgresql.org/docs/18/runtime-config-locks.html).
  Explains the timing and cost of checking waits for deadlocks.
- [The PostgreSQL pg_locks view](https://www.postgresql.org/docs/18/view-pg-locks.html).
  Describes the granted and waiting locks that operators can inspect.

<https://engineer.company/glossary/deadlock/>
