{"canonical_url":"https://engineer.company/glossary/deadlock/","content_markdown":"# Deadlock\n\n## What it is\n\nA deadlock occurs when several operations each hold a resource and wait for\nanother member of the same group to release something. The requests form a\ncycle. Two database transactions provide a small example. One has locked\ninventory item A and needs item B. The other already holds B and needs A.\nNeither operation can finish using its current sequence because the lock would\nonly be released by another operation that is also waiting.\n\nThe resource can be a row, a table, or another kind of lock. The same structural\nproblem appears in an application with several mutexes or in a workflow that\nholds one shared resource while requesting another. In a database, the lock\ntypes and their compatibility guide which requests can wait. A statement that\ntakes lock A might create a cycle through several transactions that are working\non different statements. Looking only at the last query issued by each\nconnection can miss the earlier statement that acquired its first lock.\n\nPostgreSQL checks for cycles after a lock has been waiting long enough to\nwarrant the cost of a check. When it detects a database deadlock, it aborts a\ntransaction to let the other transactions proceed. Its error code for that\ncondition is `40P01`. Waiting for a busy item whose current holder can finish is\nordinary contention. That can still create a serious service problem if the\nqueue grows. Establish which pattern you have before choosing whether to change\nordering, reduce transaction time or cap the amount of concurrent work.\n\n## Why it matters\n\nA service can look healthy through thousands of individual calls and still have\na reproducible cycle once two operations overlap. The problem can appear only at\nan unusual boundary, such as a background adjustment touching the same two\naccounts as a user action. Each path looks reasonable on its own. The relative\norder of acquired resources gives them a shared constraint that neither path can\nenforce alone.\n\nDeadlocks can trigger work after the initial incident. A worker may have\ncompleted application calculations or a network request before the database\naborts its transaction. If several workers immediately repeat the same order and\ntiming, retries can increase pressure on the locks. Treat the retry as part of\nthe operation's design. Establish what gets repeated, which effects are durable,\nwhen the client gives up, and what diagnostics remain available when the attempt\nis abandoned.\n\nLock duration matters even where ordering prevents a cycle. Acquiring rows\nconsistently does little for a waiting buyer if the holder keeps those rows\nlocked while it calls a slow partner. A transaction boundary should give the\nprotected decision enough time to commit. Connection usage, queue length and the\ntime spent waiting on locks give useful evidence about whether the current\nboundary suits the workload. Long tails and occasional deadlock errors can have\ndifferent causes even when the same route reports them.\n\n## What it looks like in practice\n\nImagine stock items A and B are bundled in a sale, and a separate adjustment\nprocess can also affect both. Record what each transaction touches as it runs.\nIn a test, let the sale lock A and the adjustment lock B. Then let each ask for\nits second item. Confirm that the database detects the cycle and that whichever\ntransaction was aborted leaves no partial stock changes. Run the same schedule\nwith both paths acquiring keys in the same deterministic order. One transaction\nshould wait, then complete once the holder commits or rolls back. The test can\nshow that waiting remains possible and that the cycle is gone for these paths.\n\nEngineer's\n[engineering note on selling limited stock](/notes/selling-limited-stock-without-overselling/)\nexamines how much work happens while an inventory lock is held. Its advice to\nmove network calls out of the locked part of the transaction is relevant to both\ntesting and diagnosis. Real traffic will produce more useful lock reports when\nthe protected work has clear boundaries. The two-item example extends that\nreasoning to a common bundle workflow.\n\nFor diagnosis, connect the wait back to the operation that held the lock.\nPostgreSQL exposes lock state and blocked sessions through its monitoring views\nand functions. A trace or structured log can record the request or job type,\ntransaction outcome, and the logical resource keys involved. Pick identifiers\nand sampling carefully so the diagnostic remains useful without copying customer\ndata into a long-lived log.\n\n## Where it goes wrong\n\nA common recovery design repeats a single failed update after a deadlock. In\nPostgreSQL the transaction has been selected for abort, and a whole operation\nmay depend on several earlier reads and writes. Roll it back, establish a new\nattempt, and re-evaluate the work as one unit. Keep retries bounded and use\ndelay or admission limits to reduce waves of similar requests. Decide whether an\nexternal payment, notification or file operation can already have taken effect\nbefore retrying.\n\nOrdering can drift as the codebase grows. A sorting rule in one application\nhandler is effective only when the other writers that acquire the same\ncombination follow it. A background job, administrative repair tool or trigger\ncan add a lock acquisition the handler author never considered. Write down the\nownership and ordering rule near the shared write path. Add an integration test\nfor a real pairing of paths when a new operation touches more than one protected\nresource.\n\nTimeouts give callers a way to stop waiting, and database lock diagnostics give\noperators a way to ask why the wait happened. A short timeout can fire before\nthe database checks for cycles. The client will then observe a timeout and the\nrelevant evidence can disappear unless the operation was already instrumented.\nCollect the error code and the wait information while the incident is active.\nTest the reported outcome as well as the database state. A buyer who saw an\nerror may try again even when the first attempt reached an external service.\nAfter a connection drops, look up the result using the operation's stable\nidentifier.\n\n## Further reading\n\n- [PostgreSQL explicit locking and deadlocks](https://www.postgresql.org/docs/18/explicit-locking.html#LOCKING-DEADLOCKS).\n  Describes lock compatibility and how the database detects a cycle.\n- [PostgreSQL lock management settings](https://www.postgresql.org/docs/18/runtime-config-locks.html).\n  Explains the timing and cost of checking waits for deadlocks.\n- [The PostgreSQL pg_locks view](https://www.postgresql.org/docs/18/view-pg-locks.html).\n  Describes the granted and waiting locks that operators can inspect.\n\n\u003chttps://engineer.company/glossary/deadlock/\u003e\n","date_modified":"2026-11-25T07:18:46Z","description":"Follow a database wait cycle, order resource acquisition and handle the rollback before a bounded retry.","formats":{"gemtext":"https://engineer.company/glossary/deadlock/index.gmi","gopher":"https://engineer.company/glossary/deadlock/gophermap","html":"https://engineer.company/glossary/deadlock/","json":"https://engineer.company/glossary/deadlock/index.json","markdown":"https://engineer.company/glossary/deadlock/index.md","pdf":"https://engineer.company/glossary/deadlock/index.pdf"},"kind":"page","language":"en","title":"What is a deadlock?","url":"https://engineer.company/glossary/deadlock/","version":1}