Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

MySQL 1213: Deadlock found when trying to get lock

InnoDB rolled back one transaction to break a lock cycle. Retry the whole transaction, order writes by key and check index coverage.

~5 min readSQL
#mysql#innodb#transactions#deadlocks
Bold white headline reading DEADLOCK 1213 beside two cyan transaction crates crossed by amber locks.

Introduction & Quick Summary

A checkout fails under load and the log shows:

ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction

Quick answer: InnoDB detected a cycle of lock waits between two or more transactions and rolled one of them back to break the cycle. The chosen transaction receives 1213; the other continues. This is not corruption and not a bug in MySQL, it is the engine defending itself.

sql
SHOW ENGINE INNODB STATUS\G -- LATEST DETECTED DEADLOCK section: both transactions, both statements, both locks

Retrying the transaction is mandatory and usually sufficient, but a deadlock that repeats on every request means the access pattern is wrong: rows are locked in different orders, an index is missing so scans lock more rows than intended, or a long transaction holds locks while doing slow work. This guide shows how to read the deadlock report, the four patterns that produce most of them, and a retry loop that is safe to run in production.

Core Mechanics, Signatures & Reproducible Setup

InnoDB uses row-level locks. When a statement needs a lock held by another transaction, it waits; if the wait graph forms a cycle, the deadlock detector picks a victim and rolls it back with error 1213. The related error 1205 (Lock wait timeout exceeded) is different: no cycle, just a wait longer than innodb_lock_wait_timeout.

CREATE TABLE accounts ( id INT PRIMARY KEY, balance INT NOT NULL ) ENGINE=InnoDB; INSERT INTO accounts VALUES (1, 100), (2, 100); -- session A BEGIN; UPDATE accounts SET balance = balance - 10 WHERE id = 1; -- session B BEGIN; UPDATE accounts SET balance = balance + 10 WHERE id = 2; -- session A UPDATE accounts VALUES ... WHERE id = 2; -- waits on B -- session B UPDATE accounts SET balance = balance - 10 WHERE id = 1; -- cycle, one gets 1213
ErrorNumberMeaningResponse
Deadlock found when trying to get lock1213cycle detected, victim rolled backretry whole transaction
Lock wait timeout exceeded1205one wait exceeded the timeoutretry or shorten the transaction
Duplicate entry1062unique constraintapplication decision
Cannot add or update a child row1452foreign key violationfix data order
Serialization failure40001SQLSTATE class shared with 1213retry
Lock typeTaken byBlocks
Record lockUPDATE, DELETE by primary keywrites to that row
Gap lockrange scans under REPEATABLE READinserts into the gap
Next-key lockrecord plus preceding gapboth
Insert intentionINSERTgap holders
Shared lockSELECT ... FOR SHARE, foreign key checksexclusive locks
Auto-inc lockinserts into tables with AUTO_INCREMENTstatement level, not a deadlock source

Key Comparison Table

PatternWhy it deadlocksFix
Two rows updated in opposite orderclassic cycleorder writes by primary key
INSERT ... ON DUPLICATE KEY UPDATE from many workersshared then exclusive lock upgradeuse INSERT ... ON DUPLICATE KEY UPDATE with sorted keys, or REPLACE carefully
Range UPDATE without an indexmany gap locksadd the index, narrow the predicate
Foreign key parent updateshared lock on parent rowupdate parents in a consistent order
Long transaction with network callslocks held for secondsmove I/O outside the transaction
Batch job plus online trafficdifferent orders and rangesseparate window, smaller batches
Isolation levelGap locksDeadlock rateNotes
READ UNCOMMITTEDfewerlowerdirty reads, rarely used
READ COMMITTEDmostly disabledlowerrow-based binlog recommended
REPEATABLE READ (default)yeshigherconsistent reads within a transaction
SERIALIZABLEconverts reads to shared lockshighestrarely appropriate

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Reading the LATEST DETECTED DEADLOCK report

sql
SHOW ENGINE INNODB STATUS\G

The section lists TRANSACTION blocks with the SQL that ran, the index used, and WAITING FOR THIS LOCK plus HOLDS THE LOCK(S). Read the two statements: they usually reveal the different order or the missing index. The LATEST FOREIGN KEY ERROR and TRANSACTIONS sections help when the cycle involves a parent row.

