Concurrent INSERT on Unique Index: MySQL Lock Waits & Deadlocks Explained
This article analyzes how concurrent INSERT operations on a MySQL unique index cause lock waits and deadlocks under READ-COMMITTED isolation, detailing InnoDB lock types, SELECT FOR UPDATE and INSERT locking behavior, a step-by-step deadlock scenario with timeline, and mitigation strategies including application-level retries and a known MySQL 8.0.28 bug fix.
Reading font
Business Scenario
Environment: MySQL 8.0.25, InnoDB storage engine, READ-COMMITTED isolation level.
Table structure:
create table t1(
id int auto_increment,
c1 int not null default 0,
c2 varchar(20),
primary key(id),
unique index uniq_index1(c1)
);Primary Key (id): auto-increment integer. InnoDB uses an index-organized table (IOT); data rows are stored in the clustered index (primary key). Row access and locking always involve the primary key index.
Unique Index (uniq_index1 on c1): Business logic revolves around c1=xx. The unique index is the critical path for queries and uniqueness enforcement. Its presence affects SELECT ... FOR UPDATE and INSERT locking behavior.
InnoDB secondary indexes (including unique indexes) store the index column value plus the corresponding primary key value in leaf nodes.
Business Model
Two transactions in the same session:
Transaction 1: SELECT ... FOR UPDATE on unique index c1=xx. If record exists, UPDATE; else INSERT unique key value.
Transaction 2: DELETE the record processed by Transaction 1.
Single-session execution is sequential, no conflict. Under concurrency, multiple sessions executing Transaction 1 → Transaction 2 cause lock waits and deadlocks.
MySQL Lock Mechanisms
InnoDB Lock Types
Record Lock : Row lock on a single index record. E.g., SELECT ... WHERE c1 = xx FOR UPDATE on existing record places an X record lock on uniq_index1.
Gap Lock : Locks a range between index records, or before first/after last record. Prevents phantom reads. Disabled for ordinary scans in READ-COMMITTED.
Next-Key Lock : Combination of record lock and gap lock; locks a record and the gap before it. Default in REPEATABLE-READ.
Insert Intention Lock : Special gap lock set by INSERT before inserting. Multiple transactions can hold insert intention locks on the same gap if inserting at different positions. Incompatible with gap locks and next-key locks.
Supremum Record : Virtual position greater than any actual key value, at the end of each index page (B+ tree leaf). INSERT locks the gap between the current key and supremum.
READ-COMMITTED Lock Strategy
Gap locks disabled for searches and index scans; only used for foreign key and duplicate key checks.
Non-matching row record locks released early: after WHERE evaluation, InnoDB releases record locks on rows not matching the condition.
Semi-Consistent Read for UPDATE: If a row is locked by another transaction, InnoDB returns the latest committed version to the server layer to evaluate WHERE; if not matched, skips the row, avoiding unnecessary lock waits.
SELECT ... FOR UPDATE in READ-COMMITTED
Record exists : InnoDB places an exclusive record lock (X, REC_NOT_GAP) on the unique index record and on the corresponding primary key record. No gap locks. Example performance_schema.data_locks output shows two X,REC_NOT_GAP locks on uniq_index1 and PRIMARY.
Record does not exist : Query returns empty set; no record or gap locks are acquired. Transaction proceeds to INSERT branch.
INSERT Lock Behavior
Successful INSERT : Sets an exclusive record lock (X Record Lock) on the new row; not a next-key lock, so does not block inserts in the gap before the new row.
Duplicate Key Error : On unique key conflict, the transaction acquires a shared lock (S lock) on the existing conflicting index record to examine its state. If that record is already X-locked by another transaction, the S lock request waits.
INSERT ... ON DUPLICATE KEY UPDATE : On duplicate, takes an X record lock on duplicate primary key, or an X next-key lock on duplicate unique key.
DELETE Lock Behavior
Similar to UPDATE: places X locks on each row to be deleted. Uses unique index to find primary key, then locks the primary key record. In READ-COMMITTED, equality delete on unique index locks only the specific record; no gap locks.
Lock Wait Analysis
Record Exists: SELECT FOR UPDATE Queueing
Session A holds X lock on c1=xx; Session B attempts same X lock, blocks. If Session A holds lock >50 seconds (innodb_lock_wait_timeout), Session B times out and rolls back with "Lock wait timeout exceeded". data_locks view shows Session B's lock status as WAITING on uniq_index1.
Record Not Exists: INSERT Unique Key Conflict Wait
T0: Session A runs SELECT ... FOR UPDATE WHERE c1=xx; no record, no locks.
T1: Session A runs INSERT INTO t1(c1,c2) VALUES (xx, 'aa'); succeeds, gains X_Insert lock on new record.
T2: Session B runs SELECT ... FOR UPDATE WHERE c1=xx; in READ-COMMITTED, sees no committed record, also judges record absent.
T3: Session B runs INSERT INTO t1(c1,c2) VALUES (xx, 'bb').
Conflict: Session B's INSERT detects duplicate key, requests S lock on the uncommitted record held by Session A.
Incompatibility: S lock vs X_Insert lock → Session B blocks.
Timeout: If Session A does not commit within 50 seconds, Session B times out and rolls back. data_locks view shows a WAITING S lock on uniq_index1 for Session B.
Deadlock Scenario Analysis
Three lock types involved in unique index inserts:
S lock for uniqueness check (short-lived, multiple transactions can hold simultaneously).
X lock held for the duration of the transaction after insert.
Insert Intention Lock indicating intent to insert in a gap.
Scenario: Table has c1=10. Session S1 runs DELETE WHERE c1=10 (holds X lock on that record, marked deleted but not physically removed). Sessions S2 and S3 concurrently try to INSERT c1=11 (adjacent gap).
Timeline Session S1 (DELETE) Session S2 (INSERT) Session S3 (INSERT)
----- --------------------- --------------------- ---------------------
T1 BEGIN;
T2 DELETE FROM t1 WHERE c1=10;
└─ gains X lock on c1=10
T3 BEGIN;
T4 SELECT WHERE C1=11 FOR UPDATE; no record
T4 INSERT INTO t1 VALUES(11, ...);
├─ requests S lock on c1=11 (uniqueness check)
└─ waits for S1's X lock release (blocked)
T5 BEGIN;
T6 SELECT WHERE C1=11 FOR UPDATE; no record
T6 INSERT INTO t1 VALUES(11, ...);
├─ requests S lock on c1=11
└─ waits for S1's X lock release (blocked)
T7 COMMIT; -- immediate
├─ releases X lock on c1=10
└─ record physically deleted
T8 S2 wakes, tries to acquire locks
├─ gets S lock on c1=10 (uniqueness check) success
├─ check passes, releases S lock
├─ acquires insert intention lock
└─ inserts new record, gains implicit X lock
T9 S3 wakes simultaneously
├─ also tries to get S lock on c1=10
└─ competition may occurDeadlock wait graph:
T8: S2 gets S lock (check uniqueness) → success
T8: S2 releases S lock → prepares to insert
T8: S3 simultaneously gets S lock (check uniqueness) → success
T9: S2 tries to get X lock to insert → must wait for all S locks to release (including S3's)
T9: S3 tries to get X lock to insert → must wait for all S locks to release (including S2's)
Result: S2 waits for S3, S3 waits for S2 → deadlockOptimization Suggestions
The core issue is using lock resources to implement optimistic locking, reducing lock hold time to improve concurrency. When timeouts or deadlocks occur, add application-level retry logic: catch error codes (e.g., ERROR 1213), retry with random backoff, max retry limit, and log retries for diagnostics.
Supplement: MySQL community bug #32554667 (fixed in MySQL 8.0.28, 2022-01-18). In READ-COMMITTED with index_condition_pushdown=ON, locks on unmatched secondary indexes were held until transaction end, hurting concurrency. The fix releases unmatched secondary index locks immediately after scan. However, early release changes lock release order; with interleaved transactions on same data, this can increase deadlock frequency. Application retries remain necessary.
Bug description: With index_condition_pushdown=ON and transaction_isolation='READ-COMMITTED', locks on secondary indexes were not released until the transaction was either committed or rolled back, even though the secondary indexes were unmatched. (Bug #102722, Bug #32554667)
Bug explanation: In READ-COMMITTED, if a secondary index does not match the query condition, the lock is still held until transaction end, reducing concurrency. The fix optimizes lock release so unmatched secondary index locks are released immediately after scanning, not waiting for commit/rollback. However, lock release order changes from fixed to early release; if multiple transactions interleave on the same data, inconsistent release order may cause deadlocks.
Some vendors have backported the fix, but early lock release may increase deadlock frequency; application-level retry remains the safety net.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.