SteelReed

Search

Search posts, questions…

4. Database & SQL

Locks in InnoDB: from the global lock to gap locks, read through data_locks

A money transfer that drives a balance negative, MySQL's lock types from global down to row level (intention, AUTO-INC, record, gap, next-key, insert intention), and performance_schema.data_locks for each kind of statement at REPEATABLE READ and READ COMMITTED, measured on MySQL 8.4.

18 Nov 20268 min readSenior

–

1. The problem

Account A holds 50. Two transfers of 30 and 40 run at once, both read 50, both pass: the balance becomes -20. The code sits in @Transactional under REPEATABLE READ, so everyone assumed it was safe.

2. Key idea

This is check-then-act: deciding on a stale number. Under RR a plain SELECT reads a snapshot (MVCC) and locks nothing.

Lock Name in data_locks Locks a gap? Meaning
Record lock X,REC_NOT_GAP no exactly one index record
Gap lock X,GAP yes the gap before a record, blocks inserts
Next-key lock X yes the record + the gap before it
Insert intention X,GAP,INSERT_INTENTION waits on gaps asks to insert, blocked by others' gap locks

Shared (FOR SHARE) can be held by many transactions; exclusive (FOR UPDATE, UPDATE, DELETE) by one. X only blocks locking reads; a plain SELECT still reads.

2.1 What does each statement lock?

Measured on MySQL 8.4, a 4-row table with keys 1, 2, 5, 9; owner_id is indexed, note isn't.

Statement REPEATABLE READ READ COMMITTED
WHERE id = 2 X,REC_NOT_GAP on 2 same as RR
WHERE id BETWEEN 2 AND 5 record on 2, next-key on 5 records on 2 and 5
WHERE owner_id = 20 (secondary) next-keys on the secondary + a gap up to the next row, records on the PK records only
WHERE note = 'c' (unindexed) X on all 4 rows + supremum only the matching row
WHERE id = 4 FOR UPDATE (missing) X,GAP on 5 no lock
Approach Use when Don't use when
Condition inside UPDATE the rule fits in a WHERE you need other data to decide
FOR UPDATE reading to decide a write read-only display
Optimistic (version) low contention hot rows: endless retries

3. In SQL

Fix the transfer and verify the locks.

SQL
-- Fold the check into the write: one atomic statement, one record lock
UPDATE account SET amount = amount - 30 WHERE id = 'A' AND amount >= 30;
-- affected rows = 0: insufficient funds
 
-- Or lock on read
START TRANSACTION;
SELECT amount FROM account WHERE id = 'A' FOR UPDATE;   -- the other request waits here
UPDATE account SET amount = amount - 30 WHERE id = 'A';
COMMIT;
 
-- See exactly what a statement locks (from another session while the transaction is open)
SELECT index_name, lock_type, lock_mode, lock_status, lock_data
FROM performance_schema.data_locks WHERE object_name = 'account';
-- PRIMARY | RECORD | X,REC_NOT_GAP | GRANTED | 'A'

PostgreSQL has no gap locks: it prevents phantoms with SERIALIZABLE (SSI) or unique constraints.

Hot rows, intention locks and outdated diagrams
  • Hold a hot row's lock for 5 ms and that row serves at most ~200 transactions/second; more servers don't help. Watch Innodb_row_lock_waits, Innodb_row_lock_time_avg and sys.innodb_lock_waits.
  • Intention locks (IS, IX) are set on the table automatically, like an "occupied" sign at the building door: LOCK TABLES ... WRITE reads the sign instead of knocking on every room. Every data_locks result includes a TABLE ... IX row.
  • Many docs draw BETWEEN 2 AND 5 under RR as also taking a next-key on the next record (9). That's older MySQL behaviour; 8.4 doesn't lock 9. Test on your version instead of trusting diagrams.
  • RR locks the scanned range: the less selective the index, the wider the range. RC releases non-matching rows immediately.

4. Working with AI

Hand to AI: a script that opens a transaction, runs a statement, prints data_locks and rolls back, for each hot query; run it in CI when queries change.

Check in AI-written code:

  • No "SELECT, then if, then UPDATE" without locking; the condition is in the UPDATE or there's a FOR UPDATE.
  • No FOR SHARE for read-then-write on the same row.
  • Columns in the WHERE of hot UPDATEs and DELETEs are indexed.
  • affected rows is checked, not ignored.
  • Transactions are short: no HTTP calls while holding locks.

5. Exercises

Exercise 1: Review "locked to be safe"

The AI wrote this, saying "it's locked, so it can't go negative". Find the bug, name a test that proves it, fix it.

SQL
START TRANSACTION;
SELECT amount FROM account WHERE id = 'A' FOR SHARE;
-- app: if (amount >= 30)
UPDATE account SET amount = amount - 30 WHERE id = 'A';
COMMIT;
Solution to Exercise 1

Both requests take S on A (S is compatible with S), both see enough funds, then both request X for the UPDATE: each waits for the other to release S. InnoDB detects a deadlock and rolls one back (error 1213).

Test: two threads via CountDownLatch on real MySQL (Testcontainers), counting 1213 errors: usually 1 per pair.

Fix: drop the SELECT, use UPDATE ... WHERE id = 'A' AND amount >= 30 and check affected rows; or switch to FOR UPDATE.

Exercise 2: Read a lock-wait incident

After deploying a "freeze suspicious accounts" job that runs UPDATE account SET status = 'FROZEN' WHERE note LIKE '%fraud%' under RR, the transfer API returns Lock wait timeout exceeded en masse during the job's 40 seconds. note has no index. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.

Solution to Exercise 2
  • Diagnosis: with no index the UPDATE scans the whole table, and under RR it holds next-key locks on every scanned row until commit: the whole table is locked for 40 seconds.
  • 15 minutes: stop the job; waiting transfers will succeed on retry.
  • Root fix: find the ids first with a plain SELECT (no locks), then UPDATE ... WHERE id IN (...) in small batches, one short transaction each; or run the job under READ COMMITTED. Verify with data_locks before deploying.

Summary

  • Check-then-act inside an RR transaction is still wrong; fold the condition into the UPDATE.
  • Reading to write: FOR UPDATE, not FOR SHARE.
  • Primary key equality: one record lock.
  • RR locks the scanned range; an unindexed column locks the whole table.
  • Predict, then verify with data_locks on the exact version.

Read more: Part 4: Optimistic, pessimistic and the booking lab.

Practice interview questions on this topic

All Transactions & Locking questions →

Loading comments…