Transactions, Isolation & Locking
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A transaction groups statements so that they succeed or fail together. This page covers how InnoDB does that in
MySQL: how a transaction starts and ends, what each isolation level lets a session see, how locks are taken and
how to observe them, and what to do about deadlocks and waits. The demos use two mysql sessions run
at the same time against the shop database; "session A" and "session B" are two separate connections. The
standard statements and the theory of isolation levels are on
Transaction Control; this page is about InnoDB’s behaviour. All results were
produced on MySQL 26.10.0.
Transactions and autocommit
InnoDB is ACID:
-
Atomicity — all changes or none, using undo to roll back.
-
Consistency — constraints and foreign keys hold at commit.
-
Isolation — concurrent transactions do not see each other’s partial work, as governed by the isolation level.
-
Durability — once committed, a transaction survives a crash, because its redo (and binlog) records are flushed (see Architecture).
By default autocommit = 1: every statement is its own transaction and commits as soon as it finishes. A
multi-statement transaction starts with START TRANSACTION (or BEGIN) and ends with COMMIT or ROLLBACK;
SET autocommit = 0 instead makes the session open a transaction implicitly with the first statement and keep it
open until the next COMMIT or ROLLBACK. Variants worth knowing are START TRANSACTION READ ONLY (lets InnoDB skip
some bookkeeping) and START TRANSACTION WITH CONSISTENT SNAPSHOT (takes the read view immediately instead of at
the first read).
The server defaults on the test server:
SELECT @@transaction_isolation, @@autocommit, @@innodb_lock_wait_timeout, @@innodb_deadlock_detect;
+-------------------------+--------------+----------------------------+--------------------------+
| @@transaction_isolation | @@autocommit | @@innodb_lock_wait_timeout | @@innodb_deadlock_detect |
+-------------------------+--------------+----------------------------+--------------------------+
| REPEATABLE-READ | 1 | 50 | 1 |
+-------------------------+--------------+----------------------------+--------------------------+
An open transaction holds its locks and pins its read view until it ends, so keep transactions short and never wait for a user while one is open.
Isolation levels in InnoDB
MySQL supports the four standard levels, set per session or for the next transaction
(SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED), per server with transaction_isolation, and visible in
information_schema.innodb_trx. InnoDB’s behaviour differs from the textbook table in a few places:
| Level | Plain SELECT |
Locking reads, UPDATE, DELETE |
|---|---|---|
|
Reads the newest version of rows, even uncommitted ones (dirty reads) |
Same as |
|
A new snapshot for every statement; no dirty reads, but a re-read can change |
Record locks only; no gap locks (except for foreign keys and duplicate checks) |
|
One snapshot, taken at the first read, used for the whole transaction |
Next-key locks (record plus gap) when scanning a range; a unique-index lookup of an existing row locks only that record |
|
Like |
Next-key locks |
Consistent reads and the snapshot
An ordinary SELECT in InnoDB is a consistent non-locking read: it reads from a snapshot defined by the read
view (see Architecture for undo and MVCC) and takes no row locks, so it
neither blocks nor is blocked by writers. Session A opens a transaction and reads a product’s stock; session B
then changes it and commits; A reads again and then does a SELECT ... FOR UPDATE on the same row:
-- session A -- session B
START TRANSACTION;
SELECT stock FROM products WHERE sku = 'A-1'; -- 12
UPDATE products SET stock = stock - 5 WHERE sku = 'A-1';
SELECT stock FROM products WHERE sku = 'A-1'; -- 7
SELECT stock FROM products WHERE sku = 'A-1'; -- ?
SELECT stock FROM products WHERE sku = 'A-1' FOR UPDATE;
SELECT trx_id, trx_state, trx_isolation_level FROM information_schema.innodb_trx;
COMMIT;
SELECT stock FROM products WHERE sku = 'A-1';
-- session A
+-------+
| stock |
+-------+
| 12 | <- first read
+-------+
+-------+
| stock |
+-------+
| 12 | <- second read, after B committed: still 12, from the snapshot
+-------+
+-------+
| stock |
+-------+
| 7 | <- FOR UPDATE reads the latest committed version
+-------+
+--------+-----------+---------------------+
| trx_id | trx_state | trx_isolation_level |
+--------+-----------+---------------------+
| 2989 | RUNNING | REPEATABLE READ |
+--------+-----------+---------------------+
+-------+
| stock |
+-------+
| 7 | <- after COMMIT, a new snapshot
+-------+
-- session B: the UPDATE returned immediately ("1 row affected") and its SELECT showed 7
(The arrows were added. Session B’s UPDATE was not blocked by A’s open read.) The rule to remember: a plain
SELECT sees the snapshot; a locking read, UPDATE and DELETE always see the latest committed data. Mixing the two
in one transaction can show seemingly contradictory results.
A phantom is a row that appears in a repeated range read. Under REPEATABLE READ a plain SELECT does not show
one, but writes can still reveal it:
-- session A (REPEATABLE READ) -- session B (autocommit)
START TRANSACTION;
SELECT COUNT(*), SUM(stock) FROM products; -- 5 rows, 297
INSERT INTO products VALUES ('Z-1','Phantom','misc',1.00,1,'[]','{}');
SELECT COUNT(*), SUM(stock) FROM products; -- still 5, 297
SELECT COUNT(*) FROM products FOR SHARE; -- 6: the locking read sees the new row
UPDATE products SET stock = stock + 1 WHERE sku = 'Z-1'; -- A can modify the row it "cannot see"
SELECT COUNT(*) FROM products; -- 6: A's own change made the row part of its snapshot
COMMIT;
+--------------+---+-------+
| step | n | stock |
+--------------+---+-------+
| A first read | 5 | 297 |
+--------------+---+-------+
+---------------+---+-------+
| step | n | stock |
+---------------+---+-------+
| A second read | 5 | 297 |
+---------------+---+-------+
+----------------+---+
| step | n |
+----------------+---+
| A locking read | 6 |
+----------------+---+
+------------------------------+---+
| step | n |
+------------------------------+---+
| A after touching the phantom | 6 |
+------------------------------+---+
(The queries in the real run each added a step label column; they are listed here without it.) The UPDATE of a row
that is invisible to the snapshot succeeds because writes operate on the latest data, and once A has changed the
row it sees it. This is the one place where InnoDB’s REPEATABLE READ is not a true snapshot.
Under READ COMMITTED each statement gets its own snapshot, so the same two reads can differ (session B committed an
update between them):
+--------------+-------+
| step | stock |
+--------------+-------+
| A first read | 150 |
+--------------+-------+
+---------------+-------+
| step | stock |
+---------------+-------+
| A second read | 140 |
+---------------+-------+
That is a non-repeatable read. READ COMMITTED is a legitimate choice for OLTP applications that want fewer
locks and less lock contention; it requires row-based binary logging (the default here) for safe replication.
READ UNCOMMITTED shows data that has not committed. Session B set a product’s stock to 0 inside a transaction and
rolled it back three seconds later; session A, at READ UNCOMMITTED, read in between and after:
+--------------+-------+
| step | stock |
+--------------+-------+
| A dirty read | 0 |
+--------------+-------+
+-----------------------+-------+
| step | stock |
+-----------------------+-------+
| A after B rolled back | 80 |
+-----------------------+-------+
A dirty read of a value that never existed. Do not use this level.
Locking reads
To read rows and lock them, so that nobody changes them until you finish, use a locking read inside a transaction:
-
SELECT ... FOR UPDATEtakes an exclusive (X) lock on every row it returns, as if updating them. -
SELECT ... FOR SHARE(older nameLOCK IN SHARE MODE) takes a shared (S) lock: other sessions may read-lock too but not modify. -
NOWAITmakes the statement fail immediately instead of waiting;SKIP LOCKEDskips rows that are locked, which turns a table into a work queue. -
OF tablelimits the locking to some tables of a join.
Session A locks the A-1 row; session B (with innodb_lock_wait_timeout = 2) tries three variants:
-- session A
START TRANSACTION;
SELECT sku, stock FROM products WHERE sku = 'A-1' FOR UPDATE;
-- ... holds the lock for 4 seconds, then COMMIT
-- session B
SET SESSION innodb_lock_wait_timeout = 2;
SELECT sku FROM products WHERE sku = 'A-1' FOR UPDATE NOWAIT;
SELECT sku FROM products WHERE sku IN ('A-1','A-2') FOR UPDATE SKIP LOCKED;
SELECT sku FROM products WHERE sku = 'A-1' FOR UPDATE;
-- session B
ERROR 3572 (HY000): Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set.
+-----+
| sku |
+-----+
| A-2 |
+-----+
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
-
NOWAITfailed at once with error 3572. -
SKIP LOCKEDreturned onlyA-2; the lockedA-1was silently skipped. Use it for queues (... WHERE status = 'open' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED), where several workers each want a different row. The result is not consistent by design, so do not use it for reports. -
The plain
FOR UPDATEwaited two seconds, the session’s timeout, and failed with error 1205.
Lock wait timeout. A statement waits for a lock for innodb_lock_wait_timeout seconds (50 by default) and then fails
with error 1205. By default only the statement is rolled back (innodb_rollback_on_timeout = 0); the transaction
stays open with its other locks, and the application must decide to retry the statement or roll back. A long wait
usually means a forgotten open transaction somewhere; find it with information_schema.innodb_trx and
sys.innodb_lock_waits.
What gets locked depends on the index. A locking read locks the index records it scans, not just the rows it
returns. status has no index in the shop schema, so a locking read on it scans the clustered index and locks every
row and the gap after the last one:
START TRANSACTION;
SELECT id, status FROM orders WHERE status = 'open' FOR UPDATE;
SELECT index_name, lock_type, lock_mode, lock_data FROM performance_schema.data_locks
WHERE object_schema = 'shop' ORDER BY lock_type DESC, index_name, lock_data;
ROLLBACK;
+------------+-----------+-----------+------------------------+
| index_name | lock_type | lock_mode | lock_data |
+------------+-----------+-----------+------------------------+
| NULL | TABLE | IX | NULL |
| PRIMARY | RECORD | X | 1001 |
| PRIMARY | RECORD | X | 1002 |
| PRIMARY | RECORD | X | 1003 |
| PRIMARY | RECORD | X | 1004 |
| PRIMARY | RECORD | X | 1005 |
| PRIMARY | RECORD | X | 1006 |
| PRIMARY | RECORD | X | 1007 |
| PRIMARY | RECORD | X | 1008 |
| PRIMARY | RECORD | X | supremum pseudo-record |
+------------+-----------+-----------+------------------------+
The query returned three rows (1002, 1006, 1008) but locked all eight plus the supremum, so any other write to
orders would wait. Index the columns you lock by, or lock by primary key. This is the most common cause of
unexpected lock contention in MySQL applications.
Record, gap and next-key locks
InnoDB locks index records, in three forms:
-
A record lock locks one index entry.
-
A gap lock locks the space between index entries (or before the first / after the last), preventing inserts into the gap but not touching existing rows.
-
A next-key lock is a record lock plus a gap lock on the gap before the record. It is the default for range scans under
REPEATABLE READ.
Next-key locking is how REPEATABLE READ stops phantoms for locking reads: the range is locked, so no one can insert
into it. The last gap, above the highest key, is locked through a pseudo-record named supremum.
Seeing locks
performance_schema.data_locks lists every lock currently held or requested, and data_lock_waits pairs each
waiting request with the lock that blocks it. A transaction locks a range of orders:
START TRANSACTION;
SELECT id FROM orders WHERE id BETWEEN 1002 AND 1004 FOR UPDATE;
SELECT object_name, index_name, lock_type, lock_mode, lock_status, lock_data
FROM performance_schema.data_locks WHERE object_schema = 'shop' ORDER BY lock_type DESC, lock_data;
COMMIT;
+-------------+------------+-----------+---------------+-------------+-----------+
| object_name | index_name | lock_type | lock_mode | lock_status | lock_data |
+-------------+------------+-----------+---------------+-------------+-----------+
| orders | NULL | TABLE | IX | GRANTED | NULL |
| orders | PRIMARY | RECORD | X,REC_NOT_GAP | GRANTED | 1002 |
| orders | PRIMARY | RECORD | X | GRANTED | 1003 |
| orders | PRIMARY | RECORD | X | GRANTED | 1004 |
+-------------+------------+-----------+---------------+-------------+-----------+
Read the lock_mode: IX is an intention lock on the table (announcing row-level X locks below), X,REC_NOT_GAP
is a plain record lock, and a bare X is a next-key lock (record plus the gap before it). The range start 1002 is
locked as a record only because the scan began with an exact match on a unique index.
A lookup of a key that does not exist locks the gap it would occupy. Order 1010 is above the highest id, so the gap is the one before the supremum. A second session inserting into that gap is blocked:
-- session A (REPEATABLE READ)
START TRANSACTION;
SELECT id FROM orders WHERE id = 1010 FOR UPDATE; -- no such row
SELECT index_name, lock_type, lock_mode, lock_data FROM performance_schema.data_locks WHERE object_schema = 'shop';
-- session B
INSERT INTO orders VALUES (1012, 'c-1', 'open', NOW()); -- waits
-- session A, while B is waiting
SELECT requesting_engine_transaction_id AS waiting, blocking_engine_transaction_id AS blocking
FROM performance_schema.data_lock_waits;
ROLLBACK;
+------------+-----------+-----------+------------------------+
| index_name | lock_type | lock_mode | lock_data |
+------------+-----------+-----------+------------------------+
| NULL | TABLE | IX | NULL |
| PRIMARY | RECORD | X | supremum pseudo-record |
+------------+-----------+-----------+------------------------+
+---------+----------+
| waiting | blocking |
+---------+----------+
| 4057 | 4056 |
+---------+----------+
+-----------------+
| seconds_blocked |
+-----------------+
| 2.3 |
+-----------------+
Session A holds a next-key lock on the supremum (no row, but the gap above 1008 is locked), session B’s transaction (4057) waits for A’s (4056), and B’s insert, which would have been to id 1012, returned only after A rolled back, 2.3 seconds later. Gap locks only block inserts; they do not conflict with each other.
Gap locks are what REPEATABLE READ pays for phantom protection. At READ COMMITTED the same lookup takes no
record or gap lock at all; only the table intention lock remains:
-- READ COMMITTED: SELECT id FROM orders WHERE id = 1010 FOR UPDATE
+------------+-----------+-----------+-----------+
| index_name | lock_type | lock_mode | lock_data |
+------------+-----------+-----------+-----------+
| NULL | TABLE | IX | NULL |
+------------+-----------+-----------+-----------+
At SERIALIZABLE, a plain SELECT takes shared next-key locks (with autocommit off):
-- SERIALIZABLE: SELECT id FROM orders WHERE id BETWEEN 1002 AND 1004
+------------+-----------+---------------+-----------+
| index_name | lock_type | lock_mode | lock_data |
+------------+-----------+---------------+-----------+
| NULL | TABLE | IS | NULL |
| PRIMARY | RECORD | S,REC_NOT_GAP | 1002 |
| PRIMARY | RECORD | S | 1003 |
| PRIMARY | RECORD | S | 1004 |
+------------+-----------+---------------+-----------+
Because gap locks are the main source of surprising blocking and deadlocks in InnoDB, many high-concurrency systems
run at READ COMMITTED.
Deadlocks
A deadlock is a cycle of transactions each waiting for a lock another holds. InnoDB detects them immediately
(innodb_deadlock_detect = ON) and rolls back one transaction, the "victim", with error 1213.
Two sessions update the same two products in opposite order:
-- session A -- session B
START TRANSACTION;
UPDATE products SET stock = stock - 1 WHERE sku = 'A-1';
START TRANSACTION;
UPDATE products SET stock = stock - 1 WHERE sku = 'A-2';
UPDATE products SET stock = stock - 1 WHERE sku = 'A-2'; -- waits
UPDATE products SET stock = stock - 1 WHERE sku = 'A-1'; -- cycle
-- session B
ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
-- session A: "A finished", COMMIT succeeded
After the deadlock A-1 and A-2 held 11 and 29: only A’s updates survived, B was rolled back completely. The details
of the latest deadlock are in the LATEST DETECTED DEADLOCK section of SHOW ENGINE INNODB STATUS:
SHOW ENGINE INNODB STATUS;
------------------------
LATEST DETECTED DEADLOCK
------------------------
*** (1) TRANSACTION:
TRANSACTION 3040, ACTIVE 3 sec starting index read
LOCK WAIT 3 lock struct(s), heap size 1128, 2 row lock(s), undo log entries 1
UPDATE products SET stock = stock - 1 WHERE sku = 'A-2'
*** (1) HOLDS THE LOCK(S):
RECORD LOCKS ... index PRIMARY of table `shop`.`products` trx id 3040 lock_mode X locks rec but not gap
Record lock ... 0: len 3; hex 412d31; asc A-1;;
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS ... index PRIMARY of table `shop`.`products` trx id 3040 lock_mode X locks rec but not gap waiting
Record lock ... 0: len 3; hex 412d32; asc A-2;;
*** (2) TRANSACTION:
TRANSACTION 3041, ACTIVE 2 sec starting index read
UPDATE products SET stock = stock - 1 WHERE sku = 'A-1'
*** (2) HOLDS THE LOCK(S): ... A-2 ...
*** (2) WAITING FOR THIS LOCK TO BE GRANTED: ... A-1 ...
*** WE ROLL BACK TRANSACTION (2)
(The hexadecimal row dumps are abbreviated, and the display is condensed to the lines that matter.) It shows both
statements, the lock each held and the one each waits for, and the victim, here transaction 3041. The server picks
the transaction that has modified the fewest rows. innodb_print_all_deadlocks = ON writes every deadlock to
the error log rather than only the latest one in the status output; the counter lock_deadlocks in
information_schema.innodb_metrics counts them.
Handling deadlocks. They are a normal event in a busy system and are not bugs in the database:
-
The application must catch error 1213 and retry the whole transaction.
-
Access rows in a consistent order in every transaction (here, always by ascending
sku) so cycles cannot form. -
Keep transactions short, index the columns you update or lock by, and lock exactly what you need.
-
Consider
READ COMMITTEDto remove gap-lock conflicts.
Metadata locks
Besides row locks, MySQL protects table definitions with metadata locks (MDL): every statement that uses a
table takes an MDL for the duration of its transaction, so a schema change cannot run underneath it. A long-open
transaction that has merely read a table therefore blocks a later ALTER TABLE on it, and that waiting ALTER
in turn blocks every new statement on the table behind it. Session A reads customers in a transaction and keeps it
open; session B runs ALTER TABLE customers ADD COLUMN phone ...:
-- session A
START TRANSACTION;
SELECT COUNT(*) FROM customers; -- transaction stays open
SELECT object_type, object_schema, object_name, lock_type, lock_duration, lock_status, owner_thread_id
FROM performance_schema.metadata_locks WHERE object_schema = 'shop' AND object_name = 'customers';
-- session B
ALTER TABLE customers ADD COLUMN phone varchar(20) NULL;
+-------------+---------------+-------------+-------------------+---------------+-------------+-----------------+
| object_type | object_schema | object_name | lock_type | lock_duration | lock_status | owner_thread_id |
+-------------+---------------+-------------+-------------------+---------------+-------------+-----------------+
| TABLE | shop | customers | SHARED_READ | TRANSACTION | GRANTED | 216 |
| TABLE | shop | customers | SHARED_UPGRADABLE | TRANSACTION | GRANTED | 217 |
| TABLE | shop | customers | EXCLUSIVE | TRANSACTION | PENDING | 217 |
+-------------+---------------+-------------+-------------------+---------------+-------------+-----------------+
A’s SHARED_READ is granted; B’s ALTER holds a SHARED_UPGRADABLE lock and its EXCLUSIVE request is PENDING
until A ends. B’s session showed the state Waiting for table metadata lock, and it finished only after A committed.
The effect in production can be dramatic (queries pile up behind an innocent ALTER). Defences: avoid long
transactions, run DDL at quiet times, set lock_wait_timeout (31,536,000 seconds, a year, by default) to a short
value in migration sessions so the ALTER gives up instead of queueing, and use online DDL with
ALGORITHM=INPLACE, LOCK=NONE where possible. Schema-change practice is covered in
Evolving the Database Model.
Savepoints
A savepoint names a point inside a transaction to which you can roll back partially:
START TRANSACTION;
INSERT INTO customers VALUES ('c-5','Edsger Dijkstra','edsger@example.com','Austin','pro', NOW());
SAVEPOINT after_customer;
INSERT INTO orders VALUES (1009,'c-5','open',NOW());
SELECT COUNT(*) AS orders_before_rollback FROM orders;
ROLLBACK TO SAVEPOINT after_customer;
SELECT COUNT(*) AS orders_after_rollback FROM orders;
SELECT COUNT(*) AS customers_still_there FROM customers WHERE id = 'c-5';
RELEASE SAVEPOINT after_customer;
ROLLBACK;
SELECT COUNT(*) AS customers_after_rollback FROM customers WHERE id = 'c-5';
orders_before_rollback: 9
orders_after_rollback: 8
customers_still_there: 1
customers_after_rollback: 0
(The four single-value results are listed as name: value.) ROLLBACK TO SAVEPOINT undid only the order and left the
customer inside the still-open transaction; the final ROLLBACK removed everything. Row locks acquired after the savepoint are not necessarily released by ROLLBACK TO SAVEPOINT, so do not use it to
shorten lock times. Savepoints are how a framework implements nested transactions; see
Hibernate Transactions for the application side.
Statements that commit implicitly
A transaction ends implicitly when you run certain statements, most importantly DDL: CREATE, ALTER, DROP and
TRUNCATE on tables, schemas and indexes, plus statements such as LOCK TABLES and START TRANSACTION itself.
MySQL’s DDL is not transactional, so it cannot be rolled back and it commits first whatever came before it:
START TRANSACTION;
UPDATE products SET stock = stock - 1 WHERE sku = 'C-3';
CREATE TABLE tmp_probe (x int); -- implicit COMMIT happens here
ROLLBACK; -- nothing left to roll back
SELECT stock AS stock_after_rollback FROM products WHERE sku = 'C-3';
+----------------------+
| stock_after_rollback |
+----------------------+
| 79 |
+----------------------+
The stock was 80 before the transaction; the UPDATE was committed by the CREATE TABLE and the ROLLBACK was a
no-op. (CREATE TEMPORARY TABLE and DROP TEMPORARY TABLE do not cause an implicit commit.) Never mix DDL into a
transaction you expect to be able to undo, and keep schema changes out of data migrations that need atomicity.
Finally, autocommit = 0 changes what a missing COMMIT means:
SET autocommit = 0;
UPDATE products SET stock = stock + 100 WHERE sku = 'C-3';
ROLLBACK;
SELECT stock FROM products WHERE sku = 'C-3';
SET autocommit = 1;
+-------+
| stock |
+-------+
| 79 |
+-------+
With autocommit off the update stayed in an open transaction until it was rolled back; a client that disconnects without committing loses it.
Diagnosing contention
A short checklist when sessions wait or fail:
-
SELECT * FROM sys.innodb_lock_waits— who is waiting for whom, with the blocking query and a ready-madeKILLstatement. -
SELECT * FROM information_schema.innodb_trx— open transactions, how long they have been running and how many rows they locked; look for old ones. -
SELECT * FROM performance_schema.data_locksanddata_lock_waits— the locks themselves. -
SHOW ENGINE INNODB STATUS— the latest deadlock, and theHistory list lengththat reveals a long-running transaction pinning undo. -
SHOW GLOBAL STATUS LIKE 'Innodb_row_lock%'— cumulative waits, total and maximum wait time.
Related
-
Transaction Control — the standard SQL statements and isolation levels.
-
Architecture — undo logs, read views and the redo log.
-
Hibernate Locking — optimistic and pessimistic locking from JPA, mapped to the
FOR UPDATEforms above. -
Multi-document ACID Transactions — the MongoDB counterpart.