Quick revision
The short answer
Under REPEATABLE READ, a SELECT ... FOR UPDATE that finds no row cannot lock a row, so InnoDB locks the gap in the index where the row would go. Gap locks from different transactions do not conflict, so both transactions get one, but an INSERT into that gap needs an insert intention lock that does conflict with the other transaction's gap lock. Each insert waits for the other, which is a deadlock; we avoid it with INSERT ... ON DUPLICATE KEY UPDATE, by inserting first and handling the duplicate key error, or by using READ COMMITTED.
What to remember
In this answer, we saw why check-then-insert deadlocks in InnoDB under REPEATABLE READ. A locking read on a missing row takes a gap lock, gap locks from different transactions are compatible, and each subsequent insert needs an insert intention lock that conflicts with the other transaction's gap lock, so the two inserts wait for each other. Letting the unique key decide, with ON DUPLICATE KEY UPDATE or insert-and-catch, removes the problem, and READ COMMITTED reduces gap locking if we can live without phantom protection.
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 SELECT ... FOR UPDATE that finds no row cannot lock a row, so InnoDB locks the gap in the index where the row would go. Gap locks from different transactions do not conflict, so both transactions get one, but an INSERT into that gap needs an insert intention lock that does conflict with the other transaction's gap lock. Each insert waits for the other, which is a deadlock; we avoid it with INSERT ... ON DUPLICATE KEY UPDATE, by inserting first and handling the duplicate key error, or by using READ COMMITTED.
Why this question is asked
The check-then-insert pattern looks perfectly safe: lock the row if it exists, and if it does not, insert it. Many teams write it to implement get-or-create, counters or unique reservations, and it deadlocks under concurrency in MySQL. Interviewers ask this question to see whether we know how InnoDB locks things that do not exist yet, because that knowledge explains a whole family of surprising deadlocks. In this answer, we will recap record, gap and next-key locks, reproduce the deadlock, walk through why the locks are compatible at first and incompatible later, and then compare the fixes.
1A Quick Recap of InnoDB Locks
InnoDB locks index entries, not abstract rows. A record lock locks one index entry, for example the entry for id 10 in the primary key. A gap lock locks the space between two index entries, for example everything between 10 and 20, so that nobody can insert a value into that space. A next-key lock is the combination of the two: the record plus the gap before it. Under REPEATABLE READ, which is InnoDB's default isolation level, locking reads such as SELECT ... FOR UPDATE use next-key and gap locks to stop phantoms, new rows appearing in a range we have already read.
There is one more lock type that matters here. Before inserting a row, InnoDB takes an insert intention lock on the gap where the row will go. It is a special kind of gap lock that says I am about to insert into this gap. Insert intention locks do not conflict with each other, so two transactions can insert different values into the same gap at once, but they do conflict with an ordinary gap lock held by another transaction.
2Reproducing the Deadlock
Suppose a table holds ids 10 and 20, and two requests both want to create id 15 if it is not there.
Notice that the second SELECT did not wait. If FOR UPDATE had locked a real row, session 2 would have blocked right there and the problem would not exist. Instead, both sessions walked away believing they had protected id 15.
3Why Both SELECTs Succeed
The row with id 15 does not exist, so there is no record to lock. To make sure no one inserts id 15 behind our back, InnoDB locks the gap between 10 and 20 instead. We can see this in performance_schema.data_locks, where the lock mode shows as X,GAP on the index entry for 20.
Gap locks have an unusual rule: they never conflict with other gap locks. Their only purpose is to stop inserts, so InnoDB lets several transactions hold a gap lock on the same gap at the same time. The reason is practical: if gap locks blocked each other, simple range reads would serialize far more often than needed. So session 2 receives its own gap lock on (10, 20) without waiting.
4Why the INSERTs Deadlock
Now session 1 inserts id 15. It needs an insert intention lock on the gap, and that conflicts with session 2's gap lock, so session 1 waits for session 2. Then session 2 inserts id 15. It needs an insert intention lock on the same gap, which conflicts with session 1's gap lock, so session 2 waits for session 1. That is a cycle, and InnoDB detects it immediately, rolls back one session and reports error 1213. The survivor then completes its insert.
| Held by the other session | Requested | Result |
|---|---|---|
| gap lock (X,GAP) | gap lock from SELECT ... FOR UPDATE | granted: gap locks never conflict |
| gap lock (X,GAP) | insert intention for id 15 | waits: inserts are what gap locks block |
| insert intention | insert intention for a different id | granted: different inserts can share a gap |
So the deadlock is not caused by bad lock order in our code. It is caused by two locks that are compatible when they are taken and incompatible with the next step that both transactions take. The output of SHOW ENGINE INNODB STATUS confirms it: in the LATEST DETECTED DEADLOCK section, each transaction holds a lock described as locks gap before rec and waits for one described as insert intention.
5Fix 1: Let the Insert Decide
The cleanest fix is to stop asking whether the row exists and simply try to insert it. The unique primary key is the real guard: only one insert of id 15 can win.
With insert first, the second session waits on the first session's lock on the new record, and when the first commits it gets a duplicate key error instead of a deadlock. ON DUPLICATE KEY UPDATE does the same in a single statement. These statements can still deadlock in some unusual concurrent cases, so the retry safety net remains useful, but the everyday collision disappears.
6Fix 2: Use READ COMMITTED
At READ COMMITTED, InnoDB turns off gap locking for searches and index scans and uses it only for foreign key and duplicate key checks. A SELECT ... FOR UPDATE that finds nothing then locks nothing at all, so the two sessions go straight to their inserts. One insert wins and the other waits on the new record and then fails with a duplicate key error, which we handle as in fix 1.
The cost is that READ COMMITTED does not stop phantoms, so a transaction that reads a range twice can see new rows the second time. Many applications are fine with that, and in Spring we can choose it per transaction with @Transactional(isolation = Isolation.READ_COMMITTED). But we should only switch after checking that no logic depends on stable ranges.
7Follow-up questions
Does the same thing happen in PostgreSQL?
No. PostgreSQL has no gap locks; SELECT ... FOR UPDATE on a missing row simply locks nothing. Two sessions can both find nothing and both insert, and the unique index makes the second insert wait and then fail with a unique violation (SQLState 23505). The usual PostgreSQL tool for this pattern is INSERT ... ON CONFLICT DO NOTHING or DO UPDATE.
Why does InnoDB lock gaps at all?
To give REPEATABLE READ its promise for locking reads. If a transaction runs SELECT ... WHERE id BETWEEN 10 AND 20 FOR UPDATE twice, it must see the same rows both times, so no other transaction may insert into that range until it commits. Gap locks are how InnoDB prevents those phantom rows.
Would a unique secondary index behave differently from the primary key?
The pattern is the same. An equality search on a unique index that finds no matching row still locks the gap where the value would be, so two transactions get compatible gap locks and their inserts then wait for each other. On a non-unique index, InnoDB uses next-key locks even when rows match, so the locked range is often wider.
8Conclusion
In this answer, we saw why check-then-insert deadlocks in InnoDB under REPEATABLE READ. A locking read on a missing row takes a gap lock, gap locks from different transactions are compatible, and each subsequent insert needs an insert intention lock that conflicts with the other transaction's gap lock, so the two inserts wait for each other. Letting the unique key decide, with ON DUPLICATE KEY UPDATE or insert-and-catch, removes the problem, and READ COMMITTED reduces gap locking if we can live without phantom protection.
Open with
The SELECT FOR UPDATE finds no row, so there is no record to lock. Under REPEATABLE READ, InnoDB protects against phantoms by locking the gap in the index where id 15 would go, for example between 10 and 20.
Then, if they want more
The key detail is that gap locks never conflict with each other, because their only job is to block inserts. So the second transaction gets its own gap lock on the same gap without waiting, and both think they own id 15. Then each transaction inserts.
An insert needs an insert intention lock on the gap, and that does conflict with a gap lock held by another transaction. So transaction one waits for transaction two's gap lock, transaction two waits for transaction one's, and InnoDB detects the cycle and rolls one back with error 1213.
SHOW ENGINE INNODB STATUS shows exactly that: gap locks held and insert intention locks waiting. To fix it, I let the unique key decide: INSERT ... ON DUPLICATE KEY UPDATE, or insert first and catch DuplicateKeyException, then read the existing row.
Another option is READ COMMITTED, where InnoDB stops gap locking for searches, as long as nothing depends on phantom protection. I would keep a small retry for any remaining deadlocks.
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
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "In MySQL InnoDB under REPEATABLE READ, two transactions that each run SELECT ... FOR...": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/35f6e44236/