Tech Interview RoomStudy guides

MySQL

Explain InnoDB locking: record, gap and next-key locks, and common deadlocks.

Intermediate · 2 min read · Lesson 3 of 5 in MySQL

At the default Repeatable Read level, InnoDB locks index ranges, not just rows, to prevent phantoms:

  • Record lock: locks one index record.
  • Gap lock: locks the gap between index records, so no one can insert there.
  • Next-key lock: record plus the gap before it (the default for locking reads and updates that scan a range).
  • Insert intention lock: a special gap lock taken by inserts.

Plain SELECTs are non-locking consistent reads (MVCC). SELECT ... FOR UPDATE, FOR SHARE, UPDATE and DELETE take locks on every index record they scan, not only those that match.

Why this causes surprises

  • An UPDATE ... WHERE status = 'NEW' without an index on status scans and locks the whole table.
  • Two transactions doing "check if row exists, else insert" with SELECT ... FOR UPDATE on a missing key both take gap locks, then both try to insert → deadlock.
  • Locks are held until commit, so long transactions block others.

Mitigations

Index the columns in WHERE of updates and locking reads; keep transactions short; access rows in a consistent order; prefer INSERT ... ON DUPLICATE KEY UPDATE over check-then-insert; consider Read Committed, which disables most gap locking (good for many OLTP apps, requires row-based binlog); retry on deadlock errors (1213).

Example

sql
-- Session A
START TRANSACTION;
SELECT * FROM seats WHERE show_id = 7 AND seat_no = 'C4' FOR UPDATE;  -- row does not exist: gap lock

-- Session B
START TRANSACTION;
SELECT * FROM seats WHERE show_id = 7 AND seat_no = 'C5' FOR UPDATE;  -- same gap: also allowed

-- A: INSERT INTO seats ... 'C4'  → waits for B's gap lock
-- B: INSERT INTO seats ... 'C5'  → waits for A  → deadlock, one is rolled back

-- Safer: rely on the unique key
INSERT INTO seats (show_id, seat_no, user_id) VALUES (7, 'C4', 99);   -- duplicate key error means taken

SHOW ENGINE INNODB STATUS shows the latest deadlock with both transactions' locks; performance_schema.data_locks shows current locks.

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you handle deadlocks in a Spring application?

Treat them as transient: catch CannotAcquireLockException / DeadlockLoserDataAccessException and retry the whole transaction a few times with a short backoff (Spring Retry's @Retryable around the @Transactional method, so each attempt is a new transaction).