Featured image of post Database Deadlocks, Part 1: The Patterns

Database Deadlocks, Part 1: The Patterns

Deadlock found when trying to get lock; try restarting transaction. That is what MySQL sends back to a payment moving 100 from account 1 to account 2 while a second payment moves 50 from account 2 to account 1. Each payment is two plain UPDATE statements, each one is correct, and on a quiet day the pair can run for years without trouble. Under load, one of them is thrown away. What did the database see that made it cancel one, and why could it not let both finish?

(updated )
TL;DR
A deadlock is two or more transactions (groups of statements the database runs as one unit) each waiting for a lock that another one holds, so that none can finish until the database cancels one. This post covers what a lock is and how long it lasts, how ordinary waiting turns into a loop, how MySQL and PostgreSQL notice the loop and choose which transaction to cancel, and the shapes deadlocks take in real workloads, including the ones where the locked row is one the query never mentions. Part 2 covers reading the deadlock log, retries and prevention.

Here is what the database saw, in outline. If two transactions, like the two payments, could change the same row at the same moment, whichever wrote last would erase the other’s change. So before a transaction changes a row, the database gives it a lock on that row, held until the transaction ends, and anyone else who wants to change the row waits. Usually the wait is short, because the first transaction finishes and the next one goes. But for the two payments it never ends. Payment 1 has changed account 1 and wants account 2, payment 2 has changed account 2 and wants account 1, and each is waiting for the other to finish, which neither can do without the row the other holds. That is a deadlock. Waiting longer cannot end it, so the database looks for exactly this loop and, when it finds one, cancels one transaction, undoing its changes and releasing its locks so the other can finish. The error is the notice that it did. Its advice, to restart the transaction, is also the fallback the PostgreSQL manual offers. It works often enough to hide the cause: neither payment was wrong, the loop came from the order they touched the rows in, and that order is still in the code the next time two payments cross.

A quick reminder about transactions

A payment is two changes, and the application needs both or neither, even through a crash or another payment squeezing in between. Guaranteeing that by hand is hard, so the database does it: a transaction is a group of statements it treats as one unit. BEGIN opens one, COMMIT keeps every change and ROLLBACK undoes every change; a statement sent without BEGIN is a transaction of its own. PostgreSQL and InnoDB, MySQL’s default storage engine, make four guarantees for every transaction, known together as ACID:

GuaranteeWhat it promises
Atomicall of the transaction’s changes happen, or none of them do
Consistentevery rule the schema declares (keys, constraints) holds when the transaction ends
Isolateda transaction is not disturbed by other transactions running at the same moment
Durableonce committed, the changes survive a crash

Deadlocks come from the third row, and there are a lot of transactions to keep apart: every program talking to the database holds a connection, which both engines call a session, PostgreSQL allows 100 by default and MySQL 151, and busy systems run thousands. Isolation has two tools. One is MVCC, multi-version concurrency control, which keeps a changed row’s old version around so that a plain read gets a consistent answer without waiting for anyone (the MVCC posts for PostgreSQL and MySQL cover it). The other is locks, which MVCC does not replace, because two transactions that both want to change the same row still have to take turns. The first row comes in at the end: cancelling a transaction is a rollback, and atomicity guarantees that all of its changes are undone, not some.

A lock lasts until the transaction ends

A lock is a note the database keeps that a transaction is using a row, and what makes deadlocks possible is how long the note stays: from the statement that touches the row until COMMIT or ROLLBACK, however many statements later. It has to. If payment 1 let go of account 1 after its first UPDATE, payment 2 could change the row, and a rollback of payment 1 would then wipe out payment 2’s change as well.

Locks come in two strengths. An exclusive lock is for changing a row. A shared lock is for reading a row while making sure nobody changes it until you are done. Any number of transactions can share a row; an exclusive lock keeps out everyone else:

Lock another transaction already holdsAsking for a shared lockAsking for an exclusive lock
nonegrantedgranted
sharedgrantedwaits
exclusivewaitswaits

UPDATE, DELETE and INSERT take exclusive locks on the rows they change, SELECT ... FOR UPDATE takes one without changing anything, and SELECT ... FOR SHARE takes a shared one. A plain SELECT takes no row lock at either engine’s default settings, because MVCC answers it from row versions (stricter settings change that; the isolation levels post covers them, and this post sticks to the defaults). The engine also takes some locks on its own, for checks the query never spelled out, and those are behind the hardest deadlocks to read.

The table already contains a deadlock. Two transactions that each hold a shared lock on a row, and then each ask for an exclusive one, wait for each other’s shared lock forever. The isolation levels post ran into it on MySQL 8.4.13, whose strictest setting, SERIALIZABLE, makes a plain read take a shared lock. Two deposits that read the same balance and then updated it deadlocked, and in a 20-second run of 16 sessions moving money between 100 accounts, 906 transfers were rolled back as deadlocks (median of three runs).

