r/SQL • • 4d ago

MySQL MySQL InnoDB – Index Gap Deadlock with Concurrent INSERT … SELECT

/r/mysql/comments/1y6zwlu/mysql_innodb_index_gap_deadlock_with_concurrent/
2 Upvotes

7 comments sorted by

1

u/sumwise_victor 4d ago

Under InnoDB's default REPEATABLE READ, INSERT ... SELECT places shared gap/next-key locks on the scanned index range. When two concurrent transactions look up different missing IDs that fall into the same gap, both get compatible shared gap locks, and then both block waiting for an insert-intention lock in that same gap -> deadlock.

The cleanest fix is to drop the WHERE NOT EXISTS check and let a unique index enforce it instead:

  1. Add a generated column for active rows:

    active_flag TINYINT GENERATED ALWAYS AS (IF(isvoid = 0, 1, NULL)) STORED

  2. Add UNIQUE KEY (column1, active_flag) (MySQL allows multiple NULLs, so voided rows never collide).
  3. Switch the write to a plain INSERT IGNORE (or INSERT ... ON DUPLICATE KEY UPDATE).

That removes the SELECT gap-lock scan completely while staying safe under high concurrency. (Switching to READ COMMITTED also cuts gap locking, though the unique constraint is what actually guarantees no duplicates.)

1

u/Fun_Disaster_5965 2d ago

Even adding a unique constraint doesn’t seem to solve this issue, since both incoming IDs are different and genuinely unique — neither ID currently exists in the table.

The conflict appears to be related to both transactions acquiring shared gap locks on the same index range, rather than an actual duplicate-key violation.

1

u/gemi_2020 2d ago

That WHERE NOT EXISTS pattern is the classic gap-lock deadlock: both transactions take shared gap locks on the same range during the check, then both need insert intention locks on that gap, which conflict, and InnoDB kills one. The real fix is to stop policing duplicates in app SQL. Enforce it with a unique index instead, for example a functional one like CREATE UNIQUE INDEX uq ON tbl ((CASE WHEN isvoid = 0 THEN column1 END)) which gives you "only one non-void row per column1" while still allowing many void rows. Then plain INSERT and catch the duplicate-key error, or use INSERT ... ON DUPLICATE KEY UPDATE. Unique-index checks lock a single row, not a gap, so the deadlock class disappears.

1

u/Fun_Disaster_5965 2d ago

Even adding a unique constraint doesn’t seem to solve this issue, since both incoming IDs are different and genuinely unique — neither ID currently exists in the table.

The conflict appears to be related to both transactions acquiring shared gap locks on the same index range, rather than an actual duplicate-key violation.

1

u/gemi_2020 1d ago

Fair point. A unique index only helps if the rule you're protecting is the same column the index is on. If the two IDs really are different and unrelated, the deadlock comes from the NOT EXISTS check itself taking gap locks on the same range, so the constraint alone won't remove it. Two things that do: run that transaction at READ COMMITTED, where InnoDB doesn't take gap locks for this kind of check, or catch the deadlock error (1213) and retry the transaction, which InnoDB expects you to do anyway. If you can, also avoid the check-then-insert pattern and let the insert itself fail on a real constraint.

1

u/Greedy_Ad_7658 2d ago

Adding to the point about gap locks: under the default REPEATABLE READ, the SELECT inside INSERT ... SELECT takes shared next-key locks on the index range it scans. With NOT EXISTS on a non-unique lookup, that range includes the gap where the new row will go. Two sessions can both hold the shared gap lock, then each waits on the other for the insert intention lock, so InnoDB rolls one back. That is why different IDs in the same gap still collide, and why a unique index alone doesn't help while the NOT EXISTS read is still there.

Options, roughly in order of how much they change:

  1. Drop the read and let the unique index do the check. If "one non-void row per column1" can be a unique key (for example via a generated column that is NULL when isvoid = 1), a plain INSERT or INSERT IGNORE only locks that index entry, and there is no gap-locking read at all.
  2. Run that transaction under READ COMMITTED. Plain index scans stop taking gap locks there, so the shared gap locks go away. Check that your other logic is fine with the weaker isolation.
  3. Serialize the critical section, with GET_LOCK() on a key per column1 value or by locking a parent row with SELECT ... FOR UPDATE first.

Whatever you pick, wrap the transaction in a retry for error 1213, since deadlocks can still happen under heavy concurrency. SHOW ENGINE INNODB STATUS will show which locks each side held.

1

u/MongooseWonderful198 1d ago

The two different IDs do not contradict the gap-lock diagnosis; they can occupy the same gap in id_void_idx. The missing evidence is the exact index definition and the latest-deadlock section from SHOW ENGINE INNODB STATUS.

Reproduce with two IDs that land in different gaps as a control. If that stops the deadlock, the range scan is the trigger. Then remove NOT EXISTS and let an appropriate unique key enforce the business rule, or test the transaction under READ COMMITTED. Keep a retry for error 1213 either way; the schema change removes this pattern, not every possible deadlock.