2. Deterministic lock order

python
def transfer(conn, src, dst, amount): first, second = sorted((src, dst)) with conn.cursor() as cur: cur.execute("SELECT id FROM accounts WHERE id IN (%s, %s) ORDER BY id FOR UPDATE", (first, second)) cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (amount, src)) cur.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", (amount, dst))

Every transaction that touches the same set of rows must take locks in the same order. Sorting the ids, or using a single statement with ORDER BY, removes the cycle. The same rule applies to multi-row upserts and to code updating parent and child rows.

3. Indexes, ranges and gap locks

UPDATE orders SET status = 'expired' WHERE created_at < '2026-01-01' AND status = 'open';

Without a composite index on (status, created_at), the statement scans and locks a wide range, including gaps that inserts need. A concurrent insert into the range then deadlocks with the update. EXPLAIN shows type: ALL or a large rows estimate; adding the index narrows both the scan and the lock set.

4. A retry loop that is actually safe

python
import time, random import mysql.connector RETRYABLE = {1213, 1205} def run_tx(pool, fn, attempts=5): for attempt in range(attempts): conn = pool.get_connection() try: conn.start_transaction() result = fn(conn) conn.commit() return result except mysql.connector.Error as err: conn.rollback() if err.errno not in RETRYABLE or attempt == attempts - 1: raise time.sleep((2 ** attempt) * 0.01 * (1 + random.random())) finally: conn.close() raise RuntimeError("unreachable")

Roll back first, then retry the whole transaction. Retrying a single statement inside an aborted transaction fails, and retrying without rollback leaves locks held. Backoff with jitter prevents a thundering herd of retries.

5. Upserts and queues

INSERT INTO counters (name, value) VALUES ('hits', 1) ON DUPLICATE KEY UPDATE value = value + 1;

Many workers inserting overlapping keys can deadlock because the insert takes a shared lock and the duplicate branch upgrades it. Sorting batches by key and using smaller batches reduces the window. SELECT ... FOR UPDATE SKIP LOCKED is the safer queue pattern because workers skip rows another transaction already locked instead of waiting.

6. Batch jobs next to online traffic

DELETE FROM events WHERE created_at < NOW() - INTERVAL 90 DAY LIMIT 1000;

A single large DELETE holds locks for a long time and blocks inserts. Chunked deletes with a LIMIT and a commit between chunks keep lock windows short. Run them off-peak and monitor SHOW ENGINE INNODB STATUS for cycles. Use the SQL formatter to review the statements, and the SQL schema designer to check index coverage before changing a query.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Not retrying at all. A deadlock victim is rolled back; the request must be retried or it becomes a user-visible error.
  • Retrying inside a broken transaction. After 1213 the transaction is gone; a new BEGIN is required.
  • Retrying everything. Only 1213 and 1205 are transient. Retrying 1062 or 1452 hides data problems and multiplies load.
  • Catching the wrong exception. Drivers map 1213 differently: pymysql.err.OperationalError, mysql.connector.Error.errno, SQLSTATE 40001, or a framework-specific DeadlockError. Match on the number, not the message.
  • Raising innodb_lock_wait_timeout. It changes 1205 into a longer wait; it does nothing for 1213.
  • Switching to READ COMMITTED blindly. It removes most gap locks and can reduce deadlocks, but statement-based replication becomes unsafe and some application assumptions about repeatable reads break.
  • innodb_deadlock_detect=OFF. It turns deadlocks into lock-wait timeouts, which fail more slowly and hide the pattern. Use it only for extreme throughput cases.
  • Version notes. MySQL 8.0 reports deadlocks in performance_schema.data_locks and events_errors_summary_by_error, which is easier than parsing the status text; MariaDB 10.6 and later expose information_schema.INNODB_DEADLOCKS. Error text differs slightly between MySQL and MariaDB, the number 1213 does not.

A deadlock is a signal about transaction shape. Fix the order of writes, give the query an index that matches its predicate, keep transactions short, and retry the rest with backoff; that combination keeps 1213 rare and harmless.

Official documentation: MariaDB deadlock detection and lock waits and deadlocks.

Official references

primary documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.