Quick revision
The short answer
Under REPEATABLE READ, a locking read of a key that does not exist, such as SELECT ... FOR UPDATE to check whether a row is there, takes a gap lock on the empty space where that key would go. Gap locks do not conflict with each other, so two sessions can both hold one on the same gap; then each tries to INSERT into it, needs an insert intention lock, and waits for the other's gap lock, which is a deadlock. Duplicate-key checks on unique indexes take shared next-key locks with the same effect. We fix it by replacing check-then-insert with INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE, using READ COMMITTED, keeping transactions short and retrying.
What to remember
In this answer, we saw that under REPEATABLE READ a locking read of a missing key takes a gap lock, gap locks are compatible with each other, and an INSERT's insert intention lock conflicts with another transaction's gap lock. Two sessions that check for absence with FOR UPDATE and then insert into the same gap deadlock, and duplicate-key checks on unique indexes can do the same through shared next-key locks. innodb_print_all_deadlocks shows the pattern, and the fixes are INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE instead of check-then-insert, READ COMMITTED where acceptable, short transactions, and retry.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Under REPEATABLE READ, a locking read of a key that does not exist, such as SELECT ... FOR UPDATE to check whether a row is there, takes a gap lock on the empty space where that key would go. Gap locks do not conflict with each other, so two sessions can both hold one on the same gap; then each tries to INSERT into it, needs an insert intention lock, and waits for the other's gap lock, which is a deadlock. Duplicate-key checks on unique indexes take shared next-key locks with the same effect. We fix it by replacing check-then-insert with INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE, using READ COMMITTED, keeping transactions short and retrying.
Why this question is asked
Deadlocks between two INSERTs of different rows seem impossible at first: nobody is touching the same row. The message in SHOW ENGINE INNODB STATUS is the clue, and reading it requires knowing InnoDB's gap and insert intention locks. Interviewers ask this because it is one of the most common real MySQL deadlocks and its fix is a change in how the application writes data. In this answer, we will recap gap and insert intention locks, reproduce the check-then-insert deadlock, look at the unique-index variant, read the deadlock report, and go through the options.
1A Quick Recap of Gap and Insert Intention Locks
InnoDB locks index records. Under REPEATABLE READ, the default, a locking read also locks the gap, the empty space between two index entries, so that no other transaction can insert a row into the range it read. That is how phantoms are prevented. A gap lock is purely inhibitive: it exists only to stop inserts, so two transactions may hold gap locks on the same gap at the same time without conflict.
An INSERT first asks for an insert intention lock, a special gap lock that says I am about to insert at this position. Insert intention locks do not conflict with each other, so two inserts at different positions in the same gap proceed in parallel. But an insert intention lock does conflict with a gap or next-key lock held by another transaction. The status line lock_mode X locks gap before rec insert intention waiting means exactly this: our insert wants to enter a gap that someone else has locked.
| Held by other \ Requested | Gap lock | Insert intention |
|---|---|---|
| Gap lock | compatible | waits |
| Next-key lock | compatible on the gap | waits |
| Insert intention | compatible | compatible |
2Reproducing the Check-Then-Insert Deadlock
A common pattern checks whether a row exists, inside a transaction with FOR UPDATE to be safe, and inserts it if not. Suppose usernames have a unique index, the table holds 'adam' and 'zoe', and two sessions register 'kim' and 'lee' at the same moment. Both names fall in the gap between 'adam' and 'zoe'.
6 messages in order. Play them, or step through them one at a time.
Notice that the two sessions use different names and never touch the same row. Each locked the same gap to check for absence, which is allowed, and each insert then needs the gap free of the other's lock. That is a cycle, and InnoDB rolls one back. The FOR UPDATE that was meant to make the check safe is what caused the deadlock.
3The Duplicate-Key Variant
The same thing can happen without any explicit SELECT. When an INSERT finds a duplicate in a unique secondary index, InnoDB takes a shared next-key lock on the conflicting entry before reporting the error. If two sessions insert the same key while a third has inserted it and not yet committed, both wait for shared locks on that entry. When the third rolls back, both get their shared locks, and both then need an exclusive lock to insert, which each other's shared lock blocks: a deadlock. Batch inserts with many rows into busy ranges of a unique index, and REPLACE or INSERT ... ON DUPLICATE KEY UPDATE under heavy concurrency on the same keys, can show similar patterns, so concurrent writers to the same key range should expect occasional deadlocks.
4Reading the Deadlock Report
SHOW ENGINE INNODB STATUS keeps only the latest deadlock. Turning on innodb_print_all_deadlocks writes every deadlock to the error log, which is what we need for a pattern that happens many times a day.
The pattern to recognise is both transactions holding a gap lock on the same index and both waiting for insert intention on it. The index name tells us which unique or secondary index the gap is in, and the earlier statements of each transaction, from the application logs, tell us what took the gap lock.
5Options for Fixing It
The best fix is to stop checking before inserting and let the unique index decide atomically. INSERT ... ON DUPLICATE KEY UPDATE inserts or updates in one statement, INSERT IGNORE inserts or silently skips duplicates, and a plain INSERT that catches the duplicate-key error (Spring's DuplicateKeyException) also works. None of them takes a gap lock for an existence check, so the common deadlock disappears, although heavy concurrency on the same key can still occasionally deadlock as described above.
Running these transactions at READ COMMITTED removes most gap locks, because InnoDB then uses gap locks only for foreign key and duplicate-key checks; the check-then-insert pattern would then not deadlock but would also no longer protect against two inserts of the same key, so the unique index must be the real guard. In every case, keep the transactions short, so locks live briefly, and retry on error 1213, because some deadlocks remain possible under any design.
6Follow-up questions
Why does the FOR UPDATE on a missing row not block the other session's FOR UPDATE?
Because both only take gap locks, and gap locks never conflict with each other. Their only purpose is to stop inserts. That is why both sessions pass the check and only meet when they try to insert.
Would SELECT without FOR UPDATE avoid the deadlock?
It would avoid the gap lock, because a plain SELECT reads a snapshot, but then the check is not protected: both sessions could see no row and both insert. With a unique index, one insert then fails with a duplicate-key error, which is the correct and safe outcome; without a unique index, we would get a duplicate row. So the unique index, not the check, is what guarantees uniqueness.
Does inserting with auto-increment keys cause these deadlocks?
Rarely, because each new row goes to the end of the primary key, past all existing entries, and nobody holds gap locks there unless they ran a locking range read up to the end. The deadlocks come from secondary unique indexes and from gaps that locking reads have touched.
7Conclusion
In this answer, we saw that under REPEATABLE READ a locking read of a missing key takes a gap lock, gap locks are compatible with each other, and an INSERT's insert intention lock conflicts with another transaction's gap lock. Two sessions that check for absence with FOR UPDATE and then insert into the same gap deadlock, and duplicate-key checks on unique indexes can do the same through shared next-key locks. innodb_print_all_deadlocks shows the pattern, and the fixes are INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE instead of check-then-insert, READ COMMITTED where acceptable, short transactions, and retry.
Open with
This is the classic gap lock versus insert intention deadlock. Under REPEATABLE READ, when a session does SELECT ... FOR UPDATE for a key that doesn't exist, InnoDB can't lock a row, so it locks the gap where the key would be.
Then, if they want more
Gap locks are compatible with each other, so a second session checking a different missing key in the same gap gets its own gap lock on it. Then each inserts.
An insert needs an insert intention lock on the gap, which conflicts with the other session's gap lock, so A waits for B and B waits for A, and InnoDB rolls one back with 1213. The status line about insert intention waiting is exactly that.
Duplicate-key checks on unique secondary indexes do something similar with shared next-key locks when several sessions insert the same key. I'd turn on innodb_print_all_deadlocks to confirm the pattern across all occurrences. The fix is to drop check-then-insert and let the unique index decide atomically, with INSERT ...
ON DUPLICATE KEY UPDATE or INSERT IGNORE, or just insert and handle the duplicate-key exception. READ COMMITTED removes most gap locks too. And I'd keep these transactions short and retry deadlocks, because some can always happen.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, MySQL reference manual
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "MySQL reports frequent deadlocks between two INSERT statements into the same table under...": https://scrivio-interview-library.netlify.app/databases/database-locking/c85c57d527/