MySQL Deadlocks: Detect, Read and Retry

MySQL 55 min min read Updated: Nov 27, 2026 Advanced
MySQL Deadlocks: Detect, Read and Retry
Advanced Topic 3 of 3

What Is a Deadlock?

Two transactions each hold a lock the other needs, so both wait forever. InnoDB detects the cycle immediately, chooses a victim (usually the one that changed fewer rows), rolls it back and returns error 1213. The other transaction then continues.

text Session A: UPDATE ... id = 1 (locks row 1) Session B: UPDATE ... id = 2 (locks row 2) Session A: UPDATE ... id = 2 (waits for B) Session B: UPDATE ... id = 1 (waits for A) -> cycle: deadlock

A Real Reproduction

This is the real output of two connections that follow exactly that order:

text A START TRANSACTION B START TRANSACTION A UPDATE accounts SET balance = balance - 10 WHERE id = 1 B UPDATE accounts SET balance = balance - 10 WHERE id = 2 A UPDATE accounts SET balance = balance + 10 WHERE id = 2 B UPDATE accounts SET balance = balance + 10 WHERE id = 1 -> ERROR 1213 Deadlock found when trying to get lock; try restarting transaction B ROLLBACK A COMMIT A SELECT id, balance FROM accounts WHERE id IN (1,2) ORDER BY id -> [[1, 90], [2, 110]]

B was chosen as the victim and rolled back. A committed, so the final balances are 90 and 110: A's transfer was applied, B's was not. B's application code must run the transfer again.

A deadlock is not a bug in MySQL Deadlocks are a normal event in busy systems. The correct response is to retry the whole transaction, not to show an error to the user.

Reading the Last Deadlock

sql SHOW ENGINE INNODB STATUS\G -- look for the section: LATEST DETECTED DEADLOCK -- it lists both transactions, their statements, the locks held and the one rolled back SET GLOBAL innodb_print_all_deadlocks = ON; -- write every deadlock to the error log

These commands need administrator privileges and print server-specific text, so they are shown without output.

How to Prevent Most Deadlocks

  • Same order everywhere. Always touch rows (or tables) in the same order, for example lowest id first. A transfer between accounts 1 and 2 should lock id 1 before id 2 regardless of direction.
  • Short transactions. Less time holding locks means fewer collisions.
  • Lock by index. Statements without a usable index lock many rows.
  • Use READ COMMITTED if gap locks cause conflicts and phantoms are acceptable.
  • Lock what you need at once with one SELECT ... ORDER BY id FOR UPDATE before updating.
sql CREATE TABLE accounts (id INT PRIMARY KEY, balance INT NOT NULL) ENGINE=InnoDB; INSERT INTO accounts VALUES (1, 100), (2, 100); START TRANSACTION; SELECT id FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE; UPDATE accounts SET balance = balance - 10 WHERE id = 2; UPDATE accounts SET balance = balance + 10 WHERE id = 1; COMMIT; SELECT id, balance FROM accounts ORDER BY id;

Result:

id
1
2

Result:

idbalance
1110
290

Locking both rows in id order first means two opposite transfers cannot form a cycle.

Retry Logic in the Application

Retry on error 1213 (deadlock) and also 1205 (lock wait timeout), with a short random pause and a limit. This Python sketch uses PyMySQL and is shown, not executed here:

python import time, random, pymysql RETRY_ERRORS = {1213, 1205} def run_transaction(conn, work, attempts=3): for attempt in range(1, attempts + 1): try: with conn.cursor() as cur: conn.begin() work(cur) conn.commit() return except pymysql.err.OperationalError as e: conn.rollback() if e.args[0] not in RETRY_ERRORS or attempt == attempts: raise time.sleep(random.uniform(0.05, 0.2) * attempt)

The work function must contain all statements of the transaction, so a retry repeats everything from the start.

Monitoring

sql SELECT COUNT(*) AS innodb_metrics_rows FROM information_schema.INNODB_METRICS WHERE NAME = 'lock_deadlocks';

Result:

innodb_metrics_rows
1

The counter lock_deadlocks (and SHOW GLOBAL STATUS LIKE 'Innodb_deadlocks' on some builds) lets monitoring tools alert when deadlocks suddenly increase.

Common Beginner Mistakes

MistakeWhat happensFix
No retry on error 1213Random failures for usersRetry the whole transaction
Retrying only the failed statementInconsistent dataRerun all statements
Different lock order in different code pathsFrequent deadlocksAgree an order
Huge transactionsMore collisionsSplit into small ones
Ignoring the deadlock logSame problem keeps happeningTurn on innodb_print_all_deadlocks

Practice

  1. Reproduce the deadlock with two mysql windows.
  2. Fix it by locking rows in id order.
  3. Write a retry wrapper in your favourite language.
  4. Find the LATEST DETECTED DEADLOCK section on a test server.

Conclusion

A deadlock is two transactions waiting for each other. InnoDB breaks it by rolling one back with error 1213. Prevent with a consistent lock order and short transactions, and always retry the whole transaction.

Quick Summary: deadlock, error 1213, SHOW ENGINE INNODB STATUS, lock order, retry.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators