Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

MySQL Deadlock & Lock Wait Troubleshooting: Rapid Mitigation & Root Cause Analysis Guide
Databases 35 min read

MySQL Deadlock & Lock Wait Troubleshooting: Rapid Mitigation & Root Cause Analysis Guide

This guide provides a systematic approach to diagnose and resolve MySQL deadlocks (error 1213) and lock wait timeouts (error 1205) using read-only queries on performance_schema, explains InnoDB locking mechanics including gap locks and MDL, and offers safe mitigation strategies with a controlled kill script.

Core Principles: Distinguish Three Lock Failure Modes

When write APIs time out and connection pools saturate with Lock wait timeout exceeded; try restarting transaction (1205) or Deadlock found when trying to get lock (1213), the first reaction is often to KILL blocking queries. This can trigger secondary cascades. The article establishes three independent diagnostic branches:

MDL blocking – threads stuck in Waiting for table metadata lock InnoDB row lock waits – many threads in updating / executing with long Sleep connections

InnoDB deadlocks – error 1213, already auto-resolved by InnoDB

Why InnoDB Deadlocks Frequently Under REPEATABLE-READ

Row locks lock indexes, not rows : Missing or invalidated indexes cause clustered index full scans, locking every scanned record.

Next-Key / Gap lock trap : Under default RR, non-unique index equal/range queries and unique index lookups for non-existent records acquire Gap Locks. Gap Locks are compatible with each other but block Insert Intention Locks. Two transactions holding the same gap lock then attempting inserts into that gap deadlock instantly.

MDL masquerades as global deadlock : A long-running transaction holding SHARED_READ MDL blocks an ALTER TABLE requesting EXCLUSIVE MDL; all subsequent SELECT / UPDATE queue behind the DDL, freezing the entire table.

Golden Five Minutes: Read-Only Four-Step Triage

Step 1: Thread State Distribution (3 seconds)

SELECT STATE, COMMAND, COUNT(*) AS cnt, MAX(TIME) AS max_sec
FROM performance_schema.processlist
WHERE USER NOT IN ('system user','event_scheduler')
GROUP BY STATE, COMMAND ORDER BY cnt DESC LIMIT 20;

Interpretation:

Spike in Waiting for table metadata lock → jump to Step 3 (MDL)

Many updating / executing / Sending data + long Sleep → Step 2 (row lock chain)

All executing with no lock waits → likely CPU/IO saturation from slow queries

Step 2: Locate Row Lock Blocking Chain & Root Blocker (MySQL 8.0)

SELECT w.REQUESTING_ENGINE_TRANSACTION_ID AS waiting_trx_id,
       wt.PROCESSLIST_ID AS waiting_pid,
       LEFT(wt.PROCESSLIST_INFO,120) AS waiting_sql,
       w.BLOCKING_ENGINE_TRANSACTION_ID AS blocking_trx_id,
       bt.PROCESSLIST_ID AS blocking_pid,
       bt.PROCESSLIST_COMMAND AS blocking_cmd,
       bt.PROCESSLIST_TIME AS blocking_idle_sec,
       trx.trx_started AS blocking_trx_started,
       trx.trx_rows_locked AS blocking_rows_locked,
       trx.trx_rows_modified AS blocking_rows_modified,
       dl.OBJECT_SCHEMA AS db_name,
       dl.OBJECT_NAME AS tbl_name,
       dl.INDEX_NAME AS idx_name,
       dl.LOCK_TYPE, dl.LOCK_MODE, dl.LOCK_DATA
FROM performance_schema.data_lock_waits AS w
JOIN performance_schema.data_locks AS dl
  ON w.BLOCKING_ENGINE_LOCK_ID = dl.ENGINE_LOCK_ID
JOIN performance_schema.threads AS wt
  ON w.REQUESTING_THREAD_ID = wt.THREAD_ID
JOIN performance_schema.threads AS bt
  ON w.BLOCKING_THREAD_ID = bt.THREAD_ID
LEFT JOIN information_schema.INNODB_TRX AS trx
  ON w.BLOCKING_ENGINE_TRANSACTION_ID = trx.trx_id
ORDER BY trx.trx_started ASC LIMIT 20;

Key field interpretation: blocking_cmd = Sleep + large blocking_idle_sec → classic uncommitted transaction (external call, exception, or manual BEGIN without COMMIT). Check history via performance_schema.events_statements_history. blocking_rows_modified small (1–100) → low rollback risk, safe to KILL after business confirmation. blocking_rows_modified huge (hundreds of thousands) → red flag ; killing triggers long rollback holding locks, thrashing IO and replication. LOCK_DATA shows supremum pseudo-record or LOCK_MODE contains GAP → gap lock / full-scan lock escalation; verify index usage.

Step 3: MDL Metadata Lock Investigation (when Step 1 hits MDL)

Verify instrumentation:

SELECT NAME, ENABLED, TIMED
FROM performance_schema.setup_instruments
WHERE NAME = 'wait/lock/metadata/sql/mdl';

Query MDL chain:

