Quick revision
The short answer
When no row matches, each SELECT ... FOR UPDATE takes a gap lock on the same gap of the index, and gap locks never conflict with each other, so both transactions get one. Each INSERT then needs an insert intention lock in that gap, which must wait for the other transaction's gap lock, so each waits for the other and InnoDB rolls one back with a deadlock error. We fix it with a unique index on (room, day) and an insert that handles the duplicate, or by locking a parent row such as the room, and we always retry deadlock victims.
What to remember
In this answer, we saw that two empty SELECT ... FOR UPDATE reads both take gap locks on the same gap because gap locks are compatible, and then each INSERT's insert intention lock waits for the other's gap lock, a cycle that InnoDB breaks by rolling one back with error 1213. The reliable fix is a unique index on (room, day) with an insert that handles the duplicate, or locking a parent room row when the rule is more complex, plus a retry of deadlock victims around the whole transaction. READ COMMITTED removes the deadlock but, without the unique index, turns it into double bookings.
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.
When no row matches, each SELECT ... FOR UPDATE takes a gap lock on the same gap of the index, and gap locks never conflict with each other, so both transactions get one. Each INSERT then needs an insert intention lock in that gap, which must wait for the other transaction's gap lock, so each waits for the other and InnoDB rolls one back with a deadlock error. We fix it with a unique index on (room, day) and an insert that handles the duplicate, or by locking a parent row such as the room, and we always retry deadlock victims.
Why this question is asked
Check then insert is the most natural way to write a booking: look for the slot, and if it is free, take it. Under concurrency it is also one of the most reliable ways to produce MySQL deadlocks, and the error message gives little hint why, since each transaction touched only an empty slot. Interviewers ask this because explaining it requires understanding gap locks and insert intention locks precisely, and fixing it well requires moving the rule into the database. In this answer, we will recap the locks involved, replay the deadlock step by step, read InnoDB's deadlock report, and then go through the fixes, the retry, and what READ COMMITTED would change.
1A Quick Recap of the Locks Involved
At REPEATABLE READ, the default in InnoDB, a locking read locks the index entries it scans and the gaps between them, so that no other transaction can insert a row the read would have seen. When the search finds nothing, InnoDB still locks the gap where a matching row would go. That gap lock blocks inserts by others, but gap locks held by different transactions do not conflict with each other: two transactions can both hold a gap lock on the same empty space.
Before an INSERT, InnoDB requests an insert intention lock in the gap where the new entry belongs. Insert intention locks are compatible with each other, but they must wait for gap locks held by other transactions. Let us assume the table has a non-unique index on (room, day), which the query uses.
2Replaying the Deadlock Step by Step
Two requests try to book room 1 on 2026-11-05 at the same moment.
10 messages in order. Play them, or step through them one at a time.
Both SELECTs succeed because gap locks are compatible, so both transactions believe the slot is free. T1's insert asks for an insert intention lock and waits for T2's gap lock. T2's insert asks for the same and waits for T1's gap lock. Each waits for the other, a cycle, and no amount of waiting will break it. InnoDB's deadlock detector notices the cycle immediately, picks a victim (usually the transaction that changed fewer rows), rolls it back, and returns error 1213 to that client. The other transaction then proceeds.
3Reading InnoDB's Deadlock Report
SHOW ENGINE INNODB STATUS keeps the most recent deadlock in its LATEST DETECTED DEADLOCK section, and setting innodb_print_all_deadlocks=ON writes every deadlock to the error log, which is what we want in production. The report shows each transaction's statement, the locks it held and the lock it waited for.
The two key phrases are locks gap before rec, a gap lock, and insert intention waiting. Seeing them together on the same index is the signature of this read-then-insert deadlock.
4Fix 1: Let a Unique Index Enforce the Rule
The real rule is one booking per room per day, so we give it to the database as a unique index and stop reading before inserting. The first insert wins; the second gets a duplicate key error, which is a clear business answer instead of a deadlock.
If the operation should update an existing booking instead, INSERT ... ON DUPLICATE KEY UPDATE does the check and the write in one statement. Notice that the race has not disappeared; it has moved to the one place that can decide it atomically, the unique index. Concurrent inserts of the same key can still deadlock in rare three-way cases, so the retry below still matters, but the everyday pattern is gone.
5Fix 2: Lock a Parent Row That Always Exists
When the rule is more complex than uniqueness, for example at most three bookings per room per day, we serialise the bookings for one room by locking the room row first. The room row always exists, so this is a plain record lock with no gaps involved.
The second transaction simply waits at the first line and then sees the committed booking. The cost is that bookings for the same room run one at a time, which is fine for a booking system and would be too strict for a hot counter.
6Always Retry Deadlock Victims
Any InnoDB application can see a deadlock now and then, so the application must retry the whole transaction when it is the victim. Error 1213 with SQLSTATE 40001 means the transaction was rolled back and is safe to run again. Spring translates it into a PessimisticLockingFailureException subclass, CannotAcquireLockException in recent versions (older versions used DeadlockLoserDataAccessException; check your version). The retry must wrap the transactional method from outside, so each attempt starts a fresh transaction; Spring Retry's @Retryable or the built-in @Retryable in Spring Framework 7 work, with two or three attempts and a short random backoff.
7Follow-up questions
Would READ COMMITTED make this deadlock go away?
Yes, but for a dangerous reason. At READ COMMITTED, InnoDB takes no gap locks for the SELECT, so both empty reads lock nothing and both inserts succeed. Without a unique index that means two bookings for the same slot, a silent double booking instead of a loud deadlock. With the unique index from fix 1, the second insert fails with a duplicate key error, which is the correct outcome at either isolation level.
Why did InnoDB not just make one transaction wait?
Because waiting cannot resolve a cycle. T1 waits for a lock T2 holds and T2 waits for a lock T1 holds, so neither can ever proceed. Rolling one back is the only way out, and InnoDB detects it immediately instead of waiting for the lock wait timeout.
8Conclusion
In this answer, we saw that two empty SELECT ... FOR UPDATE reads both take gap locks on the same gap because gap locks are compatible, and then each INSERT's insert intention lock waits for the other's gap lock, a cycle that InnoDB breaks by rolling one back with error 1213. The reliable fix is a unique index on (room, day) with an insert that handles the duplicate, or locking a parent room row when the rule is more complex, plus a retry of deadlock victims around the whole transaction. READ COMMITTED removes the deadlock but, without the unique index, turns it into double bookings.
Open with
Both transactions run SELECT FOR UPDATE for a slot that does not exist. At REPEATABLE READ, InnoDB still locks the gap where that row would go, and gap locks do not conflict with each other, so both transactions get one and both think the slot is free.
Then, if they want more
Then each INSERT needs an insert intention lock in that same gap, and an insert intention lock has to wait for gap locks held by other transactions. So T1 waits for T2's gap lock and T2 waits for T1's. That is a cycle, InnoDB detects it, rolls back the cheaper transaction with error 1213, and the other insert goes through.
In the deadlock report I would expect to see locks gap before rec and insert intention waiting on the same index.
My main fix is to let the database enforce the rule: add a unique index on room and day, drop the read, just insert, and translate the duplicate key error into a slot-taken response, or use INSERT ON DUPLICATE KEY UPDATE if it is an upsert.
If the rule is more than uniqueness, like a limit per day, I would lock the room row FOR UPDATE first to serialise bookings per room. Either way I would retry deadlock victims, error 1213, around the whole transaction, which Spring surfaces as a pessimistic locking failure.
READ COMMITTED would remove the deadlock but, without the unique index, it would allow double bookings.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 7
- 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
- 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 "Two transactions run concurrently: each does SELECT * FROM slots WHERE room=1 AND...": https://scrivio-interview-library.netlify.app/databases/mysql/beb819fdf7/