MySQL error 1213 (Deadlock Found When Trying to Get Lock) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.
MySQL rolls back one transaction automatically (the 'deadlock victim') — retry it whole. If that does not apply, the official guidance: restart the transaction that lost the deadlock — the full checklist is below.
MySQL Error Code: 1213
Official name: Deadlock Found When Trying to Get Lock
Service: MySQL
Deadlock found when trying to get lock; try restarting transaction
SHOW ENGINE INNODB STATUS;
-- 'LATEST DETECTED DEADLOCK' shows both transactions and the locks
Pinpoints the two statements that deadlocked so you can order them consistently.
Catch ER_LOCK_DEADLOCK and retry the whole transaction a bounded number of times.
for (let attempt = 0; attempt < 3; attempt++) {
try {
await runTransfer(pool, fromId, toId, amount)
break
} catch (e) {
if (e.code !== 'ER_LOCK_DEADLOCK') throw e
// else retry the full transaction
}
}
Retry on the 1213 error code with a small backoff.
import time
for attempt in range(3):
try:
with session.begin(): transfer(session, a, b, n)
break
except OperationalError as e:
if e.orig.args[0] != 1213: raise
time.sleep(0.05 * attempt)
Re-run the transaction if it loses the deadlock race.
for ($i = 0; $i < 3; $i++) {
try {
$pdo->beginTransaction();
// transfer...
$pdo->commit(); break;
} catch (PDOException $e) {
if ($e->errorInfo[1] !== 1213) throw $e;
}
}
Most often this happens when two or more transactions wait on each other's locks, forming a cycle, or when transactions update the same rows in different orders (A->B vs B->A).
MySQL rolls back one transaction automatically (the 'deadlock victim') — retry it whole.
This page documents fixes for: nodejs-mysql2, python-sqlalchemy, php-pdo.
Recommendations are editorial — DB Error Reference takes no payment or affiliate fees for tool listings.
This page is based on the official MySQL documentation linked below and adds practical troubleshooting guidance on top.