SELECT t.PROCESSLIST_ID AS pid, t.PROCESSLIST_USER AS db_user,
       t.PROCESSLIST_COMMAND AS cmd, t.PROCESSLIST_TIME AS sec,
       m.OBJECT_SCHEMA AS db_name, m.OBJECT_NAME AS tbl_name,
       m.LOCK_TYPE, m.LOCK_STATUS,
       LEFT(t.PROCESSLIST_INFO,120) AS sql_text
FROM performance_schema.metadata_locks AS m
JOIN performance_schema.threads AS t
  ON m.OWNER_THREAD_ID = t.THREAD_ID
WHERE m.OBJECT_SCHEMA NOT IN ('mysql','performance_schema','sys')
  AND m.OBJECT_NAME IS NOT NULL
ORDER BY m.OBJECT_NAME, m.LOCK_STATUS DESC, t.PROCESSLIST_TIME DESC LIMIT 30;

Find LOCK_STATUS = 'PENDING' + LOCK_TYPE = 'EXCLUSIVE' DDL (usually ALTER TABLE) and the long-held GRANTED shared lock ahead of it. Safest mitigation: kill the pending DDL – near-zero rollback cost, instantly releases queued business traffic.

Step 4: Extract Latest Deadlock Scene (for 1213)

SHOW ENGINE INNODB STATUS/G

Limitation: only retains the most recent deadlock. For high-frequency deadlocks, dynamically enable full logging: SET GLOBAL innodb_print_all_deadlocks = ON; Warning : monitor disk space and logrotate; disable after collecting samples.

Fast Mitigation & Safety Boundaries: When to KILL, When Never to KILL

Blocker Type: Queued DDL

Indicators : MDL EXCLUSIVE + PENDING Recommended Action : Priority KILL <ddl_pid> Risk of Wrong Kill : Near-zero cost, instant release

Blocker Type: Idle uncommitted transaction

Indicators : Sleep + small trx_rows_modified Recommended Action : Confirm ownership, then KILL <pid> Risk of Wrong Kill : Rollback irreversible; caller must redo

Blocker Type: Large write transaction

Indicators : trx_rows_modified ≥ hundreds of thousands

Recommended Action : Forbid blind KILL ; apply business rate-limiting first

Risk of Wrong Kill : Forced rollback takes longer, locks held, kills IO & replication

Blocker Type: Hot-row frequent deadlocks

Indicators : Many 1213, no long blocker

Recommended Action : App-side degrade/rate-limit; no manual KILL Risk of Wrong Kill : Deadlocks already auto-rolled; killing widens error surface

Special warning : KILL is irreversible. Rolling back a large transaction applies undo logs row by row, cannot be interrupted, keeps locks, and saturates disk IO. Sometimes letting it commit under rate-limiting is faster than killing.

Controlled Read-Only Diagnostic & Safe Kill Script (Default Dry-Run)

Script scripts/mysql_lock_triage.sh features:

No hard-coded passwords; uses --defaults-extra-file with 0600 credentials file.

Default read-only triage ( --dry-run), auto-tags risk by trx_rows_modified.

Only executes kill with explicit --apply --kill-pid <id> and enforces trx_rows_modified <= 1000 (configurable).

Deep Root Cause Analysis: Deadlock Log Walk-Through & Three High-Frequency Patterns

Line-by-Line Dissection of a Typical Deadlock Log

Example log shows two transactions inserting ORD-1005 and ORD-1006 into the same gap before ORD-1010 on unique index uk_order_no.

Lock carrier : both conflicts on unique index uk_order_no, record ORD-1010 (heap no 5).

Holds : lock_mode X locks gap before rec – each transaction previously ran SELECT ... FOR UPDATE or DELETE for a non-existent key, acquiring compatible gap locks.

Waits for : insert intention waiting – each insert needs insert intention lock, blocked by the other's gap lock.

Rollback choice : WE ROLL BACK TRANSACTION (2) – InnoDB picks the lighter transaction. Critical : log only shows the final INSERT, not the earlier SELECT ... FOR UPDATE / DELETE that created the gap lock; must correlate with app code or general/slow logs.

Three High-Frequency Deadlock Root Patterns

AB-BA lock order inconsistency : batch updates in different key orders (e.g., [10,20] vs [20,10]).

RR gap lock + insert intention conflict : “check-then-insert” ( SELECT ... FOR UPDATE → INSERT), “delete-then-insert”, or high-concurrency INSERT ... ON DUPLICATE KEY UPDATE.

Secondary vs clustered index cross-locking : Tx A updates via secondary index idx_user_id (locks secondary then clustered); Tx B updates same row via PK and modifies user_id (locks clustered then secondary) → cross-index deadlock.

Reproducible Isolation Experiments

Experiment A: Row Lock Wait (1205) & Blocking Tree Observation

Three sessions: Session 1 BEGIN; UPDATE ... WHERE order_no='ORD-1001'; (hold). Session 2 sets innodb_lock_wait_timeout=15, attempts same update → blocks. Session 3 runs Step 2 query → identifies Session 1 as root blocker ( Sleep, LOCK_MODE X,REC_NOT_GAP). After 15s Session 2 receives 1205.

