Skip to content

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 forGo to
The one-minute tablesEverything in one minute
Why a deadlock cannot be waited outWhy deadlocks exist
Coffman 1971 and the four conditionsWhere it comes from
Wait-for graph, lock wait, livelock, victim, timeoutsThe 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, OraclePer-engine behaviour and Mechanics
Reading the log of each engineReading a deadlock report
Lock ordering, short transactions, batching, retrySolving deadlocks
Retry table, Go wrapper, Laravel limitsRetries and failure handling
Metrics and alertsMonitoring
Which tool for which situationChoosing a remedy
Two databases, microservices, shardingIn architecture
Reproduce it in PostgreSQL and MySQLLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concepts section.

TermIn plain wordsTiny exampleWhat resolves it
Lock waitYou queue behind someone who will finishT1 holds row 1 for 3 s, T2 waits 3 sThe holder commits or rolls back
DeadlockA ring of waiters; nobody can finish firstA holds 1 wants 2, B holds 2 wants 1The engine aborts one (the victim)
Wait-for graphPicture: transactions as nodes, "waits for" as edgesA to B, B to AA cycle in it means deadlock
LivelockEveryone keeps moving but nobody progressesTwo retriers back off in lockstep foreverRandomised backoff (jitter)
StarvationOne transaction waits unfairly longA reader behind an endless queue of writersFair queues, shorter transactions
Lock timeoutA wait that gave up on a clockinnodb_lock_wait_timeout, lock_timeoutThe waiter errors; the holder is unharmed
VictimThe transaction the engine killsThe smaller one in InnoDBRetry it
Distributed deadlockA cycle that crosses two databases or servicesService A waits on DB 2, service B on DB 1Only timeouts; no engine sees the whole graph

The error you will catch.

EngineSignalRolled backRetry?
PostgreSQLSQLSTATE 40P01 deadlock_detected, message deadlock detectedThe whole transactionYes, from BEGIN
MySQL InnoDBError 1213 (SQLSTATE 40001) Deadlock found when trying to get lock; try restarting transactionThe whole transactionYes
MySQL InnoDBError 1205 (SQLSTATE HY000) Lock wait timeout exceeded; try restarting transactionThe statement only, by defaultCarefully; not a deadlock
SQL ServerError 1205, "chosen as the deadlock victim"The victim's transactionYes
OracleORA-00060: deadlock detected while waiting for resourceThe statement only; the transaction stays openRoll back, then retry

The three things to do.

SituationDo this
Touching several rows or tables in one transactionAlways in the same global order (ascending primary key, or table then key)
Anything that can still deadlockRetry the whole transaction with bounded attempts and jitter
Rising deadlock countRead 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 choiceWhat you gainWhat it costs
Lock as you go (2PL)Simple, correct isolation, no pre-declarationCycles are possible, so you need detection and retry
Declare all locks up front (conservative locking)No deadlocksNeeds to know the rows in advance; fewer concurrent transactions
Never wait (NOWAIT, SKIP LOCKED)No cycles, no waitingThe caller handles "busy"
Optimistic checks (version column)No lock held during think timeRetry 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 ​

  1. "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_timeout only delays the error.
  2. "The database should just wait." Waiting cannot help: each participant needs a lock only another participant can release, and that participant is waiting too.
  3. "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 conditionIn a databaseCan the engine remove it?Which fix targets it
Mutual exclusionWrite locks on a row are exclusiveNo (that is isolation)SKIP LOCKED, optimistic checks avoid the exclusive hold
Hold and waitA transaction keeps earlier locks while asking for later onesNo (locks are held until commit)Lock everything in one statement; short transactions
No preemptionLocks cannot be taken away; only rollback frees themOnly by aborting: the victim's rollback is the preemptionDetection and retry
Circular waitA ring of waitersYes, by orderingGlobal 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.

T1T2T3T4T1 waits for row B (held by T2)T2 waits for row C (held by T3)T3 waits for row A(held by T1)T4 waits for AReading the graphNode = transaction.Edge X to Y = X waits for a lock Y holds.T1, T2, T3: a cycle. Nobody can move,waiting longer never helps: deadlock.T4 (dashed): a plain lock wait. Itresumes when T1 finishes, so it isnot a deadlock (and is freed once thevictim is rolled back).
text
     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 error

Real 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.

EngineHow the graph is built
PostgreSQLWalks the lock manager's wait queues from the process whose timer fired; distinguishes "hard" and "soft" edges (Mechanics)
InnoDBMaintains a wait-for graph of transaction lock requests and checks on every new wait when innodb_deadlock_detect is on
SQL ServerA lock monitor thread periodically searches for cycles
OracleDetects 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.

