When a single bottleneck threatens end-to-end availability, under MySQL's default `REPEATABLE READ`, `SELECT ... FOR UPDATE` or `DELETE` on a non-unique index locks the gaps between records—including the open-ended supremum—blocking unrelated `INSERT`s.
TL;DR30-second simplified summary▾
Core Mechanics: On MySQL 8.0 (REPEATABLE READ, binlog_format = ROW) handling 3,500 INSERTs/sec into ledger_entries, a worker polling SELECT id FROM ledger_entries WHERE status = 'PENDING' AND account_id = 42 FOR UPDATE and a cleanup job running DELETE FROM ledger_entries WHERE created_at < NOW() - INTERVAL 90 DAY on non-unique idx_created_at trigger frequent ERROR 1213 (40001): Deadlock found.
Visual & Structural Flow: Depicts REPEATABLE READ Next-Key Locking vs. READ COMMITTED + SKIP LOCKED (Worker (FOR UPDATE) -> InnoDB Lock Manager -> Cleanup DELETE -> 3.5k/s INSERTs); SKIP LOCKED + PK-Chunked Delete Under 3,500 TPS Inserts (3.5k/s Inserts -> Worker 1 -> Worker 2 -> PK Cleanup).
Trade-Offs & Production: Retrying Deadlock 1213 in application code masks the symptom while still burning lock waits and CPU under 3,500 TPS inserts. Eliminate InnoDB gap locks safely while guaranteeing zero duplicate worker processing: Set transaction_isolation = READ-COMMITTED: Since binlog_format = ROW is enabled.
Failure Modes & Application: InnoDB lock contention is a classic bottleneck in high-write MySQL systems: Transactional Outbox & Job Queues: FOR UPDATE SKIP LOCKED turns MySQL/Postgres into a high-throughput concurrent work queue.
Why MySQL InnoDB Gap-Lock Deadlocks Matter.
Why this matters: The mechanism: understand how Why MySQL InnoDB Gap-Lock Deadlocks Matter works from first principles.
Think of Why MySQL InnoDB Gap-Lock Deadlocks Matter as the intuition layer for Eliminating MySQL InnoDB Gap-Lock Deadlocks: The mechanism: understand how Why MySQL InnoDB Gap-Lock Deadlocks Matter works from first principles.
On MySQL 8.0 (REPEATABLE READ, binlog_format = ROW) handling 3,500 INSERTs/sec into ledger_entries, a worker polling SELECT id FROM ledger_entries WHERE status = 'PENDING' AND account_id = 42 FOR UPDATE and a cleanup job running DELETE FROM ledger_entries WHERE created_at < NOW() - INTERVAL 90 DAY on non-unique idx_created_at trigger frequent ERROR 1213 (40001): Deadlock found.
Real-World Impact of Next-Key & Gap-Lock Contention.
Why this matters: The problem: see what breaks without Real-World Impact of Next-Key & Gap-Lock Contention under real concurrency or scale.
Under MySQL's default REPEATABLE READ, range scans acquire Next-Key Locks (record + preceding gap) and Supremum Gap Locks:
- Phantom Insert Blocking: A
FOR UPDATEorDELETEon a non-unique index locks gaps—including the open-ended+infinitysupremum—blocking unrelatedINSERTs. - Insert-Intention Deadlocks: Two transactions hold shared/exclusive gap locks and then request
LOCK_INSERT_INTENTIONon each other's gaps, triggeringDeadlock 1213. - Throughput Collapse: 3,500 TPS inserts stall behind 90-day batch deletes.
REPEATABLE READ Next-Key Locking vs. READ COMMITTED + SKIP LOCKED
1.Why Gap Locks Exist: InnoDB prevents phantom rows under REPEATABLE READ.
2.READ COMMITTED: Disables gap locks (safe with binlog_format=ROW); only locks matched rows.
3.SKIP LOCKED: SELECT ... FOR UPDATE SKIP LOCKED lets workers claim rows without waiting.
4.PK-Chunked Deletes: Delete by primary key batches (LIMIT 1000) instead of range scans.
Switching to READ COMMITTED (with ROW binlog), FOR UPDATE SKIP LOCKED, and PK-batched deletes eliminates gap-lock deadlocks.
- Problem
- How to implement Eliminating MySQL InnoDB Gap-Lock Deadlocks without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- When a single bottleneck threatens end-to-end availability, under MySQL's default
REPEATABLE READ,SELECT ... FOR UPDATEorDELETEon a non-unique index locks the gaps between records—including the open-ended supremum—blocking unrelatedINSERTs. - Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Eliminating MySQL InnoDB Gap-Lock Deadlocks experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Naive Solution (and Why It Breaks).
Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.
Think of Naive Solution (and Why It Breaks) as the intuition layer for Eliminating MySQL InnoDB Gap-Lock Deadlocks: The problem: see what breaks without Naive Solution under real concurrency or scale.
Retrying Deadlock 1213 in application code masks the symptom while still burning lock waits and CPU under 3,500 TPS inserts. Adding LOCK IN SHARE MODE or widening indexes without changing REPEATABLE READ or query patterns still acquires gap locks on non-unique ranges.
Naive Solution (and Why It Breaks)
- Implicit cast breaks B-Tree
- Deadlock or XID wraparound risk
- Long tx blocks VACUUM
- Index-only scan in <2 ms
- Deterministic lock ordering
- Autovacuum keeps bloat flat
Enterprise Solution: `READ COMMITTED`, `SKIP LOCKED` & PK-Chunked Deletes.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Eliminate InnoDB gap locks safely while guaranteeing zero duplicate worker processing:
- Set
transaction_isolation = READ-COMMITTED: Sincebinlog_format = ROWis enabled,READ COMMITTEDis replication-safe and disables gap/next-key locks for regular queries (except foreign-key/duplicate-key checks). - Worker Queueing with
FOR UPDATE SKIP LOCKED: PollSELECT id FROM ledger_entries WHERE status='PENDING' AND account_id=? ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKED(backed by composite index(status, account_id, id)). - PK-Batched Cleanup & Partitioning: Fetch
ids viaSELECT id ... LIMIT 1000andDELETE FROM ledger_entries WHERE id IN (...)—or better yet, range-partition bycreated_atandDROP PARTITIONin O(1).
SKIP LOCKED + PK-Chunked Delete Under 3,500 TPS Inserts
Workers never block each other, and 3,500 TPS inserts proceed without gap-lock interference.
-- Inspect active InnoDB lock waits
SELECT r.trx_id waiting_trx, r.trx_mysql_thread_id waiting_thread,
b.trx_id blocking_trx, l.lock_mode, l.lock_type, l.lock_data
FROM performance_schema.data_lock_waits w
JOIN information_schema.innodb_trx r ON r.trx_id = w.REQUESTING_ENGINE_TRANSACTION_ID
JOIN information_schema.innodb_trx b ON b.trx_id = w.BLOCKING_ENGINE_TRANSACTION_ID
JOIN performance_schema.data_locks l ON l.ENGINE_LOCK_ID = w.BLOCKING_ENGINE_LOCK_ID;
-- Safe PK-chunked purge (run in loop incrementing @cur_id by 1000)
DELETE FROM ledger_entries
WHERE id BETWEEN @cur_id AND @cur_id + 999
AND created_at < NOW() - INTERVAL 90 DAY;
@Retryable(retryFor = CannotAcquireLockException.class, maxAttempts = 4,
backoff = @Backoff(delay = 25, maxDelay = 200, multiplier = 2, random = true))
@Transactional(isolation = Isolation.READ_COMMITTED)
public List<Long> claimPendingBatch(long accountId, int limit) {
return jdbc.queryForList(
"SELECT id FROM ledger_entries WHERE status = 'PENDING' AND account_id = ? ORDER BY id LIMIT ? FOR UPDATE SKIP LOCKED",
Long.class, accountId, limit);
}
Where Gap-Lock Avoidance Applies in System Design.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
InnoDB lock contention is a classic bottleneck in high-write MySQL systems:
- Transactional Outbox & Job Queues:
FOR UPDATE SKIP LOCKEDturns MySQL/Postgres into a high-throughput concurrent work queue. - Ledger & Payment Tables: Time-based partitioning replaces expensive range
DELETEs with instantDROP PARTITION. - Multi-Worker Batch Processors: Composite indexes +
READ COMMITTEDkeep insert latency flat.
Practice: Make the trade-off yourself.
Why is switching from `REPEATABLE READ` to `READ COMMITTED` safe in this MySQL 8.0 setup?