dataiotech Labs
Back to Performance Guide
[MySQL]RUNBOOKMySQL 8.4 LTS / 8.022 minSenior DBA / SRE

[MySQL] RUNBOOK: Lock Diagnosis — InnoDB Lock Waits in 5 Minutes

The sneakiest performance problem is lock waiting. Because the query is not slow, CPU is not high, disk is not full. The query is just waiting. It cannot start because another transaction has not finished. In this guide you will learn how to recognize a lock problem in MySQL, how to find blocking and blocked queries in 5 minutes, how to safely release a lock, how to diagnose deadlocks, and how to prevent locks from recurring. This article completes the MySQL leg of the Performance Pillar.

Production Incident Scenario

Time is 14:07. The application team writes: Pages do not open, but database CPU usage is 15%. Disk is healthy, memory is enough, no slow query. Everything looks normal but nothing works. The DBA looks at `information_schema.innodb_trx` and sees the truth: 40 connections look active but all are in `LOCK WAIT` state. So 40 queries are not working, they are waiting. All of them wait for one transaction. That transaction has been open for 2 hours, contains an `UPDATE`, its owner went to lunch. One open transaction locked the whole system. This runbook shows what to do at that moment.

Summary

The sneakiest performance problem is lock waiting. Because the query is not slow, CPU is not high, disk is not full. The query is just waiting. It cannot start because another transaction has not finished. In this guide you will learn how to recognize a lock problem in MySQL, how to find blocking and blocked queries in 5 minutes, how to safely release a lock, how to diagnose deadlocks, and how to prevent locks from recurring. This article completes the MySQL leg of the Performance Pillar.

Scenario

Time is 14:07. The application team writes: Pages do not open, but database CPU usage is 15%. Disk is healthy, memory is enough, no slow query. Everything looks normal but nothing works. The DBA looks at information_schema.innodb_trx and sees the truth: 40 connections look active but all are in LOCK WAIT state. So 40 queries are not working, they are waiting. All of them wait for one transaction. That transaction has been open for 2 hours, contains an UPDATE, its owner went to lunch. One open transaction locked the whole system. This runbook shows what to do at that moment.

Concept: What Is a Lock, Why Does It Exist?

A lock is the mechanism the database uses to protect consistency. If two people update the same row at the same time, one must wait. Otherwise data corrupts. So a lock is not a bad thing. When used correctly, a lock protects the system.

The problem is a lock lasting longer than necessary. A short lock is normal, a long lock is a disaster.

Most common lock types in InnoDB:

  • •Record Lock: Locks a single row. If a transaction updates a row, it locks that row. Another transaction cannot update that row but can read it. This is normal.
  • •Gap Lock: Locks the gap between rows. Prevents new rows from being inserted. Occurs at REPEATABLE READ isolation level.
  • •Next-Key Lock: Record Lock + Gap Lock combination. Locks a row and the gap in front of it. The default lock type of InnoDB.
  • •Table Lock: Table-level lock. Operations like ALTER TABLE, TRUNCATE lock the table.
  • •Metadata Lock (MDL): Lock related to table structure. Occurs during ALTER TABLE. DDL and DML conflict happens with this lock.

There are 3 root causes of lock problems:

  1. 1Long transaction: As long as the transaction stays open, the lock stays open. If there is an HTTP call, sleep, user waiting inside the transaction, the lock lasts for hours.
  2. 2Wrong access order: If two transactions access the same tables in different order, deadlock occurs.
  3. 3Too many locked rows: An unindexed UPDATE locks 1 million rows instead of 1 row. Everyone waits.

Step 1: Is the System Locked? Understand in 60 Seconds

First check if anyone is waiting.

sql
SELECT trx_state, COUNT(*) AS cnt, MIN(trx_started) AS oldest_start FROM information_schema.innodb_trx GROUP BY trx_state ORDER BY cnt DESC;

▸How to Interpret the Output?

  • •If LOCK WAIT count is 0, you have no lock problem. Look elsewhere.
  • •If LOCK WAIT count is under 5 and short-lived, it is normal. Every system has momentary locks.
  • •If LOCK WAIT count is over 10 and increasing, a lock crisis has started.
  • •If LOCK WAIT count is over 30, you are already in crisis. Go to Step 2 immediately.

Also look at waits via performance_schema:

sql
SELECT EVENT_NAME, COUNT_STAR AS cnt, SUM_TIMER_WAIT / 1000000000000 AS total_wait_sec FROM performance_schema.events_waits_summary_global_by_event_name WHERE EVENT_NAME LIKE '%lock%' ORDER BY SUM_TIMER_WAIT DESC LIMIT 10;

If lock waits constantly increase, the lock problem is becoming chronic.

Step 2: Who Blocks Whom? Find Blocking and Blocked Queries

This is the main query of this runbook. It shows the chain between blocking and blocked.

sql
SELECT waiting.trx_id AS blocked_trx, waiting.trx_mysql_thread_id AS blocked_thread, waiting.trx_started AS blocked_start, blocking.trx_id AS blocking_trx, blocking.trx_mysql_thread_id AS blocking_thread, blocking.trx_started AS blocking_start, TIMESTAMPDIFF(SECOND, waiting.trx_started, NOW()) AS blocked_wait_sec, TIMESTAMPDIFF(SECOND, blocking.trx_started, NOW()) AS blocking_time_sec, LEFT(waiting.trx_query, 120) AS blocked_query, LEFT(blocking.trx_query, 120) AS blocking_query FROM information_schema.innodb_trx waiting JOIN information_schema.innodb_lock_waits waits ON waits.requesting_trx_id = waiting.trx_id JOIN information_schema.innodb_trx blocking ON blocking.trx_id = waits.blocking_trx_id ORDER BY blocked_wait_sec DESC;

▸How to Read the Output?

The table tells you this:

  • •blocked_thread: Waiting query. Innocent, just waiting its turn.
  • •blocking_thread: Query holding the lock. Usually the real culprit.
  • •blocking_query: What the locking query is.

Most of the time when you look at the table you see 20 rows but blocking_thread is always the same. So 20 queries wait for one query. If you solve that one query, 20 queries are saved at once.

Easier way, use the sys schema:

sql
SELECT waiting_trx_id AS blocked_trx, waiting_pid AS blocked_pid, blocking_trx_id AS blocking_trx, blocking_pid AS blocking_pid, waiting_query AS blocked_query, blocking_query AS blocking_query, wait_age AS wait_time FROM sys.innodb_lock_waits ORDER BY wait_age DESC;

The sys.innodb_lock_waits view shows the same chain more readably.

▸Look at Lock Details

Which table, which row is locked?

sql
SELECT lock_id, lock_trx_id, lock_mode, lock_type, lock_table, lock_index, lock_data FROM information_schema.innodb_locks ORDER BY lock_trx_id;

Look at lock_mode values:

  • •S: Shared lock. Taken for reading.
  • •X: Exclusive lock. Taken for writing.
  • •S, GAP: Shared gap lock.
  • •X, GAP: Exclusive gap lock.
  • •X, REC_NOT_GAP: Only row lock, no gap.

If you see many GAP in lock_mode values, REPEATABLE READ isolation level creates gap locks. This exists to prevent phantom reads but increases write contention.

Step 3: Which Table and Which Lock Type?

Check which table, which mode the lock is held in.

sql
SELECT lock_table AS table_name, lock_index AS index_name, lock_mode AS lock_mode, COUNT(*) AS cnt FROM information_schema.innodb_locks GROUP BY lock_table, lock_index, lock_mode ORDER BY cnt DESC;

▸Understand Lock Modes

ModeMeaningDanger
Record LockSingle row lockLow, normal write
Gap LockGap between rowsMedium, blocks new inserts
Next-Key LockRow + gapMedium, default
Table LockTable lockHigh, blocks everything
Metadata LockStructure lockHighest, DDL + DML conflict

If you see Metadata Lock, someone is changing table structure. Probably ALTER TABLE is running. Until that operation finishes, nobody can access the table.

If you see an unindexed UPDATE, the problem is not lock type, it is missing index. An unindexed UPDATE locks the whole table.

Step 4: Decide — 3 Options

In a lock crisis you have 3 options. Which one you choose depends on what the blocking query is.

▸Option A: Wait — Safest Option

If the blocking query has been running for less than 10 seconds and is a normal operation, wait. Because the query will finish, the lock will release, the queue will empty. Intervention can make it worse.