Experiment B: RR Gap Lock + Insert Intention Deadlock (1213)

Session 1:

BEGIN; SELECT id FROM order_lock_lab WHERE order_no='ORD-1005' FOR UPDATE;

(non-existent, acquires gap before ORD-1010). Session 2: same for ORD-1006 (same gap, compatible). Session 1: INSERT ... ORD-1005 → blocked by Session 2's gap lock. Session 2: INSERT ... ORD-1006 → deadlock, Session 2 rolled back, Session 1 succeeds. SHOW ENGINE INNODB STATUS reproduces the exact log analyzed above.

Root Cause Fixes, Parameter Trade-offs & Long-Term Validation

1. Application & SQL Layer Fixes (Primary)

Enforce uniform lock order : sort keys in memory before batch UPDATE / DELETE.

Replace “check-then-insert” with unique constraint : drop SELECT ... FOR UPDATE, rely on UNIQUE KEY + catch 1062 error for upsert/idempotent return.

Shrink transaction boundaries : never call external HTTP, MQ, or heavy I/O inside DB transaction; EXPLAIN all hot writes to eliminate type=ALL scans and implicit conversions.

Add bounded idempotent retry for 1213 : 2–3 retries with jittered backoff instead of surfacing error to user.

2. Database Parameter & Isolation Level Tuning

Parameter: transaction_isolation

Default / Direction : Default REPEATABLE-READ; consider READ-COMMITTED for high write contention

Coupling Prerequisites : Requires binlog_format=ROW; business must not depend on repeatable-read snapshots

Misconfiguration Impact : Breaks two-read consistency in reconciliation/reporting transactions

Parameter: innodb_lock_wait_timeout

Default / Direction : Default 50s; OLTP tighten to 5–15s

Coupling Prerequisites : Must be slightly below app-layer API timeout

Misconfiguration Impact : Too low → false 1205 on normal contention spikes; too high → pool exhaustion

Parameter: innodb_deadlock_detect

Default / Direction : Default ON; keep ON

Coupling Prerequisites : Only evaluate OFF for single-row extreme hotspot CPU saturation

Misconfiguration Impact : OFF makes deadlocks resolve only via timeout; large timeout = avalanche

Parameter: innodb_print_all_deadlocks

Default / Direction : Default OFF; enable dynamically during investigation

Coupling Prerequisites : Must pair with disk capacity alerts & logrotate

Misconfiguration Impact : Sustained high-frequency deadlocks can fill disk

Setting innodb_lock_wait_timeout : derive from gateway/RPC timeout (e.g., 15s) → set DB timeout 8–10s so lock waits fail fast before pool saturation.

3. Parameter Change Pitfalls & Rollback Verification

Dynamic changes don't affect existing connections : SET PERSIST only applies to new connections. Must rolling-restart app pools or refresh connection pools, then verify via performance_schema.variables_by_thread.

Isolation level change requires canary & full regression : test all multi-step query + aggregation write flows (finance, inventory, accounting) in staging; prefer session-level/connection-string canary before global persist. Rollback with:

SET PERSIST transaction_isolation = 'REPEATABLE-READ';
SET PERSIST innodb_lock_wait_timeout = 50;

then rolling restart pools.

4. Long-Term Monitoring & Alert Baselines (mysqld_exporter + Prometheus)

# 1. Deadlock rate per minute (5m window)
rate(mysql_info_schema_innodb_metrics_lock_lock_deadlocks_total[5m]) * 60

# 2. Avg row lock wait time (ms)
rate(mysql_global_status_innodb_row_lock_time[5m])
/
clamp_min(rate(mysql_global_status_innodb_row_lock_waits[5m]), 1e-6)

# 3. Current concurrent row lock waiters (instant pile-up)
mysql_global_status_innodb_row_lock_current_waits

Note: metric names may vary by exporter version; verify in Prometheus UI before alerting.

P1 Emergency Alert : innodb_row_lock_current_waits > 3× normal peak (e.g., sustained >10) for 1 min, or MDL PENDING threads >0 for >15s → immediate intervention.

P2 Trend Alert : deadlock rate steps up from baseline (e.g., from single-digit daily to >5/min for 10 consecutive minutes) → create ticket to pull error logs and drive code fix, no midnight restart needed.

References & Verification Status

MySQL 8.0 Reference Manual – InnoDB Locking (Record, Gap, Next-Key, Insert Intention Locks)

MySQL 8.0 Reference Manual – Deadlocks in InnoDB & SHOW ENGINE INNODB STATUS output

MySQL 8.0 Reference Manual – Performance Schema data_locks, data_lock_waits, metadata_locks MySQL 8.0 Reference Manual – Metadata Locking & SET PERSIST mechanism

Verification note : all SQL, parameters, and scripts written per MySQL 8.0 official docs; marked as “not executed on live instance”. Example outputs and deadlock logs are labeled “sample output”. Experiments only for isolated test databases.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

deadlockInnoDBMySQLtroubleshootingperformance_schemagap locklock waitMDL

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion