Deadlocks: Detection & Avoidance
"The best defense against deadlocks is generally to avoid them by being certain that all applications using a database acquire locks on multiple objects in a consistent order." — PostgreSQL documentation, Explicit Locking, section "Deadlocks"
Summary: A deadlock is a cycle of transactions that each wait for a lock the next one holds. The database cannot wait it out; it aborts one participant, and your code must retry. Focus: Reading the wait-for graph, the exact detector behaviour and error codes in PostgreSQL, InnoDB, SQL Server and Oracle, the five real-world patterns that cause cycles, and the avoidance and retry toolkit in SQL, Go and Laravel. Learning goal: Given a deadlock log from any of the four engines, name the cycle, say which two statements closed it, fix the ordering, and ship a retry that is safe to run twice.
This page is the complete reference for deadlocks in relational databases. It owns detection, victim selection, deadlock_timeout, lock ordering and retry strategy. What a lock mode is lives in Locks & Concurrency; whether to lock at all lives in Optimistic vs Pessimistic Locking; the visibility rules that surround it live in Isolation Levels; the transaction basics in ACID & Transactions.
Page map
| If you are looking for | Go to |
|---|---|
| The one-minute tables | Everything in one minute |
| Why a deadlock cannot be waited out | Why deadlocks exist |
| Coffman 1971 and the four conditions | Where it comes from |
| Wait-for graph, lock wait, livelock, victim, timeouts | The concepts, one by one |
| The five real-world patterns (opposite order, foreign keys, index order, gap locks, ORM) | The classic patterns |
| PostgreSQL detector, InnoDB detector, SQL Server, Oracle | Per-engine behaviour and Mechanics |
| Reading the log of each engine | Reading a deadlock report |
| Lock ordering, short transactions, batching, retry | Solving deadlocks |
| Retry table, Go wrapper, Laravel limits | Retries and failure handling |
| Metrics and alerts | Monitoring |
| Which tool for which situation | Choosing a remedy |
| Two databases, microservices, sharding | In architecture |
| Reproduce it in PostgreSQL and MySQL | Lab |
| Wrong beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concepts section.
| Term | In plain words | Tiny example | What resolves it |
|---|---|---|---|
| Lock wait | You queue behind someone who will finish | T1 holds row 1 for 3 s, T2 waits 3 s | The holder commits or rolls back |
| Deadlock | A ring of waiters; nobody can finish first | A holds 1 wants 2, B holds 2 wants 1 | The engine aborts one (the victim) |
| Wait-for graph | Picture: transactions as nodes, "waits for" as edges | A to B, B to A | A cycle in it means deadlock |
| Livelock | Everyone keeps moving but nobody progresses | Two retriers back off in lockstep forever | Randomised backoff (jitter) |
| Starvation | One transaction waits unfairly long | A reader behind an endless queue of writers | Fair queues, shorter transactions |
| Lock timeout | A wait that gave up on a clock | innodb_lock_wait_timeout, lock_timeout | The waiter errors; the holder is unharmed |
| Victim | The transaction the engine kills | The smaller one in InnoDB | Retry it |
| Distributed deadlock | A cycle that crosses two databases or services | Service A waits on DB 2, service B on DB 1 | Only timeouts; no engine sees the whole graph |
The error you will catch.
| Engine | Signal | Rolled back | Retry? |
|---|---|---|---|
| PostgreSQL | SQLSTATE 40P01 deadlock_detected, message deadlock detected | The whole transaction | Yes, from BEGIN |
| MySQL InnoDB | Error 1213 (SQLSTATE 40001) Deadlock found when trying to get lock; try restarting transaction | The whole transaction | Yes |
| MySQL InnoDB | Error 1205 (SQLSTATE HY000) Lock wait timeout exceeded; try restarting transaction | The statement only, by default | Carefully; not a deadlock |
| SQL Server | Error 1205, "chosen as the deadlock victim" | The victim's transaction | Yes |
| Oracle | ORA-00060: deadlock detected while waiting for resource | The statement only; the transaction stays open | Roll back, then retry |
The three things to do.
| Situation | Do this |
|---|---|
| Touching several rows or tables in one transaction | Always in the same global order (ascending primary key, or table then key) |
| Anything that can still deadlock | Retry the whole transaction with bounded attempts and jitter |
| Rising deadlock count | Read the report, find the two statements, fix the order or shorten the transaction; do not just raise timeouts |
Why deadlocks exist
Transactions hold locks until they finish (ACID & Transactions). A transaction that needs two locks takes them one after the other, so for a moment it holds one and waits for the other. If another transaction holds the second and wants the first, both wait forever. Locking is what gives you isolation; deadlock is the price of letting transactions request locks in any order.
| Design choice | What you gain | What it costs |
|---|---|---|
| Lock as you go (2PL) | Simple, correct isolation, no pre-declaration | Cycles are possible, so you need detection and retry |
| Declare all locks up front (conservative locking) | No deadlocks | Needs to know the rows in advance; fewer concurrent transactions |
Never wait (NOWAIT, SKIP LOCKED) | No cycles, no waiting | The caller handles "busy" |
| Optimistic checks (version column) | No lock held during think time | Retry on conflict instead (Optimistic vs Pessimistic) |
The analogy we reuse on this page: a one-lane bridge. Two cars meet in the middle, each already half on. Waiting longer changes nothing. You fix it with a rule that makes the situation impossible (one direction at a time, which is a global order), or a referee who makes one car reverse (detect and abort), after which that car tries again.
Three common misunderstandings, up front
- "A deadlock means the server is overloaded." It is a logic-ordering problem. It can happen between two transactions on an idle server. Raising
deadlock_timeoutonly delays the error. - "The database should just wait." Waiting cannot help: each participant needs a lock only another participant can release, and that participant is waiting too.
- "Higher isolation prevents deadlocks." MySQL's manual says it plainly: "the isolation level changes the behavior of read operations, while deadlocks occur because of write operations." Stronger isolation (InnoDB gap locks at Repeatable Read, PostgreSQL SSI aborts) can add deadlocks and aborts, not remove them.
Where it comes from
The word predates databases. Coffman, Elphick and Shoshani's 1971 survey System Deadlocks (ACM Computing Surveys, vol. 3, no. 2, June 1971) treats it as a problem of "large multiprogramming systems" and names the "deadlock or deadly-embrace problem" (Dijkstra's term, which the paper credits). It lists four conditions that must all hold:
"1) Tasks claim exclusive control of the resources they require ("mutual exclusion" condition). 2) Tasks hold resources already allocated to them while waiting for additional resources ("wait for" condition). 3) Resources cannot be forcibly removed from the tasks holding them until the resources are used to completion ("no preemption" condition). 4) A circular chain of tasks exists, such that each task holds one or more resources that are being requested by the next task in the chain ("circular wait" condition)."
The same paper gives the prevention strategies that databases still use: deny one condition. Its linear-ordering strategy says that a task holding a resource of type r "may subsequently request only those resources of types following r in the ordering", and "it can be shown that under this condition the state graph cannot have circuits, and therefore circular wait conditions are prevented." That sentence is the whole theory behind "lock rows in id order".
| Coffman condition | In a database | Can the engine remove it? | Which fix targets it |
|---|---|---|---|
| Mutual exclusion | Write locks on a row are exclusive | No (that is isolation) | SKIP LOCKED, optimistic checks avoid the exclusive hold |
| Hold and wait | A transaction keeps earlier locks while asking for later ones | No (locks are held until commit) | Lock everything in one statement; short transactions |
| No preemption | Locks cannot be taken away; only rollback frees them | Only by aborting: the victim's rollback is the preemption | Detection and retry |
| Circular wait | A ring of waiters | Yes, by ordering | Global lock order |
The database-specific wording comes from the vendors. PostgreSQL's manual describes "two (or more) transactions each hold locks that the other wants", and MySQL's "each transaction holds a lock that is needed by another one".
The concepts, one by one
Wait-for graph and cycle Must-know
In plain words: Draw each transaction as a dot and an arrow from A to B whenever A is waiting for a lock B holds. A deadlock is an arrow loop you can follow back to where you started.
Common misunderstanding: "Any long wait is a deadlock." A single arrow, or a chain with no loop, ends when the head of the chain commits. Only a cycle is permanent.
Definition: a directed graph whose nodes are transactions (or backend processes) and whose edges are "waits for". A cycle means no node on it can ever proceed. Chains and trees hanging off a cycle (T4 in the picture) are not deadlocked themselves; they resume once the victim is rolled back.
A (txn 8813) B (txn 8814)
1 BEGIN; BEGIN;
2 UPDATE accounts SET balance = balance - 10 WHERE id = 1; -- A holds row 1
3 UPDATE accounts SET balance = balance - 10 WHERE id = 2; -- B holds row 2
4 UPDATE accounts SET balance = balance + 10 WHERE id = 2; -- A waits for B
5 UPDATE accounts SET balance = balance + 10 WHERE id = 1; -- B waits for A: cycle
-- after deadlock_timeout (PostgreSQL) or immediately (InnoDB) one side gets the errorReal scenario: a money transfer between two accounts called in both directions; two workers that each reserve stock for a basket of products listed in different orders; a nightly job updating customers while the web app updates their orders.
| Engine | How the graph is built |
|---|---|
| PostgreSQL | Walks the lock manager's wait queues from the process whose timer fired; distinguishes "hard" and "soft" edges (Mechanics) |
| InnoDB | Maintains a wait-for graph of transaction lock requests and checks on every new wait when innodb_deadlock_detect is on |
| SQL Server | A lock monitor thread periodically searches for cycles |
| Oracle | Detects while a session waits on an enqueue and raises ORA-00060 in the session that closes the cycle |
Fix: remove one edge: take the locks in the same order so no transaction holds B while asking for A (Lock ordering).
Deadlock versus lock wait versus lock timeout Must-know
In plain words: A lock wait is a queue; a deadlock is a queue that bites its own tail; a lock timeout is somebody leaving the queue because they got tired.
Common misunderstanding: "Lock wait timeout exceeded is a deadlock." It is not: the holder may be perfectly healthy but slow (or idle in a transaction). It needs a different response: find the blocker, not the cycle.
Definition: a wait ends when the holder commits or aborts. A deadlock never ends by itself. A timeout is a client-side or server-side limit on how long to wait, whether or not there is a cycle.
Lock wait Deadlock Lock timeout
1 A holds row 1 A holds 1, B holds 2 A holds row 1 (idle, forgot COMMIT)
2 B asks row 1, waits A asks 2, B asks 1 B asks row 1, waits...
3 A commits engine finds cycle 50 s pass (InnoDB default)
4 B proceeds victim aborted: 40P01 / 1213 B errors: 1205 / 55P03| Situation | PostgreSQL | MySQL InnoDB | SQL Server | Oracle |
|---|---|---|---|---|
| Wait without cycle | Waits indefinitely unless lock_timeout is set | Waits up to innodb_lock_wait_timeout (default 50 s) | Waits indefinitely unless SET LOCK_TIMEOUT is set | Waits indefinitely unless NOWAIT / WAIT n |
| Timeout error | 55P03 lock_not_available (lock_timeout, NOWAIT) | 1205 ER_LOCK_WAIT_TIMEOUT | Error 1222 | ORA-30006 (WAIT n), ORA-00054 (NOWAIT) |
| Deadlock error | 40P01 | 1213 | 1205 | ORA-00060 |
| What is rolled back on timeout | The statement | The statement (whole transaction only with innodb_rollback_on_timeout) | The statement; transaction continues unless XACT_ABORT ON | The statement |
Real scenario: a report session that ran BEGIN; SELECT ... FOR UPDATE; and then waited on a person: every writer behind it times out and looks like a "deadlock problem" in the dashboards.
Fix: for waits, find and shorten the blocker (pg_blocking_pids(), pg_stat_activity, sys.innodb_lock_waits) and set lock_timeout / idle_in_transaction_session_timeout; for deadlocks, fix ordering. See Locks & Concurrency.
Livelock and starvation Important
In plain words: In a livelock nobody is stuck, yet nobody gets anywhere, like two people in a corridor who both step aside the same way, again and again. Starvation is one party never getting its turn.
Common misunderstanding: "Retry on deadlock fixes it for good." Retrying immediately and with a fixed delay makes the two losers collide again in lockstep, which is a livelock of retries.
Definition: a livelock is a set of actors that keep changing state in response to each other without making progress. Starvation is indefinite postponement of one transaction (a reader behind a continuous stream of writers on an unfair lock queue).
Retrier A Retrier B
1 deadlock, sleep 100 ms deadlock, sleep 100 ms (same delay)
2 retry, takes row 1 retry, takes row 2
3 waits for row 2 waits for row 1 -> deadlock again
4 sleep 200 ms sleep 200 ms -> repeat| Cause | Mitigation |
|---|---|
| Identical retry delays | Exponential backoff with full jitter (random in [0, cap]) |
| Unbounded retries | A maximum of 3-10 attempts, then surface the error |
| Hot row with a waiting crowd | Serialise per key in a queue; atomic UPDATE ... SET x = x + 1 |
Fix: randomise the delay (Retry with jitter).
Victim selection Important
In plain words: The engine has to kill one transaction in the loop. Which one depends on the product, and in PostgreSQL you cannot rely on it.
Common misunderstanding: "The oldest (or newest) transaction always loses." Only InnoDB documents a size rule; PostgreSQL's manual says "Exactly which transaction will be aborted is difficult to predict and should not be relied upon."
Definition: the victim is the transaction rolled back (or whose statement is cancelled) to break a cycle.
| Engine | Who is the victim | Source of the rule |
|---|---|---|
| PostgreSQL | Usually the process whose deadlock_timeout timer fired first and detected the cycle: "usually by aborting the detecting process' transaction". If earlier waiters have not yet run the check, "the first one to do so will be the victim" | lock manager README |
| InnoDB | "tries to pick small transactions to roll back, where the size of a transaction is determined by the number of rows inserted, updated, or deleted" | MySQL manual |
| SQL Server | The session with the lowest DEADLOCK_PRIORITY; ties go to the one cheapest to roll back (least log written) | SQL Server documentation (not saved for this page) |
| Oracle | The session that detected the cycle gets ORA-00060 for its statement | Oracle documentation (not saved for this page) |
Fix: do not depend on it. Make every code path retry; in SQL Server you may set SET DEADLOCK_PRIORITY LOW on background jobs so interactive requests win.
Coffman conditions as a checklist Good to know
In plain words: Four things must all be true for a deadlock; remove one and it cannot happen.
Common misunderstanding: "I can prevent deadlocks by avoiding exclusive locks." Mutual exclusion is the one condition databases keep; you remove circular wait instead.
Definition: see the table above. In a database, only circular wait is practical to remove (ordering), plus hold-and-wait for small units of work (lock everything in one statement).
Condition Broken by
1 mutual exclusion SKIP LOCKED / optimistic version column
2 hold and wait single-statement lock of all rows (ORDER BY id FOR UPDATE)
3 no preemption engine abort = forced preemption
4 circular wait one global lock orderReal scenario: a code review rule "every multi-row write sorts ids first" breaks condition 4 for the whole codebase.
Fix: pick condition 4 first: it is the cheapest.
Timeouts and what they guard Must-know
In plain words: Several different clocks exist; only one of them is about deadlocks.
Common misunderstanding: "deadlock_timeout is how long a transaction may wait for a lock." It is how long a waiter sleeps before checking for a cycle; a transaction can wait far longer when there is no cycle.
Definition: the knobs and what each clock starts and stops.
| Setting | Engine | Default | What it controls |
|---|---|---|---|
deadlock_timeout | PostgreSQL | 1s | Delay before the waiter runs the cycle check; also the threshold for log_lock_waits messages |
lock_timeout | PostgreSQL | 0 (off) | Maximum wait for any lock, then 55P03 |
statement_timeout | PostgreSQL | 0 (off) | Maximum duration of one statement |
idle_in_transaction_session_timeout | PostgreSQL | 0 (off) | Kills sessions idle inside an open transaction (the classic blocker) |
innodb_deadlock_detect | InnoDB | ON | Eager cycle detection on each wait |
innodb_lock_wait_timeout | InnoDB | 50 seconds | Maximum wait for a row lock, then error 1205; the only cure when detection is off |
innodb_rollback_on_timeout | InnoDB | OFF | Roll back the whole transaction on 1205, not only the statement |
innodb_print_all_deadlocks | InnoDB | OFF | Log every deadlock to the error log |
LOCK_TIMEOUT | SQL Server | -1 (infinite) | Per-session wait limit, error 1222 |
-- PostgreSQL: fail fast instead of queueing behind a stuck transaction
SET lock_timeout = '2s';
SET idle_in_transaction_session_timeout = '30s';
-- MySQL
SET SESSION innodb_lock_wait_timeout = 5;Real scenario: a payments path sets lock_timeout = 2s and returns "busy, try again" instead of letting a request hang for a minute behind a migration.
Fix: timeouts are a safety net for waits and for distributed cycles (below); ordering and retry are the fix for deadlocks.
The classic patterns
Pattern 1: opposite lock order Must-know
In plain words: Two code paths touch the same two rows but start from different ends.
Common misunderstanding: "Each function is correct, so the system is correct." The order is a property of the pair of callers (A to B and B to A), not of either function.
Definition: the PostgreSQL manual's example: one transaction updates account 11111 then 22222, another updates 22222 then 11111; each waits for the other.
T1 T2
1 UPDATE accounts SET balance = balance + 100 WHERE acctnum = 11111;
2 UPDATE accounts SET balance = balance + 100 WHERE acctnum = 22222;
3 UPDATE accounts SET balance = balance - 100 WHERE acctnum = 11111; -- waits for T1
4 UPDATE accounts SET balance = balance - 100 WHERE acctnum = 22222; -- waits for T2: deadlockReal scenario: transfer(a, b) and transfer(b, a) at the same second; a marketplace crediting a seller and a buyer in whichever order the event lists them; a cart checkout locking stock rows in cart order.
Fix: sort by id before locking, then one SELECT ... ORDER BY id FOR UPDATE (solution).
Pattern 2: foreign keys and parent row locks Must-know
In plain words: Inserting a child row quietly puts a light lock on its parent row; a heavier lock on that parent from somewhere else can then wait on it.
Common misunderstanding: "I never lock the parent, so it cannot be involved." The foreign-key check does, behind your back.
Definition: in PostgreSQL an insert into a child table takes FOR KEY SHARE on the referenced parent row. SELECT ... FOR UPDATE on the parent conflicts with it; FOR NO KEY UPDATE does not. An UPDATE of a non-key column of the parent also takes FOR NO KEY UPDATE, which is why ordinary parent updates do not clash with child inserts (since PostgreSQL 9.3). In InnoDB the foreign-key check sets a shared record lock on the parent record.
A B
1 BEGIN; BEGIN;
2 INSERT INTO child (id, parent_id) VALUES (11, 1); -- FOR KEY SHARE on parent 1
3 INSERT INTO child (id, parent_id) VALUES (12, 2); -- FOR KEY SHARE on parent 2
4 SELECT * FROM parent WHERE id = 2 FOR UPDATE; -- waits for B's key share
5 SELECT * FROM parent WHERE id = 1 FOR UPDATE; -- waits for A: deadlock| Parent lock the code takes | Conflicts with the FK key share? | Result |
|---|---|---|
FOR UPDATE (PostgreSQL) | Yes | Possible cycle with child inserts |
FOR NO KEY UPDATE | No | No wait; the usual fix when you do not change the key |
Plain UPDATE of a non-key column | No (it takes FOR NO KEY UPDATE) | No wait |
UPDATE of the key, or DELETE of the parent | Yes (FOR UPDATE strength) | Waits for child inserts; cycles possible |
InnoDB shared FK record lock vs FOR UPDATE on parent | Yes | 1213 possible |
Real scenario: "recalculate order total" locks the order row FOR UPDATE while another request inserts order lines (children) into two orders in the opposite order; an ON DELETE CASCADE delete of a customer racing with new orders.
Fix: use FOR NO KEY UPDATE on the parent when the key is not changing, and lock parents in id order before inserting children. Index the foreign-key column on the child so cascades and deletes do not scan and lock more (Indexing).
Pattern 3: index-order and plan-order deadlocks Important
In plain words: One statement locks rows as it finds them, so the order depends on how it finds them (which index, which scan), not on what you wrote.
Common misunderstanding: "A single UPDATE is atomic, so it cannot deadlock with anything." A multi-row UPDATE locks row by row; two of them scanning in opposite orders deadlock.
Definition: a statement acquires row locks in scan order. A plan that walks an index ascending and one that scans the heap, or two statements using different indexes (InnoDB locks the secondary-index record, then the clustered-index record), take locks in different orders.
T1: UPDATE t SET v = v + 1 WHERE status = 'new' -- finds rows via the status index: 9, then 5
T2: UPDATE t SET v = v + 1 WHERE owner = 7 -- finds rows via the primary key: 5, then 9
1 T1 locks row 9
2 T2 locks row 5
3 T1 wants row 5 -- waits for T2
4 T2 wants row 9 -- waits for T1: cycleReal scenario: a bulk "mark as processed" UPDATE ... WHERE id IN (...) racing with a status sweeper; a cleanup DELETE ... WHERE created_at < ... racing with row updates.
Fix (PostgreSQL has no UPDATE ... ORDER BY):
-- Lock in a defined order first, then update exactly those rows
WITH locked AS (
SELECT id FROM jobs WHERE status = 'new' ORDER BY id FOR UPDATE
)
UPDATE jobs SET status = 'running' FROM locked WHERE jobs.id = locked.id;
-- MySQL accepts it directly:
-- UPDATE jobs SET status = 'running' WHERE status = 'new' ORDER BY id LIMIT 100;Pattern 4: gap locks and inserts in InnoDB Important
In plain words: At Repeatable Read, a locking read on a value that does not exist locks the empty space around it; two sessions can both hold that space, and then both want to insert into it.
Common misunderstanding: "SELECT ... FOR UPDATE on a missing row locks nothing." In InnoDB it takes a gap (next-key) lock, and gap locks held by different transactions do not conflict with each other; an insert intention lock conflicts with them.
Definition: SELECT ... WHERE id = 15 FOR UPDATE with rows 10 and 20 present locks the gap (10, 20). A second session takes the same gap lock (no conflict). Each then inserts into the gap: each insert waits on the other's gap lock.
A B
1 BEGIN; BEGIN;
2 SELECT * FROM t WHERE id = 15 FOR UPDATE; -- empty set; gap lock (10,20)
3 SELECT * FROM t WHERE id = 16 FOR UPDATE; -- also gets a gap lock: no conflict
4 INSERT INTO t (id) VALUES (15); -- waits for B's gap lock
5 INSERT INTO t (id) VALUES (16); -- ERROR 1213, deadlock| Remedy | How | Cost |
|---|---|---|
READ COMMITTED (InnoDB) | Gap locks are disabled for searches and index scans (still used for FK and duplicate-key checks) | Phantoms; row-based binlog required for replication safety |
| Skip the check, rely on a unique index | INSERT ... ON DUPLICATE KEY UPDATE or catch 1062 | The constraint decides, not a lock |
| Lock an existing parent row | SELECT ... FROM parent WHERE id = ? FOR UPDATE instead of the gap | Needs a natural parent |
Retry on 1213 | The standard remedy | Bounded retries |
PostgreSQL has no gap locks; the equivalent trap is two INSERT ... ON CONFLICT transactions on unique keys, which wait on each other's uncommitted rows (a cycle when each also touches the other's key).
Real scenario: "reserve a unique slot if free, else take the next": two workers check-then-insert on neighbouring values.
Fix: insert and handle the unique-violation, or move to Read Committed for that path (Isolation Levels).
Pattern 5: ORM-induced deadlocks (Eloquent save order) Important
In plain words: The ORM decides the order of the writes, and it follows whatever order your collection happens to be in.
Common misunderstanding: "Eloquent saves in a sensible order." $models->each->save() writes in the collection's order; touches, observers and cascades add hidden writes to parents; lockForUpdate()->find($id) inside a loop takes one lock per iteration.
Definition: the lock order is the order of your loop, plus the writes done by model events (updated_at touching a parent, counter caches, observers).
Job 1: foreach [A, B] as $id Job 2: foreach [B, A] as $id
1 $a = Account::lockForUpdate()->find(A)
2 $b = Account::lockForUpdate()->find(B)
3 $b = Account::lockForUpdate()->find(B) -- waits
4 $a = Account::lockForUpdate()->find(A) -- deadlock| ORM habit | Hidden lock order | Fix |
|---|---|---|
Loop of find()->lockForUpdate() | Payload order | One whereIn()->orderBy('id')->lockForUpdate() |
$child->touch() / belongsTo(..., touch: true) | Child, then parent row | Update parents in a consistent place, or avoid touching hot parents |
| Observer updating a counter on a parent | Child row, then parent | Atomic increment() after the main writes, in id order |
saveMany in input order | Input order | Sort by key first |
Bulk upsert() | Statement scan order | Sort the rows by the conflict key before the call |
The Laravel code in Laravel shows the sorted whereIn approach. See also ORM Pitfalls.
Fix: sort keys, lock in one statement, update, keep the transaction short.
Pattern 6: long transactions and user think time Must-know
In plain words: The longer a transaction holds a lock, the larger the window in which another can cross it.
Common misunderstanding: "Opening the transaction early is harmless." Every lock taken is held until commit, including across HTTP calls and queue publishes.
Definition: the PostgreSQL manual: "a transaction seeking either a table-level or row-level lock will wait indefinitely for conflicting locks to be released. This means it is a bad idea for applications to hold transactions open for long periods of time (e.g., while waiting for user input)."
Request thread Time
1 BEGIN; SELECT ... FOR UPDATE; 0 ms
2 call payment gateway over HTTP +800 ms <- locks held, nobody else can touch the rows
3 UPDATE orders ...; COMMIT; +820 msReal scenario: a checkout that locks the stock row and then calls a card gateway; an admin screen that opens FOR UPDATE when the page loads and commits on "Save".
Fix: do external calls outside the transaction (or after it with DB::afterCommit), validate first, lock last, commit fast; use a version column for human think time (Optimistic vs Pessimistic).
Per-engine behaviour
| Axis | PostgreSQL | MySQL InnoDB | SQL Server | Oracle | SQLite |
|---|---|---|---|---|---|
| Detection | Lazy: timer deadlock_timeout (1 s) then graph walk | Eager on each wait (default); optional off | Lock monitor thread, periodic search | On enqueue wait | None needed: one writer, SQLITE_BUSY |
| Victim | Detector (often the one whose timer fired first) | Smallest by rows changed | Lowest DEADLOCK_PRIORITY, then cheapest | The detecting session's statement | n/a |
| Error | 40P01 | 1213 (40001) | 1205 | ORA-00060 | SQLITE_BUSY / SQLITE_LOCKED |
| Rolled back | Whole transaction | Whole transaction | Victim's transaction | Statement only | The statement |
| Report | Server log, log_lock_waits | SHOW ENGINE INNODB STATUS, innodb_print_all_deadlocks | xml_deadlock_report event in system_health, trace flags 1204 / 1222 | Trace file in the diagnostic dest, alert log message | n/a |
| Counter | pg_stat_database.deadlocks | INNODB_METRICS lock_deadlocks | Performance counter Number of Deadlocks/sec | AWR / v$ views, alert log | n/a |
| Gap locks | No | Yes at Repeatable Read | Key-range locks at Serializable | No (row versions) | n/a |
What each database really does.
| Product | Behaviour worth knowing |
|---|---|
| PostgreSQL | Rows are locked in tuple headers; waiters queue on the holder's transaction id (ShareLock on transaction). Readers do not block writers (MVCC). Soft-edge queue reordering can resolve some cycles without aborting anyone |
| MySQL InnoDB | Record, gap and next-key locks; secondary-index plus clustered-index locking; detection is eager, and with thousands of waiters detection itself can cost CPU (innodb_deadlock_detect = OFF plus short innodb_lock_wait_timeout) |
| MySQL Galera / group replication | Certification conflicts abort with a deadlock-like error (WSREP detected deadlock/conflict); Laravel retries it |
| SQL Server | Deadlock graph XML names processes, resources and the victim; row versioning (READ_COMMITTED_SNAPSHOT) removes reader-writer cycles |
| Oracle | Row locks live in the block; ORA-00060 rolls back only the statement; an unindexed foreign key makes parent changes take table-level share locks and a classic source of cycles |
| SQLite | A single writer at a time: no wait-for graph; a second writer gets SQLITE_BUSY, and a read-then-upgrade can fail at once (SQLite) |
| MongoDB | Document-level locking in WiredTiger; write conflicts raise WriteConflict and the server retries internally; multi-document transactions surface TransientTransactionError |
| CockroachDB | Serializable with retry errors (40001); transaction wait queues detect deadlocks and abort one |
| Redis | Single-threaded command execution: no deadlocks inside Redis; WATCH/MULTI give optimistic checks; distributed locks built on it can deadlock at the application level |
Mechanics
PostgreSQL: optimistic waiting and the detector Must-know
The lock manager README: "if a process cannot acquire the lock it wants immediately, it goes to sleep without any deadlock check. But it also sets a delay timer, with a delay of DeadlockTimeout milliseconds (typically set to one second). If the delay expires before the process is granted the lock it wants, it runs the deadlock detection/breaking code. Normally this code will determine that there is no deadlock condition, and then the process will go back to sleep and wait quietly until it is granted the lock. But if a deadlock condition does exist, it will be resolved, usually by aborting the detecting process' transaction."
Waiter P1 Timeline
1 lock request conflicts -> sleep + timer t = 0
2 ... t < 1 s: holder commits -> granted, no check ever ran
3 timer fires, run detector t = 1 s
4 walk wait-for graph from P1 hard edges: locks already held; soft edges: queue order
5 cycle with hard edges only? abort detecting transaction -> ERROR 40P01
6 soft cycle? try rearranging the wait queue; abort only if impossibleDetails that matter in practice:
| Detail | Consequence |
|---|---|
| The check costs something, so it is delayed | A real deadlock is reported only after deadlock_timeout (default 1 s); the two sessions sit blocked until then |
| "Soft" edges are wait-priority blocks (a queued request ahead of you) | The detector may reverse them by reordering the wait queue and avoid an abort; "hard" edges (locks held) can only be resolved by aborting |
| The victim is whoever detects first | "If earlier waiters in the cycle have not yet run CheckDeadLock, then the first one to do so will be the victim" |
Raising deadlock_timeout | Fewer wasted checks on busy servers, slower reporting of real deadlocks; ideally above your typical transaction time |
| Parallel and autovacuum | Autovacuum workers can be cancelled if blocking a cycle; parallel workers form lock groups |
log_lock_waits = on | Logs a message when a wait exceeds deadlock_timeout, and again when the lock is granted: it shows slow waits before they become cycles |
InnoDB: eager detection, weights and limits Must-know
With innodb_deadlock_detect = ON (default) InnoDB checks each time a transaction must wait, rolls back one of the cycle ("tries to pick small transactions to roll back, where the size of a transaction is determined by the number of rows inserted, updated, or deleted"), and returns 1213.
| Situation | Behaviour |
|---|---|
| Wait-for list longer than 200 transactions | Treated as a deadlock; the report says TOO DEEP OR LONG SEARCH IN THE LOCK TABLE WAITS-FOR GRAPH, WE WILL ROLL BACK FOLLOWING TRANSACTION |
| More than 1,000,000 locks to examine | Same error |
LOCK TABLES or non-InnoDB engines involved | Not seen unless innodb_table_locks = 1 and autocommit = 0; falls back to innodb_lock_wait_timeout |
| High concurrency on one hot row | Detection cost grows; consider innodb_deadlock_detect = OFF and a short innodb_lock_wait_timeout (MySQL's own advice), accepting that cycles last until the timeout |
| Isolation level | Does not change deadlock possibility; Repeatable Read adds gap locks, which add cycles |
SQL Server and Oracle in brief Good to know
SQL Server's lock monitor runs on a short period (it speeds up when deadlocks are found), picks the victim by DEADLOCK_PRIORITY then rollback cost, and reports error 1205: "Transaction (Process ID n) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction." The graph is available as XML (xml_deadlock_report in the default system_health Extended Events session, or trace flags 1204 / 1222 to the error log). Oracle raises ORA-00060: deadlock detected while waiting for resource in one session, rolls back only its statement, and writes a trace file; the session must still ROLLBACK or continue deliberately. These two descriptions are from the vendors' documentation and were not saved with this page's sources; verify against your version.
Reading a deadlock report
PostgreSQL. DeadLockReport() builds one "waits for" line per participant, sends those to the client, and adds each process's query for the server log. The format strings in deadlock.c are Process %d waits for %s on %s; blocked by process %d. and Process %d: %s, followed by the hint See server log for query details.
ERROR: deadlock detected
DETAIL: Process 4121 waits for ShareLock on transaction 8814; blocked by process 4130.
Process 4130 waits for ShareLock on transaction 8813; blocked by process 4121.
Process 4121: UPDATE accounts SET balance = balance + 10 WHERE id = 2
Process 4130: UPDATE accounts SET balance = balance + 10 WHERE id = 1
HINT: See server log for query details.
CONTEXT: while updating tuple (0,2) in relation "accounts"(Illustrative, assembled from the format strings; the CONTEXT line is typical and varies by statement.)
| Piece | How to read it |
|---|---|
Process 4121 waits for ShareLock on transaction 8814 | A row-lock waiter queues on the holder's transaction id, with a ShareLock on it (transactionid lock) |
blocked by process 4130 | The next node in the cycle; the last line points back to the first |
Lock type other than transaction | relation, tuple, advisory: the second lock names the object (table, page/tuple, advisory key) |
Process N: <query> | The statement that was running when the wait began, not necessarily the one that took the first lock |
| Missing statements | Earlier statements in each transaction took the held locks; find them via log_statement, application logs or auto_explain |
With log_lock_waits = on you also get lines such as process 4121 still waiting for ShareLock on transaction 8814 after 1000.113 ms followed by DETAIL: Process holding the lock: 4130. Wait queue: 4121. (the format comes from PostgreSQL's proc.c, which is not in this page's saved sources).
InnoDB. SHOW ENGINE INNODB STATUS prints only the last deadlock in the LATEST DETECTED DEADLOCK section; with innodb_print_all_deadlocks = ON every one goes to the error log.
------------------------
LATEST DETECTED DEADLOCK
------------------------
*** (1) TRANSACTION:
TRANSACTION 4117, ACTIVE 5 sec starting index read
LOCK WAIT 3 lock struct(s), 2 row lock(s)
UPDATE accounts SET balance = balance + 10 WHERE id = 2
*** (1) HOLDS THE LOCK(S):
RECORD LOCKS ... index PRIMARY of table `lab`.`accounts` trx id 4117 lock_mode X locks rec but not gap
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS ... index PRIMARY of table `lab`.`accounts` trx id 4117 lock_mode X locks rec but not gap waiting
*** (2) TRANSACTION:
TRANSACTION 4118, ACTIVE 3 sec starting index read
UPDATE accounts SET balance = balance + 10 WHERE id = 1
*** (2) HOLDS THE LOCK(S): ... id 2 ...
*** (2) WAITING FOR THIS LOCK TO BE GRANTED: ... id 1 ...
*** WE ROLL BACK TRANSACTION (2)(Illustrative skeleton; real output has more fields and differs by version.)
| Section | Meaning |
|---|---|
(1) TRANSACTION / (2) TRANSACTION | The two (or more) participants and the statement each was running |
HOLDS THE LOCK(S) | What each already owns: index, lock_mode (X, S), rec but not gap, gap before rec, insert intention |
WAITING FOR THIS LOCK TO BE GRANTED | The request that closed the cycle |
WE ROLL BACK TRANSACTION (n) | The victim |
SQL Server. The deadlock graph has <victim-list>, <process-list> (each with inputbuf, waitresource, isolationlevel, priority) and <resource-list> (key, page or object locks with owner-list and waiter-list). Read owners and waiters to find the cycle; the resource name shows whether an index or a lookup order is involved.
Oracle. The trace file shows a "Deadlock graph" with the resource names and the waiting sessions; the common root causes are the same plus unindexed foreign keys and bitmap-index maintenance.
Solving deadlocks
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Lock ordering | Sort ids; lock all rows in one ORDER BY id FOR UPDATE | Removes circular wait | Needs the full set of keys up front; must be applied in every code path |
Key-ordered UPDATE / FOR UPDATE | CTE with ORDER BY ... FOR UPDATE, or MySQL UPDATE ... ORDER BY | Fixes plan-order cycles | Extra statement |
| Batching in id order | Process chunks of sorted ids, one transaction per chunk | Short locks, no cycles between workers | More round trips; partial progress on failure |
| Shorter transactions | Do slow work outside; lock last, commit first | Smaller collision window | Needs design effort |
| No user interaction inside a transaction | Version column for think time | No locks across user time | Conflict handling in the UI |
| Strongest lock first | FOR UPDATE / FOR NO KEY UPDATE instead of read then upgrade | Avoids lock upgrade cycles | Locks earlier |
FOR NO KEY UPDATE on parents | Does not conflict with FK key shares | Removes pattern 2 | PostgreSQL-specific |
READ COMMITTED on InnoDB | No gap locks for searches | Removes pattern 4 | Phantoms; binlog format must be ROW |
NOWAIT / SKIP LOCKED | Never wait for a held row | No cycles; ideal for queues | Caller handles "busy" or "missing" rows |
| Atomic updates | SET x = x + $1 with no prior read | One lock instead of two | Only for single-row arithmetic |
| Retry with jitter | Re-run the whole transaction | Absorbs the cycles you cannot design out | Needs idempotent work |
| Timeouts | lock_timeout, innodb_lock_wait_timeout | Bounds waits and distributed cycles | Errors instead of progress |
Lock ordering
-- PostgreSQL / MySQL 8: one statement, defined order, strongest mode you need
BEGIN;
SELECT id FROM accounts WHERE id IN (7, 3, 5) ORDER BY id FOR UPDATE; -- PostgreSQL: FOR NO KEY UPDATE if the key is not changed
UPDATE accounts SET balance = balance - 10 WHERE id = 7;
UPDATE accounts SET balance = balance + 10 WHERE id = 3;
COMMIT;The order is only guaranteed within that statement; every other path that touches these rows (a cascade, a trigger, another service) must obey the same rule. Define the rule once for the whole system: by primary key within a table; by table name then key across tables.
Batching in id order
A background job that updates a million rows should work in chunks of sorted ids so its locks are short and ordered:
-- keyset loop: each chunk is its own short transaction
WITH chunk AS (
SELECT id FROM orders WHERE id > $1 AND status = 'pending' ORDER BY id LIMIT 500 FOR UPDATE SKIP LOCKED
)
UPDATE orders o SET status = 'archived' FROM chunk WHERE o.id = chunk.id RETURNING o.id;Retry with jitter and idempotent work
A retry re-runs the transaction from the top, so the work inside must be safe to run twice. It is when the transaction touches only the database (it was rolled back) and the outside effects are issued after commit, ideally with an idempotency key so a duplicate request is harmless (Idempotent Consumers).
Go: sorted locking and the retry wrapper
SortedIDs and ApplyCredits lock the batch in ascending id order with one statement:
// Package main shows batching in id order: lock every row the unit of work
// will touch up front, sorted and de-duplicated, then write.
package main
import (
"context"
"fmt"
"os"
"slices"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// SortedIDs returns the ids ascending with duplicates removed. Two requests
// that name the same rows in different orders produce the same slice.
func SortedIDs(ids []int64) []int64 {
out := slices.Clone(ids)
slices.Sort(out)
return slices.Compact(out)
}
// ApplyCredits locks all affected accounts in ascending id order with a single
// statement (FOR NO KEY UPDATE is enough: we never change the key), then
// applies every credit. The caller wraps this in a retry as a safety net.
func ApplyCredits(ctx context.Context, tx pgx.Tx, credits map[int64]int64) error {
ids := make([]int64, 0, len(credits))
for id := range credits {
ids = append(ids, id)
}
ids = SortedIDs(ids)
if _, err := tx.Exec(ctx,
`SELECT id FROM accounts WHERE id = ANY($1) ORDER BY id FOR NO KEY UPDATE`, ids); err != nil {
return err
}
for _, id := range ids { // same order as the lock order, by habit
if _, err := tx.Exec(ctx,
`UPDATE accounts SET balance = balance + $2 WHERE id = $1`, id, credits[id]); err != nil {
return err
}
}
return nil
}
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer pool.Close()
err = pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
return ApplyCredits(ctx, tx, map[int64]int64{7: 100, 3: 50, 5: 25})
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}The retry wrapper WithDeadlockRetry from the Go section, re-runs the whole closure on 40P01.
Laravel: sorted ids, attempts and a jittered wrapper
The ApplyCreditsJob in Laravel sorts ids and uses whereIn(...)->orderBy('id')->lockForUpdate(). For backoff use the wrapper below, which delegates "is this a concurrency error" to the framework's own ConcurrencyErrorDetector:
<?php
// app/Support/DeadlockRetry.php: Laravel's DB::transaction($cb, attempts: n)
// retries a deadlock immediately and never at nested depth. This wrapper adds
// exponential backoff with full jitter and gives up after a bounded number of
// attempts. It must own the OUTERMOST transaction.
namespace App\Support;
use Closure;
use Illuminate\Database\ConcurrencyErrorDetector;
use Illuminate\Support\Facades\DB;
use LogicException;
use Throwable;
final class DeadlockRetry
{
public function __construct(
private readonly int $maxAttempts = 5,
private readonly int $baseDelayMs = 20,
private readonly int $maxDelayMs = 500,
) {}
/**
* @template T
*
* @param Closure(): T $work Database work only; it may run more than once.
* @return T
*/
public function run(Closure $work): mixed
{
if (DB::transactionLevel() > 0) {
throw new LogicException('DeadlockRetry must own the outermost transaction.');
}
$detector = new ConcurrencyErrorDetector();
for ($attempt = 1; ; $attempt++) {
try {
// attempts: 1 means Laravel itself never retries; we do, with a delay.
return DB::transaction($work, attempts: 1);
} catch (Throwable $e) {
// At the outermost level Laravel rethrows the original QueryException.
if (! $detector->causedByConcurrencyError($e) || $attempt >= $this->maxAttempts) {
throw $e;
}
$ceiling = min($this->maxDelayMs, $this->baseDelayMs * (2 ** $attempt));
usleep(random_int(0, $ceiling) * 1000);
}
}
}
}Go
Before
Transfer locks the source row, then the destination row. Called as 1 to 2 and 2 to 1 at the same moment, each goroutine holds one row and waits for the other's. Nothing in this code is wrong in isolation; the order depends on the caller.
// Package main shows the classic deadlock: two transfers between the same
// two accounts, each locking rows in the order the request names them.
package main
import (
"context"
"fmt"
"os"
"sync"
"github.com/jackc/pgx/v5/pgxpool"
)
// Transfer locks the source row, then the destination row, then moves money.
// Nothing here is "broken", but the lock order depends on the caller.
func Transfer(ctx context.Context, pool *pgxpool.Pool, from, to, amount int64) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op after Commit
if _, err := tx.Exec(ctx, `SELECT 1 FROM accounts WHERE id = $1 FOR UPDATE`, from); err != nil {
return err
}
if _, err := tx.Exec(ctx, `SELECT 1 FROM accounts WHERE id = $1 FOR UPDATE`, to); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE accounts SET balance = balance - $2 WHERE id = $1`, from, amount); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE accounts SET balance = balance + $2 WHERE id = $1`, to, amount); err != nil {
return err
}
return tx.Commit(ctx)
}
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer pool.Close()
// A -> B and B -> A at the same time: each holds one row and wants the other.
var wg sync.WaitGroup
for _, p := range [][2]int64{{1, 2}, {2, 1}} {
wg.Add(1)
go func() {
defer wg.Done()
if err := Transfer(ctx, pool, p[0], p[1], 10); err != nil {
fmt.Printf("transfer %d -> %d: %v\n", p[0], p[1], err)
}
}()
}
wg.Wait()
}After
Take both locks in a single statement ordered by id, so the order no longer depends on the request, and wrap the transaction in a retry for the case it still happens (another code path, a foreign-key check, a different statement order elsewhere).
// Package main fixes the deadlock by locking rows in ascending id order,
// whatever order the caller named them, and retrying on SQLSTATE 40P01.
package main
import (
"context"
"fmt"
"os"
"sync"
"github.com/jackc/pgx/v5/pgxpool"
)
// Transfer takes both row locks in one statement ordered by id, so every
// transaction acquires them in the same global order.
func Transfer(ctx context.Context, pool *pgxpool.Pool, from, to, amount int64) error {
return WithDeadlockRetry(ctx, 3, func(ctx context.Context) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx) //nolint:errcheck // no-op after Commit
if _, err := tx.Exec(ctx,
`SELECT id FROM accounts WHERE id = ANY($1) ORDER BY id FOR UPDATE`,
[]int64{from, to}); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE accounts SET balance = balance - $2 WHERE id = $1`, from, amount); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE accounts SET balance = balance + $2 WHERE id = $1`, to, amount); err != nil {
return err
}
return tx.Commit(ctx)
})
}
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer pool.Close()
var wg sync.WaitGroup
for _, p := range [][2]int64{{1, 2}, {2, 1}} {
wg.Add(1)
go func() {
defer wg.Done()
if err := Transfer(ctx, pool, p[0], p[1], 10); err != nil {
fmt.Printf("transfer %d -> %d: %v\n", p[0], p[1], err)
}
}()
}
wg.Wait()
}The retry wrapper checks SQLSTATE 40P01 through pgx's *pgconn.PgError, sleeps with exponential backoff and full jitter, and reruns the whole transaction closure.
package main
import (
"context"
"errors"
"math/rand/v2"
"time"
"github.com/jackc/pgx/v5/pgconn"
)
// sqlstateDeadlockDetected is PostgreSQL's SQLSTATE for "deadlock_detected".
const sqlstateDeadlockDetected = "40P01"
func isDeadlock(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == sqlstateDeadlockDetected
}
// WithDeadlockRetry runs fn, which must be a whole transaction, again when
// PostgreSQL aborts it with 40P01. Sleeps use exponential backoff with full
// jitter so the transactions that just collided do not collide again in step.
func WithDeadlockRetry(ctx context.Context, attempts int, fn func(context.Context) error) error {
var err error
for i := 0; i < attempts; i++ {
if err = fn(ctx); err == nil || !isDeadlock(err) {
return err
}
backoff := 20 * time.Millisecond << i
select {
case <-time.After(rand.N(backoff)):
case <-ctx.Done():
return ctx.Err()
}
}
return err
}The Go angle
database/sql returns driver errors unchanged, so you inspect them with errors.As. With pgx, the error is a *pgconn.PgError whose Code field is the SQLSTATE; with lib/pq it is *pq.Error with the same code; with go-sql-driver/mysql it is *mysql.MySQLError with Number 1213 (deadlock) or 1205 (lock wait timeout). Match the code, not the message, since messages are localisable. The retry must wrap the entire transaction, begin to commit, because PostgreSQL has rolled the whole thing back; retrying a single statement inside an aborted transaction only yields "current transaction is aborted". Pass the context.Context into the sleep so a cancelled request does not keep retrying. Jitter matters: two transactions that collided and sleep the same fixed time will usually collide again.
Laravel
Before
Two queued jobs credit the same accounts in whatever order their payloads list them. Each loop iteration takes one row lock and keeps it to commit.
<?php
// app/Jobs/ApplyCreditsJob.php — two jobs touch the same accounts but in
// whatever order their payloads list them. Run A->B and B->A together and
// each job holds one row lock while waiting for the other's.
namespace App\Jobs;
use App\Models\Account;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
final class ApplyCreditsJob implements ShouldQueue
{
use Queueable;
/** @param array<int, int> $credits account id => amount, in payload order */
public function __construct(private array $credits) {}
public function handle(): void
{
DB::transaction(function () {
foreach ($this->credits as $accountId => $amount) {
// Each iteration takes a row lock and keeps it until commit.
$account = Account::query()->lockForUpdate()->findOrFail($accountId);
$account->balance += $amount;
$account->save();
}
});
}
}After
Sort the ids, lock all rows with one whereIn(...)->orderBy('id')->lockForUpdate() query, then update, and let DB::transaction retry the closure.
<?php
// app/Jobs/ApplyCreditsJob.php — lock every row up front, in ascending id
// order, and let Laravel retry the whole transaction if a deadlock still occurs.
namespace App\Jobs;
use App\Models\Account;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
final class ApplyCreditsJob implements ShouldQueue
{
use Queueable;
/** @param array<int, int> $credits account id => amount */
public function __construct(private array $credits) {}
public function handle(): void
{
$ids = array_keys($this->credits);
sort($ids);
// The second argument is the number of attempts; the callback must be
// safe to run again from the top because the whole transaction is rolled back.
DB::transaction(function () use ($ids) {
// One statement, ORDER BY id, so every job acquires locks in the same order.
$accounts = Account::query()
->whereIn('id', $ids)
->orderBy('id')
->lockForUpdate()
->get()
->keyBy('id');
foreach ($ids as $id) {
$accounts[$id]->increment('balance', $this->credits[$id]);
}
}, attempts: 3);
}
}The Laravel angle
The Laravel 13 database documentation says the transaction method "accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs. Once these attempts have been exhausted, an exception will be thrown." The retry decision lives in Illuminate\Database\ConcurrencyErrorDetector. It returns true for a PDOException with code 40001 (PostgreSQL serialization failure, and MySQL's SQLSTATE for deadlock 1213) or when the message contains one of: Deadlock found when trying to get lock, deadlock detected, The database file is locked, database is locked, database table is locked, A table in the database is locked, has been chosen as the deadlock victim (SQL Server), Lock wait timeout exceeded; try restarting transaction, a Galera WSREP detected deadlock/conflict message, and Record has changed since last read in table. PostgreSQL's 40P01 is therefore matched through the deadlock detected message, not the code. A plain lock wait timeout (1205) is retried too.
The limits of attempts, all visible in ManagesTransactions:
| Limit | Detail | Workaround |
|---|---|---|
| No delay | The loop continues straight into the next beginTransaction(); colliding requests retry in lockstep | DeadlockRetry above, with jitter |
| No retry when nested | When the transaction level is above 1, Laravel rolls back one level and throws DeadlockException; the source says: "MySQL rolls back the entire transaction so we can't just retry the query" | Own the retry at the outermost DB::transaction |
| Side effects run again | Emails, HTTP calls and cache writes inside the closure repeat on every attempt | DB::afterCommit(...), jobs with afterCommit, an outbox row |
| Original exception at the end | At the outermost level, once attempts are exhausted, you get the original QueryException, not DeadlockException | Catch QueryException and classify with the detector |
Retries 1205 too | A lock wait timeout is retried like a deadlock, which can hide a blocker | Log retries and alert on them |
Retries and failure handling
| Error | Engine | Meaning | Retry? |
|---|---|---|---|
40P01 | PostgreSQL | Deadlock detected; transaction rolled back | Yes, whole transaction |
40001 | PostgreSQL, CockroachDB | Serialization failure | Yes |
1213 | MySQL | Deadlock; transaction rolled back | Yes |
1205 | MySQL | Lock wait timeout; statement only (default) | Roll back first, then retry; investigate the blocker |
1205 | SQL Server | Deadlock victim | Yes |
1222 | SQL Server | Lock request timeout | Maybe; investigate |
ORA-00060 | Oracle | Deadlock; statement rolled back | ROLLBACK, then retry |
55P03 | PostgreSQL | lock_timeout / NOWAIT | Caller decides: busy |
23505, 1062 | PostgreSQL, MySQL | Unique violation | No: the constraint answered |
Rules.
- Retry the whole transaction, never the single statement. After
40P01the transaction is gone. - The retried function must be free of outside effects; issue them after commit with an idempotency key.
- Bound attempts (3-10) and use exponential backoff with full jitter:
sleep(random(0, min(cap, base * 2^n))). - Retry only at the outermost boundary; nested retries re-run on a dead transaction.
- Count retries and deadlocks and alert on the rate (Monitoring).
- After the last attempt, surface the error; do not loop forever.
Monitoring
| Signal | Where | What it tells you |
|---|---|---|
pg_stat_database.deadlocks | PostgreSQL | "Number of deadlocks detected in this database" (cumulative per database) |
pg_stat_database_conflicts.confl_deadlock | PostgreSQL standby | Queries cancelled on a standby due to deadlocks |
Server log ERROR: deadlock detected | PostgreSQL | The participants and statements |
log_lock_waits = on | PostgreSQL | Waits longer than deadlock_timeout, before they turn into cycles |
pg_locks + pg_blocking_pids(pid) | PostgreSQL | Who blocks whom right now |
SHOW ENGINE INNODB STATUS | MySQL | Only the latest deadlock |
innodb_print_all_deadlocks = ON | MySQL | Every deadlock in the error log |
INNODB_METRICS lock_deadlocks, lock_timeouts; Innodb_row_lock_waits, Innodb_row_lock_time | MySQL | Counters for rate graphs (enable the metric if it is off) |
performance_schema.data_lock_waits, sys.innodb_lock_waits | MySQL | Current waits and their blockers |
xml_deadlock_report event | SQL Server | The deadlock graph XML |
| Application retry counter | Your code | The rate users actually feel |
-- PostgreSQL: deadlocks per database since stats reset
SELECT datname, deadlocks FROM pg_stat_database WHERE datname = current_database();
-- Who is blocking whom right now
SELECT a.pid, pg_blocking_pids(a.pid) AS blocked_by, left(a.query, 60) FROM pg_stat_activity a WHERE cardinality(pg_blocking_pids(a.pid)) > 0;Alerting on the deadlock rate. The metric is a counter, so alert on its increase, not its value. A sketch with postgres_exporter (check the metric name your exporter version exposes): increase(pg_stat_database_deadlocks{datname="app"}[15m]) > 0 as a warning, and a sustained rate (for example more than a handful per hour on a steady workload) as a page. A single deadlock a day on a busy system with a working retry is not an incident; a rising trend is a design bug, and the report tells you which two statements to fix (Database Observability).
Choosing a remedy
| Situation | Recommended remedy | Extra technique | Reason |
|---|---|---|---|
| Transfer or multi-account update | Sort ids, one ORDER BY id FOR UPDATE | Retry wrapper, idempotency key | Removes circular wait |
Child inserts racing a parent FOR UPDATE | FOR NO KEY UPDATE on the parent | Lock parents in id order first | No conflict with FK key share |
| Job queue workers | FOR UPDATE SKIP LOCKED | Small batches | Workers never wait on each other |
| InnoDB check-then-insert | Unique index plus catch 1062 | READ COMMITTED for the path | Avoids gap-lock cycles |
| Hot counter | UPDATE ... SET n = n + 1 | Per-shard counters | One lock, no read first |
| Human think time | Version column (optimistic) | Conflict message in UI | No locks across user time |
| Bulk update racing with row updates | CTE with ORDER BY ... FOR UPDATE | Chunks of 500-1000 | Defined order and short locks |
| Cross-database or cross-service | Timeouts, global order, saga | Idempotent steps | No engine sees the whole graph |
| Many waiters on one InnoDB row | Disable detection, short wait timeout | Queue per key | Detection cost dominates |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One database, one lock manager, one detector: every cycle is found and one victim is aborted. The simplest correct design is a retry wrapper at the transaction boundary and a documented lock order (by primary key). Example: an invoicing app where transfer(a, b) sorts [a, b] before locking and DeadlockRetry wraps the controller's transaction.
Modular monolith and multiple databases
Modules share one database but own tables; a deadlock can cross modules (orders locks orders then inventory, shipping locks inventory then orders). Define the lock order at the platform level (by table name then key, or "the module that owns the aggregate locks first"), not per module. With several databases in one process the engines cannot see each other: a transaction holding a lock in database 1 and waiting in database 2 while another does the reverse is invisible to both detectors.
Microservices: sagas, outbox and no cross-service graph
Each service has its own database, so no single wait-for graph exists across services. Cycles happen when services call each other synchronously inside their transactions: service A holds a row lock and calls B over HTTP; B holds a lock and calls A. The detector sees neither cycle; only HTTP timeouts end it.
Service A (DB 1) Service B (DB 2)
1 BEGIN; lock order 17 BEGIN; lock stock 9
2 POST /reserve to B ................> waits for DB 1? calls A /confirm
3 waits for B's reply waits for A's reply -> distributed deadlock
4 client timeout / 30 s client timeout -> both fail; nothing detectedThe cure is architectural: never call another service inside a database transaction; commit locally, publish with an outbox (Transactional Outbox), coordinate with a saga (Saga Pattern) and make each step idempotent so a timeout-and-retry is safe.
Distributed data: replicas, caches and distributed SQL
Replicas do not take part: deadlocks are a primary-side phenomenon (a standby's confl_deadlock counts queries cancelled by recovery conflicts). Distributed locks in a cache or ZooKeeper-style store can deadlock at the application level and rely on lease expiry. Distributed SQL systems add their own detectors (Citus runs a distributed deadlock detector, CockroachDB detects cycles in its transaction wait queues, Spanner uses wound-wait to avoid them; these are from the products' documentation, not saved for this page): see Distributed SQL, Consensus & 2PC. Two plain databases tied together by application code have no detector at all, and timeouts are the only cure: set an explicit timeout on every cross-database wait, take cross-database locks in one global order, and prefer a single writer or a saga.
Scaling path: 1x, 10x, 100x
| Scale | What changes | What to do |
|---|---|---|
| 1x | Deadlocks rare; one code path per row set | Sort ids, retry wrapper, log deadlocks |
| 10x | More concurrent writers; hot rows appear; 1 s detector delay becomes visible as latency | Shorter transactions, batch by id, alert on deadlocks rate, consider lock_timeout |
| 100x | Hot rows dominate; detection cost (InnoDB) or retry storms | Per-key queues, sharded counters, partition by key so one tenant's rows live on one shard, drop cross-row transactions in favour of sagas |
Lab
Two terminals per experiment. Output is described from the formats in the sources; run it and compare, since the process ids and transaction ids will differ. I could not run Docker in the environment that wrote this page, so the outputs below were not captured from a live server.
Setup.
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
docker run -d --name my -e MYSQL_ROOT_PASSWORD=my -e MYSQL_DATABASE=lab -p 3306:3306 mysql:8.4
# PostgreSQL terminals A and B: docker exec -it pg psql -U postgres
# MySQL terminals A and B: docker exec -it my mysql -uroot -pmy lab-- PostgreSQL
ALTER SYSTEM SET log_lock_waits = on;
SELECT pg_reload_conf();
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100), (2, 100);
CREATE TABLE parent (id int PRIMARY KEY, n int NOT NULL DEFAULT 0);
CREATE TABLE child (id int PRIMARY KEY, parent_id int NOT NULL REFERENCES parent (id));
INSERT INTO parent VALUES (1, 0), (2, 0);
-- MySQL
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL) ENGINE=InnoDB;
INSERT INTO accounts VALUES (1, 100), (2, 100);
CREATE TABLE t (id int PRIMARY KEY) ENGINE=InnoDB;
INSERT INTO t VALUES (10), (20);
SET GLOBAL innodb_print_all_deadlocks = ON;Experiment 1: opposite order in PostgreSQL.
A B
1 BEGIN; BEGIN;
2 UPDATE accounts SET balance = balance - 10 WHERE id = 1;
3 UPDATE accounts SET balance = balance - 10 WHERE id = 2;
4 UPDATE accounts SET balance = balance + 10 WHERE id = 2; -- blocks
5 UPDATE accounts SET balance = balance + 10 WHERE id = 1; -- blocks, ~1 s later one gets:
-- ERROR: deadlock detected
-- DETAIL: Process <A> waits for ShareLock on transaction <B>; blocked by process <B>. ...
-- the other session's UPDATE then completes. ROLLBACK both.Read the log (docker logs pg): two "waits for" lines and both queries. Check SELECT deadlocks FROM pg_stat_database WHERE datname = 'postgres'; went up by one. With log_lock_waits on you also see "still waiting for ShareLock ... after 1000... ms".
Experiment 2: the same in MySQL.
A B
1 BEGIN; BEGIN;
2 UPDATE accounts SET balance = balance - 10 WHERE id = 1;
3 UPDATE accounts SET balance = balance - 10 WHERE id = 2;
4 UPDATE accounts SET balance = balance + 10 WHERE id = 2; -- blocks
5 UPDATE accounts SET balance = balance + 10 WHERE id = 1;
-- ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction (immediately, no 1 s wait)Then run SHOW ENGINE INNODB STATUS\G and find LATEST DETECTED DEADLOCK: two transactions, what each holds and waits for, and WE ROLL BACK TRANSACTION (n). The same text is in the error log because innodb_print_all_deadlocks is on.
Experiment 3: the foreign-key deadlock (PostgreSQL).
A B
1 BEGIN; BEGIN;
2 INSERT INTO child VALUES (11, 1); -- key share on parent 1
3 INSERT INTO child VALUES (12, 2); -- key share on parent 2
4 SELECT * FROM parent WHERE id = 2 FOR UPDATE; -- blocks on B's key share
5 SELECT * FROM parent WHERE id = 1 FOR UPDATE; -- 40P01 after ~1 sLook at pg_locks before step 5 (SELECT locktype, mode, granted, pid FROM pg_locks WHERE NOT granted;).
Experiment 4: the fix by ordering and by lock mode.
A B
1 BEGIN; BEGIN;
2 SELECT id FROM parent WHERE id IN (1,2) ORDER BY id FOR NO KEY UPDATE;
3 SELECT id FROM parent WHERE id IN (1,2) ORDER BY id FOR NO KEY UPDATE; -- waits at id 1
4 INSERT INTO child VALUES (13, 1); -- (B is waiting)
5 COMMIT; -- B's SELECT returns; B continues
-- No error. Repeat experiment 1 with both sessions updating id 1 then id 2: also no deadlock; B just waits.Also repeat experiment 3 replacing FOR UPDATE by FOR NO KEY UPDATE: no wait at all, because that mode does not conflict with the foreign-key key share.
Experiment 5: gap-lock deadlock (MySQL, Repeatable Read).
A B
1 BEGIN; BEGIN;
2 SELECT * FROM t WHERE id = 15 FOR UPDATE; -- empty; gap (10,20) locked
3 SELECT * FROM t WHERE id = 16 FOR UPDATE; -- OK, gap locks do not conflict
4 INSERT INTO t VALUES (15); -- blocks
5 INSERT INTO t VALUES (16); -- ERROR 1213
-- Repeat with SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED before BEGIN in both: no deadlock.Experiment 6: a lock wait is not a deadlock (MySQL). In A: BEGIN; UPDATE accounts SET balance = 0 WHERE id = 1; and do nothing. In B: SET SESSION innodb_lock_wait_timeout = 5; UPDATE accounts SET balance = 1 WHERE id = 1; After 5 seconds B gets ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction, and LATEST DETECTED DEADLOCK is unchanged.
Common misconceptions
| Belief | Reality |
|---|---|
| A deadlock means the database is overloaded | It is an ordering problem; it can happen on an idle server |
Raising deadlock_timeout reduces deadlocks | It only delays detection (and the two sessions stay blocked longer) |
| A higher isolation level avoids deadlocks | MySQL: deadlocks come from write operations; Repeatable Read even adds gap-lock cycles |
| Retry only the failed statement | The whole transaction is rolled back (PostgreSQL, InnoDB 1213); rerun from BEGIN |
SELECT ... ORDER BY id FOR UPDATE fixes everything | It orders the locks of that statement only; other statements and code paths can still cross |
1205 and 1213 are the same | 1213 is a cycle (transaction rolled back); 1205 is a timeout (statement only by default) |
| The oldest transaction always wins | PostgreSQL: unpredictable; InnoDB: the smaller one loses; SQL Server: priority then cost |
| Row locks only matter for the rows I update | FK checks lock parent rows; gap locks lock empty space; index scans lock secondary and clustered records |
Laravel attempts is a full retry policy | No backoff, no nested retry, side effects repeat, and it also retries lock wait timeouts |
| Two databases are protected by their detectors | Each sees only its own graph; cross-database cycles end only by timeout |
Cheat sheet
| Topic | What to remember |
|---|---|
| Definition | A cycle in the wait-for graph; waiting cannot resolve it |
| Coffman | Mutual exclusion, hold and wait, no preemption, circular wait; remove circular wait |
| PostgreSQL | deadlock_timeout = 1 s, optimistic waiting, 40P01, report in server log |
| InnoDB | Eager detection, smallest transaction is the victim, 1213; 1205 is a timeout |
| SQL Server | Error 1205, DEADLOCK_PRIORITY, deadlock graph XML in system_health |
| Oracle | ORA-00060, statement rolled back, trace file, index foreign keys |
| Ordering | Sort ids; one ORDER BY id FOR UPDATE; document a global order |
| Foreign keys | FOR NO KEY UPDATE on parents; lock parents before inserting children |
| Gap locks | Read Committed or catch unique violations instead of check-then-insert |
| Retry | Whole transaction, bounded, jittered, idempotent, outermost only |
| Laravel | DB::transaction($fn, attempts: n): no backoff, no nested retry, retries 1205 too |
| Monitor | pg_stat_database.deadlocks, innodb_print_all_deadlocks, alert on the rate |
| Distributed | No global detector: timeouts, global order, sagas, no remote calls inside a transaction |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Draw the wait-for graph for two transfers in opposite order. Which edge closes the cycle? Must-know
Answer
Answer: A holds row 1 and waits for row 2; B holds row 2 and waits for row 1. The second wait closes the cycle A to B to A.
2 — Why does PostgreSQL wait deadlock_timeout before checking? Important
Answer
Answer: The check is expensive and most waits end without a cycle, so it uses optimistic waiting: sleep with a timer and run the detector only if the timer fires.
3 — How does InnoDB choose its victim, and what is the error? Important
Answer
Answer: It picks a small transaction by rows inserted, updated or deleted, and returns error 1213 (SQLSTATE 40001) after rolling it back.
4 — What is the difference between 1213 and 1205? Must-know
Answer
Answer: 1213 is a detected deadlock with the transaction rolled back; 1205 is a lock wait timeout (default 50 s) that rolls back only the statement by default.
5 — Which coffman condition does lock ordering break? Must-know
Answer
Answer: Circular wait.
6 — Why can a parent SELECT ... FOR UPDATE deadlock with child inserts in PostgreSQL, and what is the fix? Important
Answer
Answer: Child inserts take FOR KEY SHARE on the parent row, which conflicts with FOR UPDATE. Use FOR NO KEY UPDATE if the key is unchanged and lock parents in id order first.
7 — Why do two sessions both succeed at SELECT ... FOR UPDATE on a missing id in InnoDB, and then deadlock? Good to know
Answer
Answer: Gap locks of different transactions do not conflict, but each insert needs an insert intention lock that conflicts with the other's gap lock.
8 — What must a retry wrapper do for a deadlock to be safe? Must-know
Answer
Answer: Re-run the whole transaction, bound the attempts, back off with jitter, keep outside effects out of the closure, and retry only at the outermost transaction.
9 — Name two limits of Laravel's attempts. Important
Answer
Answer: No backoff delay; no retry when nested (it throws DeadlockException); side effects repeat; it also retries lock wait timeouts.
10 — How do you detect a rising deadlock rate in PostgreSQL? Important
Answer
Answer: Alert on the increase of pg_stat_database.deadlocks and read the server log for the participants.
11 — Why can two databases deadlock without any engine noticing? Important
Answer
Answer: Each engine sees only its own wait-for graph; the cycle spans both, so only timeouts end it.
Glossary
| Term | Meaning |
|---|---|
| Deadlock | A cycle of transactions each waiting for a lock the next holds |
| Wait-for graph | Nodes are transactions; edge A to B means A waits for a lock B holds |
| Cycle | A path in the graph that returns to its start; the signature of a deadlock |
| Coffman conditions | Mutual exclusion, hold and wait, no preemption, circular wait |
| Lock wait | Waiting for a lock that will be released; ends without intervention |
| Livelock | Actors keep reacting without progress, for example retries in lockstep |
| Starvation | A transaction waits indefinitely while others proceed |
| Victim | The transaction the engine aborts to break a cycle |
deadlock_timeout | PostgreSQL delay (1 s) before the cycle check runs |
| Optimistic waiting | Sleeping first and checking for deadlock only after the timer fires |
| Hard edge / soft edge | PostgreSQL: wait on a held lock / wait caused only by queue order |
40P01 | PostgreSQL SQLSTATE deadlock_detected |
40001 | SQLSTATE for serialization failure; also InnoDB's SQLSTATE for error 1213 |
1213 | MySQL ER_LOCK_DEADLOCK |
1205 | MySQL lock wait timeout; SQL Server deadlock victim |
innodb_deadlock_detect | InnoDB eager detection switch (default ON) |
innodb_lock_wait_timeout | InnoDB row-lock wait limit (default 50 s) |
innodb_print_all_deadlocks | Logs every InnoDB deadlock to the error log |
LATEST DETECTED DEADLOCK | Section of SHOW ENGINE INNODB STATUS with the last deadlock |
log_lock_waits | PostgreSQL logging of waits longer than deadlock_timeout |
lock_timeout | PostgreSQL maximum lock wait; error 55P03 |
ORA-00060 | Oracle deadlock error |
| Deadlock graph | SQL Server XML describing processes, resources and victim |
| Lock ordering | Always acquire locks in one global order |
FOR NO KEY UPDATE | PostgreSQL row lock that does not conflict with foreign-key key shares |
FOR KEY SHARE | Row lock taken on a referenced parent row by foreign-key checks |
| Gap lock / insert intention | InnoDB locks on index gaps and the lock an insert needs there |
SKIP LOCKED / NOWAIT | Skip held rows / fail immediately instead of waiting |
| Retry with jitter | Re-run with exponential backoff plus random delay |
| Idempotent retry | A re-run that has the same effect as running once |
| Distributed deadlock | A cycle across two databases or services that no single engine sees |
pg_stat_database.deadlocks | Per-database counter of detected deadlocks |
References
- PostgreSQL documentation, "13.3.4. Deadlocks" (Explicit Locking). postgresql.org
- PostgreSQL documentation,
deadlock_timeout(Lock Management). postgresql.org - PostgreSQL documentation, Appendix A, error code
40P01. postgresql.org - PostgreSQL source:
src/backend/storage/lmgr/READMEanddeadlock.c(deadlock report format). README, deadlock.c - PostgreSQL documentation,
pg_stat_databaseandlog_lock_waits. postgresql.org - MySQL 8.4 Reference Manual, "Deadlocks in InnoDB" and "Deadlock Detection". innodb-deadlocks, innodb-deadlock-detection
- E. G. Coffman Jr., M. J. Elphick, A. Shoshani, "System Deadlocks", ACM Computing Surveys 3(2), June 1971, DOI 10.1145/356586.356588. Read from a course-hosted copy: PDF
- Laravel 13 documentation, Database: Transactions and "Handling Deadlocks". laravel.com
- Laravel framework source,
ConcurrencyErrorDetector. GitHub - pgx:
pgconn.PgError