MySQL interview question · Most asked
What causes deadlocks in MySQL, and how do you handle them?
Summary
A deadlock happens when two transactions each hold a lock the other needs. InnoDB detects it and rolls back one transaction (the 'victim') with error 1213. Applications must retry the whole transaction, and reduce deadlocks by locking in a consistent order and keeping transactions short.
Longer Answer
Typical causes: two transactions updating the same rows in opposite order (transfer A to B while B to A); gap or next-key locks from concurrent inserts into the same range; unindexed lookups that lock many rows; foreign-key checks.
Diagnosis: SHOW ENGINE INNODB STATUS shows the latest deadlock with both statements and the locks involved; innodb_print_all_deadlocks=ON logs every deadlock. performance_schema.data_locks shows current locks.
Prevention: access rows in a consistent order (for example by primary key), keep transactions small and fast, index the columns in WHERE clauses of updates, and avoid user think-time inside transactions. Deadlocks can never be eliminated entirely in a busy system, so retry with a small backoff.
Key Points
- Circular waits; InnoDB rolls back one (error 1213).
- Retry the whole transaction.
- Consistent lock order, short transactions, good indexes.
SHOW ENGINE INNODB STATUSfor diagnosis.
Deep dive: Code Clinic: review a PHP money transfer
More most-asked MySQL questions
- Why is OFFSET pagination slow on large tables, and what is keyset pagination?
- How do you read EXPLAIN output in MySQL?
- What is a clustered index in InnoDB, and why does primary key choice matter so much?
- Why might MySQL not use an index you created?
- What are the transaction isolation levels, and which does InnoDB use by default?
- How does a composite index work, and what is the leftmost-prefix rule?
- What are gap locks and next-key locks, and why do they surprise developers?
- How does MySQL replication work? Explain the binary log, asynchronous and semi-synchronous replication, and GTIDs.