text
     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
SituationPostgreSQLMySQL InnoDBSQL ServerOracle
Wait without cycleWaits indefinitely unless lock_timeout is setWaits up to innodb_lock_wait_timeout (default 50 s)Waits indefinitely unless SET LOCK_TIMEOUT is setWaits indefinitely unless NOWAIT / WAIT n
Timeout error55P03 lock_not_available (lock_timeout, NOWAIT)1205 ER_LOCK_WAIT_TIMEOUTError 1222ORA-30006 (WAIT n), ORA-00054 (NOWAIT)
Deadlock error40P0112131205ORA-00060
What is rolled back on timeoutThe statementThe statement (whole transaction only with innodb_rollback_on_timeout)The statement; transaction continues unless XACT_ABORT ONThe 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).

text
     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
CauseMitigation
Identical retry delaysExponential backoff with full jitter (random in [0, cap])
Unbounded retriesA maximum of 3-10 attempts, then surface the error
Hot row with a waiting crowdSerialise 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.

EngineWho is the victimSource of the rule
PostgreSQLUsually 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 ServerThe 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)
OracleThe session that detected the cycle gets ORA-00060 for its statementOracle 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).

text
     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 order

Real 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.

SettingEngineDefaultWhat it controls
deadlock_timeoutPostgreSQL1sDelay before the waiter runs the cycle check; also the threshold for log_lock_waits messages
lock_timeoutPostgreSQL0 (off)Maximum wait for any lock, then 55P03
statement_timeoutPostgreSQL0 (off)Maximum duration of one statement
idle_in_transaction_session_timeoutPostgreSQL0 (off)Kills sessions idle inside an open transaction (the classic blocker)
innodb_deadlock_detectInnoDBONEager cycle detection on each wait
innodb_lock_wait_timeoutInnoDB50 secondsMaximum wait for a row lock, then error 1205; the only cure when detection is off
innodb_rollback_on_timeoutInnoDBOFFRoll back the whole transaction on 1205, not only the statement
innodb_print_all_deadlocksInnoDBOFFLog every deadlock to the error log
LOCK_TIMEOUTSQL Server-1 (infinite)Per-session wait limit, error 1222
sql
-- 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.

text
     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: deadlock

Real 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.

text
     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 takesConflicts with the FK key share?Result
FOR UPDATE (PostgreSQL)YesPossible cycle with child inserts
FOR NO KEY UPDATENoNo wait; the usual fix when you do not change the key
Plain UPDATE of a non-key columnNo (it takes FOR NO KEY UPDATE)No wait
UPDATE of the key, or DELETE of the parentYes (FOR UPDATE strength)Waits for child inserts; cycles possible
InnoDB shared FK record lock vs FOR UPDATE on parentYes1213 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.

text
     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: cycle

Real 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):

sql
-- 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.

text
     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
RemedyHowCost
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 indexINSERT ... ON DUPLICATE KEY UPDATE or catch 1062The constraint decides, not a lock
Lock an existing parent rowSELECT ... FROM parent WHERE id = ? FOR UPDATE instead of the gapNeeds a natural parent
Retry on 1213The standard remedyBounded 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).

text
     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 habitHidden lock orderFix
Loop of find()->lockForUpdate()Payload orderOne whereIn()->orderBy('id')->lockForUpdate()
$child->touch() / belongsTo(..., touch: true)Child, then parent rowUpdate parents in a consistent place, or avoid touching hot parents
Observer updating a counter on a parentChild row, then parentAtomic increment() after the main writes, in id order
saveMany in input orderInput orderSort by key first
Bulk upsert()Statement scan orderSort 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)."

text
     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 ms

Real 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 ​

AxisPostgreSQLMySQL InnoDBSQL ServerOracleSQLite
DetectionLazy: timer deadlock_timeout (1 s) then graph walkEager on each wait (default); optional offLock monitor thread, periodic searchOn enqueue waitNone needed: one writer, SQLITE_BUSY
VictimDetector (often the one whose timer fired first)Smallest by rows changedLowest DEADLOCK_PRIORITY, then cheapestThe detecting session's statementn/a
Error40P011213 (40001)1205ORA-00060SQLITE_BUSY / SQLITE_LOCKED
Rolled backWhole transactionWhole transactionVictim's transactionStatement onlyThe statement
ReportServer log, log_lock_waitsSHOW ENGINE INNODB STATUS, innodb_print_all_deadlocksxml_deadlock_report event in system_health, trace flags 1204 / 1222Trace file in the diagnostic dest, alert log messagen/a
Counterpg_stat_database.deadlocksINNODB_METRICS lock_deadlocksPerformance counter Number of Deadlocks/secAWR / v$ views, alert logn/a
Gap locksNoYes at Repeatable ReadKey-range locks at SerializableNo (row versions)n/a