Waiting on its own is not a deadlock, and a picture tells them apart. Draw a dot for each transaction and an arrow from each waiting transaction to the one it waits for; this is the wait-for graph, and it is what the database inspects. If C waits for B and B waits for A, the chain ends at A, which is still running, and drains when A commits. A deadlock is when the arrows come back around to where they started, a cycle, and nobody in it can move.

The two payments make the smallest cycle there is, and it is the example the PostgreSQL manual uses to explain deadlocks:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
-- Payment 1
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

-- Payment 2, at the same time
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE id = 2;
UPDATE accounts SET balance = balance + 50 WHERE id = 1;
COMMIT;

Payment 1 updates account 1 and holds its lock. Payment 2 updates account 2 and holds that one. Payment 1 moves on to account 2 and has to wait for payment 2; payment 2 moves on to account 1 and has to wait for payment 1. Now the arrows point both ways:

Payment 1 has updated account 1 and holds its lock, payment 2 has updated account 2 and holds its lock, and each waits for the row the other holds, which in the wait-for graph is a cycle from payment 1 to payment 2 and back; the database breaks it by cancelling one payment.

Neither transaction is wrong, and that is the part worth holding on to. Each takes its locks in an order that makes sense on its own; the cycle exists only in how the two orders combine, which no test of one code path will ever show. It needs transactions that hold locks while asking for more, two of them each wanting what the other holds, and no way to take both locks in one step. Remove any of those and it cannot form. The usual one to remove is the second, by making every code path touch rows in the same order (the lower account id first), so the second payment waits behind the first instead of grabbing a row the first one needs. The PostgreSQL manual calls a consistent order “the best defense”, and Part 2 covers making it hold across a whole codebase.

How MySQL and PostgreSQL break the loop

Left alone, a cycle lasts forever. The PostgreSQL manual puts it flatly: “So long as no deadlock situation is detected, a transaction seeking either a table-level or row-level lock will wait indefinitely for conflicting locks to be released.” So both engines run a deadlock detector, which walks the wait-for graph looking for a cycle, picks one transaction in it as the victim, rolls it back and returns an error to its application. The rest carry on as if nothing had happened.

The engines differ in when they look and in whom they pick:

MySQL (InnoDB)PostgreSQL
When the check runson by default, controlled by innodb_deadlock_detectafter a transaction has waited deadlock_timeout, 1 second by default
Who gets cancelledthe smaller transaction, by rows inserted, updated or deleted“difficult to predict and should not be relied upon”
Error the victim gets1213, SQLSTATE 40001: Deadlock found when trying to get lock; try restarting transactionSQLSTATE 40P01: deadlock detected
With the detector offinnodb_deadlock_detect = OFF: the waiters give up after innodb_lock_wait_timeout, 50 seconds by defaultno off switch; a higher deadlock_timeout only delays the check

PostgreSQL’s delay is deliberate: its documentation calls the check “relatively expensive” and bets that most lock waits end on their own, so a deadlock there is noticed only once one of its transactions has waited that long. InnoDB has a quirk of its own: when more than 200 transactions are queued in one wait-for chain, it treats the chain as a deadlock and rolls back the transaction doing the checking, cycle or no cycle.

The victim did nothing wrong, so running it again is safe as far as the database is concerned, and the retry usually succeeds because the other transaction has finished by then. Whether it is safe for the application (an email already sent, a payment provider already called) is a question Part 2 takes up.

Deadlock vs. lock wait timeout
A deadlock is a cycle. A lock wait timeout is a long chain: A waits for B, B is busy with something legitimate that takes too long, and a timer runs out. No cycle, no victim selection. The two errors look alike in application logs but have different causes and different fixes. innodb_lock_wait_timeout (MySQL) and lock_timeout (PostgreSQL, off by default) govern the second; the deadlock detector works independently of both.

Locks the query never asked for

In the payment example every lock is written in the SQL. The deadlocks that take longest to understand involve a lock nobody wrote, taken by the engine to keep some other promise, often on a row or index entry the statement never names. Four come up again and again, three of them at their worst at MySQL’s default settings.

A search that finds nothing still locks

The default isolation level, the setting for how much a transaction is shielded from others, is READ COMMITTED in PostgreSQL and REPEATABLE READ in MySQL. At REPEATABLE READ, a locking search in InnoDB also locks the gaps between the index entries it passes, so that nobody can insert a row into a range the transaction has searched and the same search cannot turn up a new row later. The manual calls the combination a next-key lock, “a record lock on the index record and a gap lock on the gap before the index record.”

