Database Administration — Mon Apr 06

← Home | ← database-admin

MySQL - DBA Toolkit - Deadlocks

Mon Apr 06 — Detect and investigate MySQL deadlocks using InnoDB status, performance_schema, and the last deadlock report.
#mysql #dba #monitoring #deadlocks #innodb #locking #troubleshooting #tool-kit

They Both Needed Each Other’s Lock

A deadlock is not a random failure.

Two transactions each hold a lock that the other one needs. Neither can proceed. MySQL resolves it by choosing one as the victim and rolling it back. The application receives an error. Most applications retry silently.

Nobody investigated. The pattern repeats.

This script surfaces what happened, who was involved, and what they were fighting over.

Deadlocks.sql
    Loading…
  

Reading the Results

Query 1 — SHOW ENGINE INNODB STATUS

The LATEST DETECTED DEADLOCK section shows the two transactions involved, which locks each held and which they were waiting for, which transaction was rolled back (the victim), and the actual SQL statements from each side.

This only shows the most recent deadlock. It is overwritten every time a new one occurs.

Query 2 — Deadlock Count

A low number is expected on any busy server. A rapidly climbing number means a recurring pattern that needs investigation, not just retry logic.

Query 5 — InnoDB Transactions

ColumnWhat It Tells You
trx_stateRUNNING or LOCK WAIT
wait_secondsHow long this transaction has been blocked
trx_rows_lockedHow many row locks this transaction holds
trx_rows_modifiedHow many rows it has changed (not yet committed)
trx_queryThe SQL currently executing

Long-running transactions with many rows locked are deadlock generators. Find them early.

What to Watch For

SignalWhat It Means
Innodb_deadlocks climbing rapidlyA recurring access pattern is causing repeated deadlocks
Same table appearing in every deadlockIndex design or transaction ordering issue on that table
Long trx_rows_locked countsA transaction is holding too many locks for too long
LOCK WAIT state without a matching deadlockA slower blockage — not a deadlock yet, but could become one
Application retrying errors silentlyDeadlocks may be happening but nobody knows — check error logs

Reducing Deadlocks

Deadlocks are usually fixable at the application level:

  • Access tables in the same order across all transactions
  • Keep transactions short — commit quickly, hold locks for as little time as possible
  • Use appropriate indexes — full table scans take gap locks on far more rows than needed
  • Retry on deadlock (error 1213) — but treat it as a signal, not a solution

Gareth Winterman