Menu

MySQL Error 1213: Deadlock Found When Trying to Get Lock

Fix MySQL Error 1213 by retrying the rolled-back transaction, inspecting the latest deadlock, and keeping lock order consistent.

Posted on By
On this page

MySQL Error 1213 (40001, ER_LOCK_DEADLOCK) means InnoDB detected a deadlock and rolled back one transaction to break the cycle. The message is Deadlock found when trying to get lock; try restarting transaction. Retry the entire rolled-back transaction, not just the last statement. See the MySQL 8.4 error reference and deadlock handling guidance.

Why a deadlock occurs

A deadlock happens when transactions wait on each other in a cycle. For example, transaction A locks row 1 and then requests row 2, while transaction B locks row 2 and then requests row 1. Neither can continue, so InnoDB selects one transaction as the victim and rolls it back. Deadlocks can occur even when each individual statement is valid.

Inspect the latest deadlock

Run the InnoDB status command soon after the error and find the LATEST DETECTED DEADLOCK section:

SHOW ENGINE INNODB STATUS\G

The report identifies the transactions, statements, and locks involved in the most recent deadlock. It retains only the latest deadlock, so capture it before another one replaces it. For recurring deadlocks, temporarily enable logging for every deadlock:

SET GLOBAL innodb_print_all_deadlocks = ON;

This writes deadlock details to the MySQL error log. Turn it off after collecting enough evidence:

SET GLOBAL innodb_print_all_deadlocks = OFF;

Changing this global variable requires appropriate privileges. See innodb_print_all_deadlocks.

Reduce recurring deadlocks

  • Keep transactions short and commit promptly. Do not leave an interactive session open with an uncommitted transaction.
  • Make transactions that update multiple tables or row sets access them in the same order.
  • Add or adjust indexes when they help a statement scan fewer rows and acquire fewer locks. Use EXPLAIN to review the statement’s access path.
  • Avoid locking reads such as SELECT ... FOR UPDATE when a consistent nonlocking read is sufficient.

In application code, retry the complete transaction that InnoDB rolled back. Use bounded retries and make any external side effects safe to repeat; a database rollback cannot undo a message or payment already sent by another system.

Error 1213 differs from Error 1205. A deadlock rolls back the entire victim transaction; a lock wait timeout normally rolls back only the waiting statement. See how to troubleshoot MySQL Error 1205 and the MySQL transaction guide. Browse all MySQL error troubleshooting guides.