A gap lock has a slightly absurd property. Its only job is to keep inserts out, so the manual lets everyone hold one at once: “Gap locks can co-exist.” That turns a very common piece of code, check that a row does not exist and then insert it, into a deadlock. Two requests create the first order for customer 7 at the same moment, both running this:

1
2
3
4
5
6
-- MySQL at its default REPEATABLE READ; orders has an index on customer_id
-- and no rows yet for customer 7
BEGIN;
SELECT id FROM orders WHERE customer_id = 7 FOR UPDATE;  -- finds nothing, locks the gap
INSERT INTO orders (customer_id, amount_cents) VALUES (7, 1000);
COMMIT;

Both searches find nothing and both lock the same gap, which they may do together. Then each inserts into it, and an insert has to wait for any gap lock another transaction holds on that spot. Each waits for the other’s: a cycle over a row neither transaction has written. Run as two sessions on MySQL 8.4.13, half a second apart, the first insert went through once the second session had been rolled back with Deadlock found when trying to get lock, and customer 7 ended with one order.

PostgreSQL has no gap locks at any isolation level, so this shape cannot deadlock there. It cannot protect anything either: on PostgreSQL 18.6 both sessions’ searches found nothing, both inserts went through, and customer 7 ended with two first orders. The PostgreSQL MVCC post measured the difference: an insert into a range another transaction had locked with FOR UPDATE went through in 2.6 ms on PostgreSQL 18.6, while MySQL 8.4.13 at its defaults made it wait the full 2 seconds the other transaction stayed open. At READ COMMITTED, MySQL keeps gap locking only for foreign-key and duplicate-key checks (manual), and in the MySQL MVCC post the same insert then took 6.7 ms. That removes the deadlock and the protection with it: run the same way at READ COMMITTED, both MySQL sessions inserted and customer 7 got two orders, as on PostgreSQL. Only a unique index stops that on either engine. Switching levels changes what the application sees in other ways too, which Part 2 weighs.

A failed insert still takes a lock

A unique index promises that no two rows share a value, and InnoDB keeps that promise with a lock even when the insert fails: an INSERT that hits a duplicate puts a shared lock on the existing index entry before raising the error. The manual shows where that goes wrong with three sessions inserting the same primary key. Session 1 inserts first and holds an exclusive lock on the new row. Sessions 2 and 3 find the duplicate and queue for a shared lock. Then session 1 rolls back, sessions 2 and 3 are granted their shared locks together, and both now need an exclusive lock to insert the row, which each one’s shared lock denies the other. “At this point, sessions 2 and 3 deadlock.” It is the shared-then-exclusive deadlock from the lock table, set off by a check the application never asked for.

INSERT ... ON DUPLICATE KEY UPDATE takes an exclusive lock on a duplicate instead, since it is about to change the row, so two of them hitting the same existing row simply queue; batches of them reaching the same keys in different orders still cycle like the payments. PostgreSQL has no shared lock to upgrade: a second insert of a key another transaction has just inserted waits for that transaction to finish, then fails or goes ahead, and its INSERT ... ON CONFLICT deadlocks come from batches in different key orders (more on unique indexes under concurrent writes).

Foreign keys lock the parent row

A foreign key promises that a child row points at a parent that exists, orders.customer_id at a real customers.id, so both engines lock the parent row while a child row is written, to keep the parent from being deleted underneath it. MySQL takes a shared lock: any statement that has to check the constraint “sets shared record-level locks on the records that it looks at to check the constraint” (manual).

That shared lock is what makes a counter cache deadlock. Say each order also bumps customers.order_count, through application code or a trigger, and two orders for customer 42 arrive at once:

1
2
3
4
5
-- Both orders for customer 42 run this at the same time (MySQL)
BEGIN;
INSERT INTO orders (customer_id, amount_cents) VALUES (42, 1000);  -- shared lock on customer 42
UPDATE customers SET order_count = order_count + 1 WHERE id = 42;   -- needs an exclusive lock on it
COMMIT;

Each insert takes a shared lock on customer 42 through the foreign key, and both are granted, since shared locks coexist. Then each update needs an exclusive lock and waits for the other’s shared lock. On MySQL 8.4.13 the second session got the deadlock error and the first finished, leaving order_count at 1 and one order. The deadlock names customers, a table neither INSERT mentions, which is why this shape so often reaches someone as “why is my UPDATE customers deadlocking against an INSERT INTO orders?”

PostgreSQL takes a weaker lock, FOR KEY SHARE, added in version 9.3, which “blocks other transactions from performing DELETE or any UPDATE that changes the key values, but not other UPDATE” (documentation). So on PostgreSQL the counter updates do not conflict with the foreign-key locks, and the second waits for the first like any two updates of one row: a queue, not a cycle. On PostgreSQL 18.6 the second update finished 0.54 seconds after the first, once the first transaction had committed, and order_count ended at 2. Deleting the customer or changing its id would still conflict. On either engine a hot parent row lines up every write that touches it; Part 2 covers moving such updates off the parent.

An UPDATE locks what it reads

At REPEATABLE READ, InnoDB locks every index entry a locking statement examines, not only the rows it ends up changing. An UPDATE orders SET priority = 'high' WHERE status = 'pending' with no index on status has to read the whole table to find the pending rows, and the manual spells out the result: “every row of the table becomes locked, which in turn blocks all inserts by other users to the table.” Those locks last until the transaction ends, so every transaction touching any row of the table now has someone to wait for, and a slow query has become a deadlock-prone one too. At READ COMMITTED, InnoDB releases the locks on rows that did not match once it has checked the WHERE clause (manual), and PostgreSQL only ever locks the rows an UPDATE changes. An index on status helps at every setting, because the search then examines only the matching entries.

Two indexes, one row
When InnoDB finds rows through a secondary index, it locks the entries in that index and then the row itself in the clustered index, the primary key index that holds the table’s rows (the clustered index post explains that layout). Two transactions that reach the same rows through different indexes, one by status and one by customer_id, take those locks in different orders and can deadlock on the primary key, even though their WHERE clauses share no columns.

When the same work runs many times at once

Every shape so far needs two transactions that happen to collide. Running the same work many times in parallel makes collisions routine. The common case is a pool of identical workers pulling jobs from one table (jobs, outbox, email_queue), each locking a batch with SELECT ... FOR UPDATE. Without an ORDER BY, two workers can lock overlapping rows in different orders: the payment deadlock, spread across copies of code that no review will fault, since every copy is identical. Locking rows in a fixed order removes the cycle, and SKIP LOCKED, which makes a worker pass over rows someone else has locked instead of waiting for them, removes the waiting altogether (Part 2).

Replicas can deadlock on transactions that never overlapped on the primary. A MySQL 8.4 replica applies changes with four worker threads by default (replica_parallel_workers), so transactions that committed one after another on the source can run side by side on the replica, and the manual plans for it: a worker that fails “because of an InnoDB deadlock” retries up to replica_transaction_retries times, 10 by default, before replication stops with an error. PostgreSQL 18 made parallel apply the default for logical replication, with a documented “risk of deadlock when the schemas of the publisher and subscriber differ, although such cases are rare,” also retried automatically. Either way the deadlocks show up on the replica with nothing matching them on the source.

Which shape is firing

Every shape in this post, with the lock behind it and where it can happen at each engine’s settings:

ShapeThe lock behind itMySQL, REPEATABLE READ (default)MySQL, READ COMMITTEDPostgreSQL, READ COMMITTED (default)Evidence
Two transactions, opposite orderthe row locks the statements takecan deadlockcan deadlockcan deadlockdocumented (PostgreSQL manual’s example)
Shared lock, then updateshared locks from FOR SHARE, or from plain reads at MySQL’s SERIALIZABLEcan deadlockcan deadlockcan deadlock with FOR SHAREmeasured on MySQL 8.4.13 at SERIALIZABLE: 906 in 20 s, 16 sessions, median of 3 runs
Check, then insertgap locks from a search that found nothingcan deadlockno gap lock, and no protection against a second insertno gap locks, no deadlock, and no protection eithermeasured on MySQL 8.4.13 and PostgreSQL 18.6 (MySQL READ COMMITTED included)
Duplicate insertshared lock left by the duplicate-key errorcan deadlockcan deadlockwaits for the first inserter insteaddocumented (MySQL manual’s three-session example); READ COMMITTED and PostgreSQL reasoned
Child insert, then parent updateforeign-key lock on the parent rowcan deadlockcan deadlockqueues; the key-share lock does not block the updatemeasured on MySQL 8.4.13 (REPEATABLE READ) and PostgreSQL 18.6; MySQL READ COMMITTED from the manual
Unindexed UPDATElocks on every row it readsevery scanned row lockednon-matching rows releasedonly changed rows lockeddocumented
Worker poolthe opposite-order shape, in identical workerscan deadlockcan deadlockcan deadlockreasoned
Parallel replica applyreplica worker threadsretried up to 10 timesretried up to 10 timeslogical replication in PostgreSQL 18: rare, retrieddocumented

The error the application gets is the same for every row of that table, which is why restarting the transaction treats the symptom of each and the cause of none. The useful first question, when one turns up, is whether the locks in the cycle are ones the SQL asked for. If the deadlock log names a table or an index that the statements never mention, it is one of the middle rows, and reordering the code rarely helps; the fix is in the schema or the isolation level. Reading that log is where Part 2 starts.

SELECT insights FROM experience WHERE downtime = 0; -- Ruslan Tolkachev