Currently Available: Need a skilled Software Developer for your next project?
Categories
Databases MySQL

How MySQL Locking and Concurrency Control Works

When several clients read and change the same MySQL data at once, InnoDB coordinates their transactions so one does not unexpectedly overwrite another’s work. InnoDB relies on two mechanisms to do this. Consistent reads let ordinary queries read a stored version of the data without waiting, while locks force transactions to wait when they need to change the same data or protect a read.

In MySQL 8.4, InnoDB uses row-level locking, and its locks generally protect index records. Because of that, the index a query uses and the portion of that index it scans determine which records InnoDB locks and how much other work it blocks. Once you see how InnoDB ties locks to indexes, you can choose transaction boundaries, indexes, and locking reads that fit your workload. The details below apply to InnoDB; other storage engines can use different locking behavior, as the MySQL 8.4 Reference Manual explains.

Ordinary reads use snapshots, while writes take locks

A plain InnoDB SELECT usually reads a snapshot, which is a view of the data as it existed at a particular point in time. InnoDB does not lock every row that the query returns. If another transaction has modified a row since that snapshot was taken, InnoDB uses stored undo information to rebuild the earlier version. As a result, many readers can run without waiting for writers, and those reads do not stop writers from changing the rows. The InnoDB transaction model explains how InnoDB combines versioned reads with locking.

A transaction holds its locks until it ends. Because MySQL enables autocommit by default, each successful statement normally runs as its own transaction. To group related statements together, a client starts a transaction with START TRANSACTION or BEGIN. Running COMMIT saves the changes and releases the locks, while ROLLBACK cancels the changes and releases the locks. When a transaction stays open for a long time, it holds its locks longer and leaves other transactions waiting. In its deadlock-handling guidance, the manual recommends keeping transactions short and committing promptly after related changes.

A snapshot read will not stop another transaction from changing a row that you plan to update based on what you just read. When a client needs to read a row and then act on it safely, it can use a locking read inside a transaction:

For example, a transaction can run FOR SHARE to verify that a parent row exists and stop another transaction from deleting it before the first transaction inserts a child row. The foreign-key constraint still acts as a separate integrity check. Keep in mind that a locking clause on an outer query does not automatically lock rows read only by a nested subquery; you need to add a locking clause to the subquery when those rows also need protection. You can check the full details in the manual’s locking-read rules.

How index scans shape the locks InnoDB takes

InnoDB places its row locks on index records. Even when a table has no declared index, InnoDB creates a hidden clustered index and uses it for record locking. The index InnoDB picks for a statement therefore decides which records it scans and locks.

InnoDB uses three main lock types on index records:

InnoDB uses next-key locking to help prevent phantom rows, which are new rows that show up in a range query after an earlier read. The InnoDB locking documentation covers how these locks interact.

A locking read, UPDATE, or DELETE can lock every index record it scans, including records that do not match its WHERE condition. A lookup through a suitable unique index for a single unique value is an important exception: InnoDB can lock only the matching index record without locking the preceding gap. Range searches and nonunique indexes can lock more records and gaps.

The index InnoDB uses affects both query speed and how much other work a statement blocks. If a statement lacks a suitable index and scans the entire table, InnoDB can lock every row it encounters and block inserts from other clients. Because InnoDB sets locks based on the query plan and the scan it performs, you cannot tell which records a statement will lock by looking at its WHERE clause alone. The manual’s statement locking details explain how different statements set locks.

How isolation levels change reads and locks

An isolation level controls what data a transaction can see while other transactions are changing it. InnoDB defaults to REPEATABLE READ. Under that level, every consistent read in a transaction uses the snapshot created by its first consistent read. Locking reads and writes still take locks whose scope depends partly on the index lookup or range scan.

Isolation level Behavior that affects reads and locks
REPEATABLE READ InnoDB’s default. Consistent reads in one transaction use the snapshot from its first consistent read. Range locking can use gap or next-key locks.
READ COMMITTED Each consistent read gets a fresh snapshot. For locking reads, UPDATE, and DELETE, InnoDB generally locks index records rather than preceding gaps, though it still uses gap locks for foreign-key and duplicate-key checks. Inserts into gaps can produce phantom rows.
READ UNCOMMITTED Reads can see uncommitted changes, which permits dirty reads. For the locking behavior described here, it otherwise works like READ COMMITTED.
SERIALIZABLE When autocommit is disabled, InnoDB treats plain SELECT statements as shared locking reads. Those reads can wait for changes and increase contention.

The InnoDB isolation-level documentation lays out these behaviors in detail. Switching to READ COMMITTED reduces some gap locking and can reduce the probability of deadlocks in certain cases, though it does not eliminate them. It also gives readers newer snapshots and allows inserts into gaps that REPEATABLE READ can protect.

Inside a REPEATABLE READ transaction, a plain SELECT can return data from an earlier snapshot, while a locking read uses current data. If you mix both read types in the same transaction, your queries can return results that look inconsistent unless you account for those different rules.

Handling deadlocks and lock-wait timeouts

A deadlock happens when two or more transactions each wait for a lock held by another, leaving none of them able to move forward. For example, one transaction can lock row A and request row B while a second transaction locks row B and requests row A. InnoDB detects deadlocks by default and rolls back one transaction as the victim. InnoDB tries to pick the transaction that changed fewer rows, counting rows it inserted, updated, or deleted. Deadlocks are a normal failure case for concurrent transactions and do not mean your data is corrupted. You can read more about how InnoDB detects deadlocks in the manual.

You can reduce deadlocks by keeping transactions short, accessing shared rows in a consistent order, and writing transaction code so it is safe to retry. Even with those habits, deadlocks can still happen. When InnoDB hits a deadlock, it rolls back the entire victim transaction. By default, when a statement hits a lock-wait timeout, InnoDB rolls back only the statement that timed out; enabling innodb-rollback-on-timeout changes that so the whole transaction rolls back. Your client code needs to handle both errors based on how you configured the server, as described in the InnoDB error-handling documentation.

To investigate a deadlock, run SHOW ENGINE INNODB STATUS to see the latest detected case. If deadlocks keep happening and you need more history, enable innodb_print_all_deadlocks to log every one. To inspect current row and table lock requests, query performance_schema.data_locks and performance_schema.data_lock_waits.

Table locks, intention locks, and metadata locks

Row locks are only one part of MySQL’s locking system. InnoDB also uses intention locks, which are table-level markers that tell MySQL a transaction intends to lock rows in that table. They allow row-level locks and table-level lock modes to coexist. For instance, FOR SHARE sets an intention shared lock, and FOR UPDATE sets an intention exclusive lock.

Explicit table locks work differently. LOCK TABLES can restrict concurrency, and the MySQL 8.4 manual advises against using it for InnoDB when ordinary row-level locking is enough. It also interacts with transactions in ways that make it a poor routine substitute for SELECT ... FOR UPDATE.

MySQL also uses metadata locks to protect database objects, such as table definitions, while queries and schema changes use them. An online ALTER TABLE can allow other transactions to change table data, yet it still waits for an exclusive metadata lock before finalizing the table definition. A long-running transaction can hold a metadata lock, and while an exclusive lock request waits for it, that waiting request can block later queries. To investigate metadata waits, query performance_schema.metadata_locks, or run SHOW FULL PROCESSLIST to see sessions waiting for a table metadata lock. The online DDL documentation explains the concurrency and waiting involved in more detail.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *