# Deadlocks in MySQL: find them, prevent them, retry them

> A deadlock is two transactions waiting for each other. InnoDB breaks it by rolling one back, so your code must retry. Here is how to read the report and design the cause away.

Published 2026-11-25 · Language: en · Tags: mysql, innodb, locking

Deadlocks scare people because they look like random failures. They are not random: every deadlock follows from two transactions acquiring locks in different orders. Once you understand the shape, you can usually remove the cause and handle the rest with a retry.

 

## What a deadlock is

 

A deadlock is a cycle of waiting. Transaction 1 holds a lock that transaction 2 wants, while transaction 2 holds a lock that transaction 1 wants. Neither can continue, and waiting longer will not help. The classic wallet example is two transfers in opposite directions.

 

```sql
START TRANSACTION;                                           -- T1 (transfer A to B)
START TRANSACTION;                                           -- T2 (transfer B to A)
UPDATE wallets SET balance = balance - 10 WHERE id = 1;      -- T1 locks wallet 1
UPDATE wallets SET balance = balance - 5 WHERE id = 2;       -- T2 locks wallet 2
UPDATE wallets SET balance = balance + 10 WHERE id = 2;      -- T1 waits for wallet 2
UPDATE wallets SET balance = balance + 5 WHERE id = 1;       -- T2 waits for wallet 1: cycle
```

 

InnoDB detects the cycle immediately, picks one transaction as the victim, rolls it back, and returns error **1213** (SQLSTATE 40001, `ER_LOCK_DEADLOCK`) to that session. The other transaction then proceeds. This is different from error **1205**, a lock wait timeout, which happens when a transaction waits longer than `innodb_lock_wait_timeout` (50 seconds by default) with no cycle at all.

 

## Reading the deadlock report

 

The most recent deadlock is shown in the InnoDB status output, under the heading `LATEST DETECTED DEADLOCK`. For production, enable logging of every deadlock to the error log.

 

```mysql
SHOW ENGINE INNODB STATUS\G
SET GLOBAL innodb_print_all_deadlocks = ON;
```

 

The report lists both transactions, the statements they were running, the locks each one held and the lock each one was waiting for, and which one was rolled back. Read it in this order: find the two statements, find the index and lock type in each "waiting for" line, then ask why the two transactions locked the same rows in different orders.

 

## How to prevent them

 

- **Lock in a consistent order.** If a transaction needs several rows, always lock them in the same order, for example ascending by id. Two transfers then compete for the lower id first, and one simply waits.
- **Keep transactions short.** Do not call an HTTP API, wait for a user or sleep while holding locks. The shorter the lock lifetime, the smaller the window for cycles.
- **Use indexes so statements lock only what they need.** A scan without an index locks many rows and multiplies the chances of overlap.
- **Take all locks up front.** Locking both wallets in one statement is safer than updating them one by one in an order that depends on the request.
- **Consider READ COMMITTED.** It avoids gap locks, which are a frequent source of surprising cycles on insert-heavy tables, provided phantoms are acceptable.

 

```sql
START TRANSACTION;
SELECT id, balance FROM wallets WHERE id IN (1, 2) ORDER BY id FOR UPDATE;
UPDATE wallets SET balance = balance - 10 WHERE id = 1 AND balance >= 10;
UPDATE wallets SET balance = balance + 10 WHERE id = 2;
COMMIT;
```

 

With the ordered locking read, a transfer from 1 to 2 and a transfer from 2 to 1 both lock wallet 1 first. They queue instead of crossing.

 

## Handling the rest: retry

 

Even a careful design can deadlock occasionally, for example when two different code paths touch the same rows. InnoDB rolls the victim back completely, so it is safe to run the whole transaction again from the beginning.

 

- Catch error 1213 (and SQLSTATE 40001) around the whole transaction, not around a single statement.
- Retry a small number of times, three to five, with a short random backoff.
- Make the transaction safe to repeat: use an idempotency key or a unique constraint so a retry cannot apply the effect twice.
- Log retries and alert when the rate rises. A growing count is a design problem, not noise.

 

## Takeaway

 

A deadlock is a lock-ordering bug between two transactions. Read the report to see which statements collide, fix it with consistent ordering, short transactions and proper indexes, and wrap the transaction in a bounded retry for the remaining cases. Treat the number of deadlocks as a health metric.

Source: https://tdphat.io.vn/blog/deadlocks-in-mysql-find-fix-retry
