Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
MySQL Tuning, Indexing & Concurrency 10+ Years (Principal / Architect) Expert Production Scenario

Explain InnoDB Locking Modes: Record Locks, Gap Locks, and Next-Key Locks, and how they prevent Phantom Reads.

Real-World Scenario / Incident Description

Under `REPEATABLE READ` isolation level, two concurrent transactions inserting users with IDs between 10 and 20 resulted in lock wait timeouts and deadlocks.

278 views • Updated 1 month ago

The Three InnoDB Row Lock Types

  1. Record Lock: Locks the physical index record itself (e.g. WHERE id = 5 FOR UPDATE).
  2. Gap Lock: Locks the gap between index records (or before the first / after the last) to prevent other transactions from inserting new rows in that gap.
  3. Next-Key Lock: A combination of a Record Lock on the index record plus a Gap Lock on the gap preceding it.

Why MySQL Uses Next-Key Locks by Default

Under the default REPEATABLE READ isolation level, MySQL uses Next-Key locking to solve the Phantom Read problem (preventing another transaction from inserting a new row that matches your query's range before you commit).

Reducing Lock Contention:

Switching transaction isolation to READ COMMITTED (with binlog_format=ROW) disables Gap Locks except for foreign key constraint checks and duplicate key checks.

Related Concepts: #InnoDB Locks #Gap Locks #Next-Key Locks #Phantom Reads #Transactions