Waiting rule: If the blocking query has been running for less than 2 minutes and shows progress, wait. Do not kill in panic.

▸Option B: Warn the Blocking Query Owner — Communicate with the App Team

If the blocking query has been running for more than 10 minutes and belongs to an application session, first notify the application team. Because if you kill that query, there may be a half-finished operation on the application side.

The sentence you say must be clear:

Blocking Thread 12345 has been open for 42 minutes. Query: UPDATE orders SET status... 20 connections wait for it. If it will not finish in 5 minutes, I will kill it.

Warning without numbers does not work. Say Thread ID, duration, and waiting count.

▸Option C: Kill — Last Resort

If the blocking query has been running for more than 30 minutes, its owner is unreachable, and the system is at a standstill, you must kill it.

sql
-- First verify the thread ID SELECT ID, USER, HOST, TIME, STATE, LEFT(INFO, 150) FROM information_schema.processlist WHERE ID = 12345; -- Then kill it KILL 12345;

▸3 Rules When Killing

  1. 1Never kill in bulk. Kill 1 blocking query, not 20 waiting queries. If you kill waiters, the blocker still stands and new waiters come.
  2. 2First verify the thread ID. If you kill the wrong thread, you kill an innocent report or backup.
  3. 3Monitor after kill. After killing, verify locks released. If not, there is a second blocker in the chain.

Step 5: Deadlock — Two Transactions Wait for Each Other

Deadlock is a special case of locking. Two transactions wait for each other, neither progresses. InnoDB automatically detects deadlock and terminates one of them.

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

To diagnose deadlock, look at the last deadlock info:

sql
SHOW ENGINE INNODB STATUS\G

In the output, look at the LATEST DETECTED DEADLOCK section. It shows which two transactions waited for each other, which queries ran, and which one was terminated.

To monitor deadlocks automatically, turn on logging:

ini
[mysqld] innodb_print_all_deadlocks = ON

This setting writes every deadlock to the error log. It is recommended to be on in production.

The root cause of deadlock is usually access order. If two transactions access the same tables in different order, deadlock occurs.

Example:

text
Transaction A: First orders, then customers Transaction B: First customers, then orders

Both wait for each other. Solution is to use the same order in all transactions. Always first orders, then customers. Order standard reduces deadlock by 90%.

Step 6: Prevent Recurrence — Permanent Solutions

You survived the crisis. Now take 5 permanent measures so it does not repeat.

▸1. Keep Transactions Short

Transactions must not contain:

  • •HTTP calls
  • •External API waiting
  • •User confirmation waiting
  • •Sleep, waiting, long loops
  • •File reading, email sending

A transaction should only do database work. Nothing else. Open the transaction, do the work, close it. A transaction longer than 3 seconds is suspicious. A transaction longer than 30 seconds requires an alarm.

▸2. Do Not Do Unindexed UPDATE

An unindexed UPDATE locks the whole table. Because InnoDB scans the table to find which row to update and locks every row it scans.

sql
-- Bad: If customer_id is unindexed, the whole table is locked UPDATE orders SET status = 'shipped' WHERE customer_id = 123; -- Good: First check the index EXPLAIN UPDATE orders SET status = 'shipped' WHERE customer_id = 123;

If EXPLAIN output shows type = ALL, that UPDATE will lock the table. First add the index, then do the UPDATE.

▸3. Set Up a Long Transaction Alarm

sql
-- List transactions longer than 5 minutes SELECT trx_id, trx_started, TIMESTAMPDIFF(SECOND, trx_started, NOW()) AS time_sec, LEFT(trx_query, 120) FROM information_schema.innodb_trx WHERE TIMESTAMPDIFF(SECOND, trx_started, NOW()) > 300 ORDER BY trx_started;

Add this query to the monitoring system as an alarm. If there is a transaction over 5 minutes, the team should be notified. Intervene before a crisis.

▸4. Set a Lock Timeout

Prevent a query from waiting forever. The innodb_lock_wait_timeout setting terminates a query if it waits longer than the set time for a lock.

ini
[mysqld] innodb_lock_wait_timeout = 10

