MySQL transaction locks: trace blockers and verify timeout behavior
When database updates keep waiting but CPU and disk activity do not rise with them, check transaction locks before adding more I/O threads. The connection holding a lock may have stopped executing SQL while its transaction remains open. Expanding the connection pool will only put more requests in the queue. Using MySQL 8.4 on Ubuntu 24.04, this guide follows a diagnostic path: record the error, trace the blocker, and verify rollback behavior.
1. Distinguish waits, timeouts, and deadlocks
Collect the error code returned to the application, the time it occurred, the transaction entry point, and the request identifier. Error 1205 means a lock wait exceeded its limit; error 1213 means a deadlock occurred and a victim transaction was selected. These errors cannot both be handled by retrying the current SQL statement. A deadlock victim has already been rolled back, so the retry must cover the entire business transaction.
Read the current settings before changing global configuration:
SELECT VERSION();
SHOW VARIABLES
WHERE Variable_name IN (
'performance_schema',
'innodb_lock_wait_timeout',
'innodb_rollback_on_timeout',
'innodb_deadlock_detect'
);
Also capture transaction duration and connection pool wait time from the application. Requests still waiting to obtain a connection will not appear in the database's lock wait tables. This guide covers requests that have acquired a connection but are blocked by row locks. A general slowdown in database requests does not mean every request is waiting for the same resource.
A timeout stops the wait; it does not remove the blocker. By default, a lock wait timeout usually rolls back only the current statement. Changes made successfully earlier in the transaction still need to be explicitly committed or rolled back.
The diagnostic account needs permission to inspect the relevant sessions and monitoring views. If you encounter permission errors, request the required access rather than disabling security controls.
2. Follow the wait chain to the blocking transaction
MySQL's sys.innodb_lock_waits presents the waiter, blocker, and locked object together in a single row. Run this query when application requests are waiting:
SELECT
wait_started,
wait_age_secs,
locked_table,
locked_index,
waiting_pid,
blocking_pid,
waiting_query,
blocking_query
FROM sys.innodb_lock_waits
ORDER BY wait_age_secs DESC;
Start with the longest wait, record its blocking_pid, and correlate it with the transaction table:
SELECT
trx_id,
trx_mysql_thread_id,
trx_started,
trx_state,
trx_rows_locked,
trx_rows_modified,
trx_query
FROM information_schema.innodb_trx
ORDER BY trx_started;
blocking_pid is a connection identifier, not an operating system process ID. A blocking transaction may itself be waiting for another transaction. Keep following the relationships until you reach the lock holder at the end of the chain. Terminating only the first waiting request usually does not unblock the requests behind it.
Check for idle connections holding locks
Use SHOW FULL PROCESSLIST to inspect connection states. Sleep means only that the connection is not currently executing a statement. If that connection still appears in innodb_trx, it may have an unfinished transaction. Common causes include an error-handling branch that omits a rollback or an application waiting for an external API response inside a transaction.
An empty blocking_query does not prove that a connection is harmless. Use the connection identifier, transaction start time, and application request records to trace its earlier operations. Diagnostic output may contain business parameters; redact sensitive data before saving it and restrict access.
An empty wait view does not rule out a lock problem. The wait may already have ended, or it may involve metadata locks, which must be checked separately in performance_schema.metadata_locks.
3. Test timeout behavior with two sessions
Run the following experiment on an isolated test instance, not against production application tables. First confirm that the test database does not already exist. If it does, choose another name to avoid overwriting or accidentally deleting existing objects.
CREATE DATABASE lock_lab;
CREATE TABLE lock_lab.accounts (
id INT PRIMARY KEY,
balance INT NOT NULL
) ENGINE=InnoDB;
INSERT INTO lock_lab.accounts VALUES (1, 100), (2, 100);
In session A, start a transaction and acquire an exclusive lock on the first row:
START TRANSACTION;
UPDATE lock_lab.accounts
SET balance = balance - 10
WHERE id = 1;
In session B, change the other row first, then try to update the locked first row:
SET SESSION innodb_lock_wait_timeout = 15;
START TRANSACTION;
UPDATE lock_lab.accounts
SET balance = balance + 5
WHERE id = 2;
UPDATE lock_lab.accounts
SET balance = balance + 10
WHERE id = 1;
While B is waiting, run the queries from the previous section through a third diagnostic connection. Confirm that B is the waiter and A is the blocker. The 15-second setting only shortens the experiment; it is not a recommended production value.
After B receives error 1205, run the following in B:
SELECT @@SESSION.in_transaction;
SELECT * FROM lock_lab.accounts ORDER BY id;
ROLLBACK;
With the default timeout rollback behavior, the earlier successful change to the second row remains part of the uncommitted transaction, and B can see a balance of 105. If whole-transaction rollback on timeout is enabled, the result will differ. Confirm the behavior using both the settings and the actual query results.
Next, execute ROLLBACK in A. The third connection should see a balance of 100 in both rows. Once you have confirmed that both transactions have ended, delete the test database:
DROP DATABASE lock_lab;
4. Decide the transaction outcome before removing the blocker
The preferred approach is to have the application owner commit or roll back the lock-holding transaction normally. Terminating a connection is disruptive: the connection closes, uncommitted work is rolled back, and the application must handle the failure. Do not terminate connections in bulk simply because they have been waiting a long time.
Distinguish statements from connections
KILL QUERY terminates only the current statement and does not guarantee that the entire transaction ends. An idle connection holding locks may not even have a current statement to terminate. KILL CONNECTION closes the connection and triggers rollback of its uncommitted transaction, but rollback can take time. The command returning does not mean that all locks have been released.
Before acting, recheck the connection identifier, account, connection source, and transaction start time. The connection captured in an earlier record may already have ended. Afterward, recheck the wait chain, transaction table, and application errors to make sure you have not replaced blocking with continuous reconnects.
Deadlock evidence is available in the latest deadlock section of SHOW ENGINE INNODB STATUS. This is not a complete history, so save the evidence promptly. Do not disable deadlock detection merely to reduce errors, or use unlimited retries to conceal transaction design problems.
5. Make the fix verifiable
After the fix, retest using the same request path, concurrency conditions, and data range. Check at least the following:
- Wait chains no longer keep building up, and the related old transactions have ended.
- Failure paths explicitly roll back, leaving no open transaction when a connection returns to the pool.
- Deadlock retries cover the entire transaction, with an attempt limit and backoff.
- Multirow updates use a consistent access order rather than competing for locks in opposite orders.
- External API calls run outside transactions, reducing unnecessary waits while locks are held.
Insufficient indexing can also widen the scan and locking scope. Review update predicates alongside execution plans, but do not treat a new index as a universal fix for lock problems. Changing the isolation level changes concurrency semantics and requires separate consistency testing. A lower error count alone is not enough.
Exclusive CPU resources on a dedicated server and directly attached NVMe do not eliminate logical conflicts between transactions. Troubleshooting records should include the error code, wait chain, lock-holding transaction, chosen action, and retest results. A lock incident is only verified as resolved when all of that evidence lines up.
Frequently asked questions
Does a lock wait timeout roll back the entire transaction?
By default, an InnoDB lock wait timeout generally rolls back only the current statement. Earlier changes may remain pending. Check innodb_rollback_on_timeout and explicitly execute ROLLBACK in the failure path.
Can a blocking connection in Sleep state be ignored?
No. Sleep means no statement is currently running; it does not mean the transaction has ended. Correlate innodb_trx with the wait chain before deciding whether to commit, roll back, or terminate the connection.
EPYC 7543P Dedicated Server
From $457/mo