MySQL Lock Contention

Queries getting stuck due to high contention for row or table-level locks, causing delays or timeouts.
  1. Identify the queries causing lock contention by checking the `INFORMATIONSCHEMA.INNODBLOCKS` and `INFORMATIONSCHEMA.INNODBLOCK_WAITS` tables. Use this query to find which transactions are waiting for locks:



SELECT * FROM INFORMATIONSCHEMA.INNODBLOCK_WAITS w
INNER JOIN INFORMATION
SCHEMA.INNODBLOCKS l1 ON w.REQUESTINGTRXID = l1.LOCKTRXID
INNER JOIN INFORMATION
SCHEMA.INNODBLOCKS l2 ON w.BLOCKINGTRXID = l2.LOCKTRXID;

  1. Check which transactions are currently running and might be causing the locks. Execute the following to see the running transactions:



SHOW ENGINE INNODB STATUS\G
Look for the `TRANSACTIONS` section.

  1. Identify long-running transactions that might be responsible for the contention. Use:



SELECT trxid, trxstate, trxstarted, trxrequestedlockid, trxwaitstarted, trxweight, trxmysqlthreadid, trx_query
FROM information
schema.innodbtrx
ORDER BY trx_started;


  1. Kill the transaction that is causing the lock contention, if it's safe to do so, to free up the lock. Use the MySQL `KILL` command followed by the thread ID:



KILL THREAD_ID;
Replace `THREADID` with the `trxmysqlthreadid` from the query in step 3.

  1. Analyze the slow query log to understand why these queries are causing lock contention. Enable it if it's not already enabled:



SET GLOBAL slowquerylog = 'ON';
SET GLOBAL slow
querylog_file = '/path/to/your/log/file.log';
SET GLOBAL long
querytime = 2;

Adjust the `longquerytime` value as needed.

  1. Optimize the queries identified in step 1. Look at the execution plan using `EXPLAIN` and consider adding indexes, rewriting the query, or splitting a long transaction into smaller parts.



EXPLAIN SELECT * FROM yourtable WHERE yourconditions;

Replace the `SELECT` statement with the query causing lock contention.

These are immediate actions you can take to identify and potentially resolve lock contention issues in your MySQL database.

Master

MySQL

in Minutes — Grab the Ultimate Cheatsheet

(Perfect for DevOps & SREs)

Most-used commands
Real-world configs/examples
Handy troubleshooting shortcuts
Your email is safe with us. No spam, ever.

Thankyou for your submission

We have sent the cheatsheet on your email!
Oops! Something went wrong while submitting the form.

MySQL

Cheatsheet

(Perfect for DevOps & SREs)

Most-used commands
Your email is safe with us. No spam, ever.

Thankyou for your submission

We have sent the cheatsheet on your email!
Oops! Something went wrong while submitting the form.

MORE ISSUES

Made with ❤️ in Bangalore & San Francisco 🏢

Doctor Droid