This setting prevents waiting queries from staying in queue forever. A query waiting 10 seconds gets an error and returns. The application can retry. But the system does not lock up.

Default value is 50 seconds. 10 seconds is recommended in production. If you make it too low, even normal queries get timeouts. 10 is a balanced starting point.

▸5. Set an Access Order Standard

Rule for the whole team: Tables will always be accessed in the same order in transactions.

Example standard:

  1. 1First customers
  2. 2Then orders
  3. 3Then order_items
  4. 4Then payments

This order will be the same in all code. Code accessing in a different order will be rejected in code review.

Verification: Did the Lock Release?

After intervention, run the same queries again:

sql
SELECT trx_state, COUNT(*) AS cnt FROM information_schema.innodb_trx GROUP BY trx_state;

Success criteria:

  • •Did LOCK WAIT count return to 0 or normal?
  • •Did long transaction count drop?
  • •Did waiting queries start working?
  • •Did application error rate return to normal?

If you cannot say yes to these questions, there is a second blocker in the chain. Go back to Step 2, find the new blocker.

7 Common Mistakes

First mistake: Killing waiting queries. Waiters are innocent. Kill the blocker. If you kill waiters, the problem continues.

Second mistake: Judging a lock by its type. Not lock type, but duration is the problem. A 1-second table lock is normal. A 2-hour row lock is a disaster.

Third mistake: Making HTTP calls inside a transaction. A transaction is opened for database work. The outside world is not waited for.

Fourth mistake: Not setting innodb_lock_wait_timeout. Without this setting, one bad query can lock the whole system.

Fifth mistake: Thinking deadlock is a database error. Deadlock is an application design error. Without fixing access order, deadlock does not end.

Sixth mistake: Doing unindexed UPDATE. An unindexed UPDATE locks the whole table. First check with EXPLAIN.

Seventh mistake: Thinking a lock problem is a memory or CPU problem. If the system stops while CPU is 15%, the first place to look is the lock screen. Look at waiting, not CPU.

Checklist

  • LOCK WAIT count checked
  • Long transaction count and longest duration checked
  • Blocking and blocked threads identified
  • Lock mode and table determined
  • Blocking query duration and owner verified
  • If shorter than 2 minutes, waited, not killed in panic
  • If long, application team notified
  • If needed, KILL used, thread verified first
  • After kill, locks released verified
  • If deadlock, access order checked
  • innodb_lock_wait_timeout setting checked
  • innodb_print_all_deadlocks is on checked
  • Long transaction alarm set up
  • Access order standard shared with team
  • Root cause fixed in code

Conclusion

A lock is not the fault of the database. A lock is the mirror of transaction design. With short transactions, correct access order, no unindexed UPDATE, and timeout settings, lock crises can be almost completely prevented. After reading this article, when the system stops you will look not at CPU, but at waiting. You will find not the waiter, but the blocker. And you will not only solve the crisis, but prevent it from recurring.

Performance Pillar Completed — MySQL Leg

With this article, the MySQL leg of the Performance Pillar is complete.

Completed Articles:

  • •Pillar Hub: Performance Guide
  • •[Universal] N+1, EXPLAIN ANALYZE, Connection Pool, Partitioning
  • •[PostgreSQL] pg_stat_statements, Vacuum, Index Selection, Memory Tuning, Lock Diagnosis
  • •[MySQL] Performance Schema, Buffer Pool + Redo Log, Purge + Undo, Lock Diagnosis

Total: Pillar + 12 Clusters

Next Phase:

  • •SQL Server: Performance Dashboard, Buffer Pool, Lock Diagnosis
  • •Oracle: AWR, SGA / PGA Tuning, Lock Diagnosis

Related Articles

  • •Pillar: Performance Guide — Performance & Query Optimization
  • •Cluster: [MySQL] Finding the 20 Most Expensive Queries with Performance Schema
  • •Cluster: [MySQL] InnoDB Buffer Pool and Redo Log Tuning
  • •Cluster: [MySQL] InnoDB Purge and Undo Tuning
  • •Cluster: [PostgreSQL] Lock Diagnosis — pg_locks + pg_stat_activity in 5 Minutes
  • •Next: [SQL Server] Most Expensive Queries with Performance Dashboard
Operational Checklist

Verify each operational safety check before completing the task: