CS › Database

InnoDB row locks, next-key locks, and deadlock diagnosis

Comparing InnoDB record, gap, and next-key locks with PostgreSQL row locks, plus diagnosing and preventing deadlocks with InnoDB status and pg_locks.

InnoDB row locks, next-key locks, and deadlock diagnosis

Running SELECT ... FOR UPDATE on a row that didn’t exist blocked another session’s INSERT and triggered a deadlock. This post breaks down what InnoDB’s gap and next-key locks actually lock, how PostgreSQL differs, and how to diagnose deadlocks in both engines.

Tested with MySQL 8.0.34 InnoDB (REPEATABLE READ) and PostgreSQL 15.4 (READ COMMITTED).

Background

In a seat reservation toy project from a study group, I wrote an “insert if not reserved” flow like this: run SELECT ... FOR UPDATE to check whether a seat was already taken, and if no row came back, run INSERT. I added FOR UPDATE specifically to stop double bookings. Under a load test, two concurrent requests for the same empty seat hit the endpoint and one immediately failed with MySQL error 1213: Deadlock found when trying to get lock; try restarting transaction.

When I ran the exact same code against PostgreSQL, it didn’t deadlock—instead, it allowed a duplicate reservation. Both failures came from the same blind spot: I didn’t understand what range each engine actually locks.

How InnoDB and PostgreSQL row locks work

In InnoDB, row-level locks are actually locks placed on index records, not just standalone rows. Under REPEATABLE READ, InnoDB combines four lock types:

  • Record Lock: Locks a single existing index record.
  • Gap Lock: Locks the empty interval between index records to stop new rows from being inserted into that range. Gap locks are purely inhibitory—two transactions can hold gap locks on the same gap simultaneously without blocking each other.
  • Next-Key Lock: Combines a record lock with the gap lock right before it. This is InnoDB’s default locking unit for locking reads and range scans under REPEATABLE READ.
  • Insert Intention Lock: A special gap lock acquired right before an INSERT. It conflicts with any existing gap lock held by another transaction.

When you run an equality lookup on a unique index and the row exists, InnoDB acquires only a record lock. If the row doesn’t exist—or if you scan a range or a non-unique index—InnoDB locks the surrounding gap too. That exact behavior caused the seat reservation deadlock:

sequenceDiagram
    participant A as Transaction A
    participant DB as InnoDB
    participant B as Transaction B
    A->>DB: FOR UPDATE missing seat (acquires gap lock)
    B->>DB: FOR UPDATE same seat (acquires compatible gap lock)
    A->>DB: INSERT (waits for insert intention lock)
    B->>DB: INSERT (waits for insert intention lock)
    DB-->>B: Deadlock detected, rolls back B

Both transactions legally acquired a gap lock on the missing seat because gap locks don’t conflict with each other. Then both tried to INSERT into that gap, and each waited for the other to release its gap lock—an instant cycle.

PostgreSQL doesn’t have gap locks. It stores row locks directly in the tuple header’s xmax field and infomask bits. When no matching row exists, there is no tuple to lock, so both transactions see zero rows and proceed to INSERT duplicates. If you need range-level protection in PostgreSQL, you have to use a unique constraint, INSERT ... ON CONFLICT, or SERIALIZABLE isolation with Serializable Snapshot Isolation (predicate locks shown as SIReadLock in pg_locks). For the MVCC and snapshot mechanics behind these isolation levels, see Transaction isolation levels and MVCC in PostgreSQL and InnoDB.

Locking behavior comparison and anti-patterns

ScenarioInnoDB (RR)PostgreSQL (RC)Recommended approach
Lock existing row by PKRecord lockRow lockSafe as-is
Lock non-existent keyGap lock (blocks INSERT)Nothing lockedUnique constraint + duplicate key handling
Non-unique index range lockNext-key lockLocks matched rows onlyNarrow the range or consider RC
Unindexed WHERE columnLocks every scanned recordLocks matched rows onlyAdd an index on the filter column
Deadlock detectionImmediate (innodb_deadlock_detect)Checked after deadlock_timeout (default 1s)Consistent lock ordering + retry

When not to rely on gap locks: Implementing “check then insert” with SELECT ... FOR UPDATE is an anti-pattern on both engines—it triggers deadlocks in InnoDB and allows duplicates in PostgreSQL. Enforcing a unique constraint and handling the duplicate key error (or using INSERT ... ON CONFLICT / INSERT ... ON DUPLICATE KEY) is simpler and works consistently across databases. Likewise, switching MySQL to READ COMMITTED drops most search gap locks and boosts write concurrency, but any legacy logic that quietly depended on gap locks to prevent phantoms will break.

Diagnosing deadlocks and lock waits

In MySQL 8.0, I use three views and commands to inspect active locks and deadlocks:

1
2
3
4
5
6
7
8
9
10
11
12
13
-- 1. Inspect the most recent deadlock (LATEST DETECTED DEADLOCK section)
SHOW ENGINE INNODB STATUS\G

-- 2. List currently held and waiting locks (MySQL 8.0)
SELECT engine_transaction_id, object_name, index_name,
       lock_type, lock_mode, lock_status, lock_data
FROM performance_schema.data_locks;

-- 3. See which session is blocking which
SELECT * FROM sys.innodb_lock_waits\G

-- Log every deadlock to the MySQL error log
SET GLOBAL innodb_print_all_deadlocks = ON;

In performance_schema.data_locks, read lock_mode closely: X,GAP is a gap lock, plain X is a next-key lock, X,REC_NOT_GAP is a record lock, and INSERT_INTENTION marks an insert intention lock. When reading SHOW ENGINE INNODB STATUS, trace each transaction’s HOLDS THE LOCK(S) and WAITING FOR THIS LOCK TO BE GRANTED blocks down to the final WE ROLL BACK TRANSACTION (2) line to see the exact cycle.

In PostgreSQL, join pg_stat_activity with pg_locks and pg_blocking_pids() to expose blocking chains:

1
2
3
4
5
6
7
8
SELECT a.pid, pg_blocking_pids(a.pid) AS blocked_by,
       l.locktype, l.mode, l.granted, a.query
FROM pg_stat_activity a
JOIN pg_locks l ON l.pid = a.pid
WHERE NOT l.granted OR cardinality(pg_blocking_pids(a.pid)) > 0;

-- postgresql.conf: log waits that exceed deadlock_timeout (default 1s)
-- log_lock_waits = on

The primary defense against deadlocks is consistent lock ordering. Whenever a transaction updates multiple rows—such as transferring funds between two accounts—always lock them in ascending PK order with ORDER BY id ... FOR UPDATE. Because you can’t eliminate every possible deadlock under concurrency, also add a short bounded retry in application code for MySQL error 1213 and PostgreSQL SQLSTATE 40P01.

Production pitfalls and checklist

In InnoDB, running an UPDATE or DELETE with an unindexed WHERE condition forces a full scan of the clustered index and places a lock on every scanned record. That effectively locks the entire table, so a single batch UPDATE can stall all writes across the service. Because lock waits default to innodb_lock_wait_timeout = 50 seconds, the failure often looks like a hanging request rather than an immediate deadlock error.

Thinking in terms of “which index interval gets locked” instead of “which row gets locked” makes database concurrency predictable. Before shipping locking queries, I check these five items:

  • Is the locking read an equality lookup on a unique index, or a range/non-unique scan?
  • Can any “select then insert” flow be replaced with a unique constraint?
  • Do all code paths that lock multiple rows acquire them in the same PK order?
  • Are innodb_print_all_deadlocks (MySQL) or log_lock_waits (PostgreSQL) enabled?
  • Does the application retry cleanly on deadlock errors (1213 / 40P01)?
This post is licensed under CC BY 4.0 by the author.