What each database really does.

ProductBehaviour worth knowing
PostgreSQLRows 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 InnoDBRecord, 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 replicationCertification conflicts abort with a deadlock-like error (WSREP detected deadlock/conflict); Laravel retries it
SQL ServerDeadlock graph XML names processes, resources and the victim; row versioning (READ_COMMITTED_SNAPSHOT) removes reader-writer cycles
OracleRow 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
SQLiteA 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)
MongoDBDocument-level locking in WiredTiger; write conflicts raise WriteConflict and the server retries internally; multi-document transactions surface TransientTransactionError
CockroachDBSerializable with retry errors (40001); transaction wait queues detect deadlocks and abort one
RedisSingle-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."

Lock requestconflicts: sleepTimer runs:deadlock_timeout (1s)Timer fires: walkthe wait-for graphLock granted first:no check was neededSoft cycle: reorder waitqueue, no abortHard cycle: abort detectorERROR 40P01no cycle: sleep againfast path
text
     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 impossible

Details that matter in practice:

DetailConsequence
The check costs something, so it is delayedA 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_timeoutFewer wasted checks on busy servers, slower reporting of real deadlocks; ideally above your typical transaction time
Parallel and autovacuumAutovacuum workers can be cancelled if blocking a cycle; parallel workers form lock groups
log_lock_waits = onLogs 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.

SituationBehaviour
Wait-for list longer than 200 transactionsTreated 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 examineSame error
LOCK TABLES or non-InnoDB engines involvedNot seen unless innodb_table_locks = 1 and autocommit = 0; falls back to innodb_lock_wait_timeout
High concurrency on one hot rowDetection 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 levelDoes 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.

text
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.)

PieceHow to read it
Process 4121 waits for ShareLock on transaction 8814A row-lock waiter queues on the holder's transaction id, with a ShareLock on it (transactionid lock)
blocked by process 4130The next node in the cycle; the last line points back to the first
Lock type other than transactionrelation, 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 statementsEarlier 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.

text
------------------------
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.)

SectionMeaning
(1) TRANSACTION / (2) TRANSACTIONThe 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 GRANTEDThe 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 ​

SolutionHowAdvantageCost / limitation
Lock orderingSort ids; lock all rows in one ORDER BY id FOR UPDATERemoves circular waitNeeds the full set of keys up front; must be applied in every code path
Key-ordered UPDATE / FOR UPDATECTE with ORDER BY ... FOR UPDATE, or MySQL UPDATE ... ORDER BYFixes plan-order cyclesExtra statement
Batching in id orderProcess chunks of sorted ids, one transaction per chunkShort locks, no cycles between workersMore round trips; partial progress on failure
Shorter transactionsDo slow work outside; lock last, commit firstSmaller collision windowNeeds design effort
No user interaction inside a transactionVersion column for think timeNo locks across user timeConflict handling in the UI
Strongest lock firstFOR UPDATE / FOR NO KEY UPDATE instead of read then upgradeAvoids lock upgrade cyclesLocks earlier
FOR NO KEY UPDATE on parentsDoes not conflict with FK key sharesRemoves pattern 2PostgreSQL-specific
READ COMMITTED on InnoDBNo gap locks for searchesRemoves pattern 4Phantoms; binlog format must be ROW
NOWAIT / SKIP LOCKEDNever wait for a held rowNo cycles; ideal for queuesCaller handles "busy" or "missing" rows
Atomic updatesSET x = x + $1 with no prior readOne lock instead of twoOnly for single-row arithmetic
Retry with jitterRe-run the whole transactionAbsorbs the cycles you cannot design outNeeds idempotent work
Timeoutslock_timeout, innodb_lock_wait_timeoutBounds waits and distributed cyclesErrors instead of progress

Lock ordering ​

Before: caller decides the orderAfter: ascending id, alwaysABrow 1row 2A: lock 1 then 2B: lock 2 then 1cross = cycleone is aborted (40P01 / 1213)ABrow 1row 2A: 1 then 2B: wants 1 first, waits for Ano cycle: B just waits
sql
-- 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:

sql
-- 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:

go
// 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
<?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.

go
// 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).

go
// 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.

go
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
<?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
<?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:

LimitDetailWorkaround
No delayThe loop continues straight into the next beginTransaction(); colliding requests retry in lockstepDeadlockRetry above, with jitter
No retry when nestedWhen 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 againEmails, HTTP calls and cache writes inside the closure repeat on every attemptDB::afterCommit(...), jobs with afterCommit, an outbox row
Original exception at the endAt the outermost level, once attempts are exhausted, you get the original QueryException, not DeadlockExceptionCatch QueryException and classify with the detector
Retries 1205 tooA lock wait timeout is retried like a deadlock, which can hide a blockerLog retries and alert on them

Retries and failure handling ​

ErrorEngineMeaningRetry?
40P01PostgreSQLDeadlock detected; transaction rolled backYes, whole transaction
40001PostgreSQL, CockroachDBSerialization failureYes
1213MySQLDeadlock; transaction rolled backYes
1205MySQLLock wait timeout; statement only (default)Roll back first, then retry; investigate the blocker
1205SQL ServerDeadlock victimYes
1222SQL ServerLock request timeoutMaybe; investigate
ORA-00060OracleDeadlock; statement rolled backROLLBACK, then retry
55P03PostgreSQLlock_timeout / NOWAITCaller decides: busy
23505, 1062PostgreSQL, MySQLUnique violationNo: the constraint answered

Rules.

  1. Retry the whole transaction, never the single statement. After 40P01 the transaction is gone.
  2. The retried function must be free of outside effects; issue them after commit with an idempotency key.
  3. Bound attempts (3-10) and use exponential backoff with full jitter: sleep(random(0, min(cap, base * 2^n))).
  4. Retry only at the outermost boundary; nested retries re-run on a dead transaction.
  5. Count retries and deadlocks and alert on the rate (Monitoring).
  6. After the last attempt, surface the error; do not loop forever.

Monitoring ​

SignalWhereWhat it tells you
pg_stat_database.deadlocksPostgreSQL"Number of deadlocks detected in this database" (cumulative per database)
pg_stat_database_conflicts.confl_deadlockPostgreSQL standbyQueries cancelled on a standby due to deadlocks
Server log ERROR: deadlock detectedPostgreSQLThe participants and statements
log_lock_waits = onPostgreSQLWaits longer than deadlock_timeout, before they turn into cycles
pg_locks + pg_blocking_pids(pid)PostgreSQLWho blocks whom right now
SHOW ENGINE INNODB STATUSMySQLOnly the latest deadlock
innodb_print_all_deadlocks = ONMySQLEvery deadlock in the error log
INNODB_METRICS lock_deadlocks, lock_timeouts; Innodb_row_lock_waits, Innodb_row_lock_timeMySQLCounters for rate graphs (enable the metric if it is off)
performance_schema.data_lock_waits, sys.innodb_lock_waitsMySQLCurrent waits and their blockers
xml_deadlock_report eventSQL ServerThe deadlock graph XML
Application retry counterYour codeThe rate users actually feel
sql
-- 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 ​

SituationRecommended remedyExtra techniqueReason
Transfer or multi-account updateSort ids, one ORDER BY id FOR UPDATERetry wrapper, idempotency keyRemoves circular wait
Child inserts racing a parent FOR UPDATEFOR NO KEY UPDATE on the parentLock parents in id order firstNo conflict with FK key share
Job queue workersFOR UPDATE SKIP LOCKEDSmall batchesWorkers never wait on each other
InnoDB check-then-insertUnique index plus catch 1062READ COMMITTED for the pathAvoids gap-lock cycles
Hot counterUPDATE ... SET n = n + 1Per-shard countersOne lock, no read first
Human think timeVersion column (optimistic)Conflict message in UINo locks across user time
Bulk update racing with row updatesCTE with ORDER BY ... FOR UPDATEChunks of 500-1000Defined order and short locks
Cross-database or cross-serviceTimeouts, global order, sagaIdempotent stepsNo engine sees the whole graph
Many waiters on one InnoDB rowDisable detection, short wait timeoutQueue per keyDetection 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.

text
     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 detected

The 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 ​

ScaleWhat changesWhat to do
1xDeadlocks rare; one code path per row setSort ids, retry wrapper, log deadlocks
10xMore concurrent writers; hot rows appear; 1 s detector delay becomes visible as latencyShorter transactions, batch by id, alert on deadlocks rate, consider lock_timeout
100xHot rows dominate; detection cost (InnoDB) or retry stormsPer-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.

bash
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
sql
-- 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.

text
     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.

text
     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).

text
     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 s

Look 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.

text
     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).

text
     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 ​

BeliefReality
A deadlock means the database is overloadedIt is an ordering problem; it can happen on an idle server
Raising deadlock_timeout reduces deadlocksIt only delays detection (and the two sessions stay blocked longer)
A higher isolation level avoids deadlocksMySQL: deadlocks come from write operations; Repeatable Read even adds gap-lock cycles
Retry only the failed statementThe whole transaction is rolled back (PostgreSQL, InnoDB 1213); rerun from BEGIN
SELECT ... ORDER BY id FOR UPDATE fixes everythingIt orders the locks of that statement only; other statements and code paths can still cross
1205 and 1213 are the same1213 is a cycle (transaction rolled back); 1205 is a timeout (statement only by default)
The oldest transaction always winsPostgreSQL: unpredictable; InnoDB: the smaller one loses; SQL Server: priority then cost
Row locks only matter for the rows I updateFK checks lock parent rows; gap locks lock empty space; index scans lock secondary and clustered records
Laravel attempts is a full retry policyNo backoff, no nested retry, side effects repeat, and it also retries lock wait timeouts
Two databases are protected by their detectorsEach sees only its own graph; cross-database cycles end only by timeout

Cheat sheet ​

TopicWhat to remember
DefinitionA cycle in the wait-for graph; waiting cannot resolve it
CoffmanMutual exclusion, hold and wait, no preemption, circular wait; remove circular wait
PostgreSQLdeadlock_timeout = 1 s, optimistic waiting, 40P01, report in server log
InnoDBEager detection, smallest transaction is the victim, 1213; 1205 is a timeout
SQL ServerError 1205, DEADLOCK_PRIORITY, deadlock graph XML in system_health
OracleORA-00060, statement rolled back, trace file, index foreign keys
OrderingSort ids; one ORDER BY id FOR UPDATE; document a global order
Foreign keysFOR NO KEY UPDATE on parents; lock parents before inserting children
Gap locksRead Committed or catch unique violations instead of check-then-insert
RetryWhole transaction, bounded, jittered, idempotent, outermost only
LaravelDB::transaction($fn, attempts: n): no backoff, no nested retry, retries 1205 too
Monitorpg_stat_database.deadlocks, innodb_print_all_deadlocks, alert on the rate
DistributedNo global detector: timeouts, global order, sagas, no remote calls inside a transaction

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
DeadlockA cycle of transactions each waiting for a lock the next holds
Wait-for graphNodes are transactions; edge A to B means A waits for a lock B holds
CycleA path in the graph that returns to its start; the signature of a deadlock
Coffman conditionsMutual exclusion, hold and wait, no preemption, circular wait
Lock waitWaiting for a lock that will be released; ends without intervention
LivelockActors keep reacting without progress, for example retries in lockstep
StarvationA transaction waits indefinitely while others proceed
VictimThe transaction the engine aborts to break a cycle
deadlock_timeoutPostgreSQL delay (1 s) before the cycle check runs
Optimistic waitingSleeping first and checking for deadlock only after the timer fires
Hard edge / soft edgePostgreSQL: wait on a held lock / wait caused only by queue order
40P01PostgreSQL SQLSTATE deadlock_detected
40001SQLSTATE for serialization failure; also InnoDB's SQLSTATE for error 1213
1213MySQL ER_LOCK_DEADLOCK
1205MySQL lock wait timeout; SQL Server deadlock victim
innodb_deadlock_detectInnoDB eager detection switch (default ON)
innodb_lock_wait_timeoutInnoDB row-lock wait limit (default 50 s)
innodb_print_all_deadlocksLogs every InnoDB deadlock to the error log
LATEST DETECTED DEADLOCKSection of SHOW ENGINE INNODB STATUS with the last deadlock
log_lock_waitsPostgreSQL logging of waits longer than deadlock_timeout
lock_timeoutPostgreSQL maximum lock wait; error 55P03
ORA-00060Oracle deadlock error
Deadlock graphSQL Server XML describing processes, resources and victim
Lock orderingAlways acquire locks in one global order
FOR NO KEY UPDATEPostgreSQL row lock that does not conflict with foreign-key key shares
FOR KEY SHARERow lock taken on a referenced parent row by foreign-key checks
Gap lock / insert intentionInnoDB locks on index gaps and the lock an insert needs there
SKIP LOCKED / NOWAITSkip held rows / fail immediately instead of waiting
Retry with jitterRe-run with exponential backoff plus random delay
Idempotent retryA re-run that has the same effect as running once
Distributed deadlockA cycle across two databases or services that no single engine sees
pg_stat_database.deadlocksPer-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/README and deadlock.c (deadlock report format). README, deadlock.c
  • PostgreSQL documentation, pg_stat_database and log_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

Built by Morteza Negahi