Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Eliminating MySQL InnoDB
Gap-Lock Deadlocks.

Switch transaction isolation to READ COMMITTED (with binlog_format=ROW) to disable InnoDB gap locks on non-unique range scans, replace FOR UPDATE worker polling with FOR UPDATE SKIP LOCKED, and batch range deletes by primary key.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

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.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

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:

  1. Phantom Insert Blocking: A FOR UPDATE or DELETE on a non-unique index locks gaps—including the open-ended +infinity supremum—blocking unrelated INSERTs.
  2. Insert-Intention Deadlocks: Two transactions hold shared/exclusive gap locks and then request LOCK_INSERT_INTENTION on each other's gaps, triggering Deadlock 1213.
  3. Throughput Collapse: 3,500 TPS inserts stall behind 90-day batch deletes.
InnoDB Gap & Insert-Intention Locks

REPEATABLE READ Next-Key Locking vs. READ COMMITTED + SKIP LOCKED

Worker (FOR UPDATE)REPEATABLE READ: gap lockInnoDB Lock ManagerNext-Key + SupremumCleanup DELETELocks idx_created_at…3.5k/s INSERTsBlocked on…

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.

Engineering Decision Framework
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 UPDATE or DELETE on a non-unique index locks the gaps between records—including the open-ended supremum—blocking unrelated INSERTs.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

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?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

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.

Design Trade-Off

Naive Solution (and Why It Breaks)

Before · Seq Scan + Unbounded Bloat
  • Implicit cast breaks B-Tree
  • Deadlock or XID wraparound risk
  • Long tx blocks VACUUM
After · Indexed Plan + Bounded MVCC
  • Index-only scan in <2 ms
  • Deterministic lock ordering
  • Autovacuum keeps bloat flat
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

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: Since binlog_format = ROW is enabled, READ COMMITTED is replication-safe and disables gap/next-key locks for regular queries (except foreign-key/duplicate-key checks).
  • Worker Queueing with FOR UPDATE SKIP LOCKED: Poll SELECT 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 via SELECT id ... LIMIT 1000 and DELETE FROM ledger_entries WHERE id IN (...)—or better yet, range-partition by created_at and DROP PARTITION in O(1).
Zero-Contention Worker & Cleanup Flow

SKIP LOCKED + PK-Chunked Delete Under 3,500 TPS Inserts

3.5k/s InsertsWorker 1Worker 2PK Cleanup1. SELECT ... FOR UPDATE SKIPLOCKED (rows 1..10)2. Skips locked rows, claims11..20 immediately3. READ COMMITTED: no gap locks oninserts4. DELETE WHERE id IN (batch 1000)-> 0ms stall

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);
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

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 LOCKED turns MySQL/Postgres into a high-throughput concurrent work queue.
  • Ledger & Payment Tables: Time-based partitioning replaces expensive range DELETEs with instant DROP PARTITION.
  • Multi-Worker Batch Processors: Composite indexes + READ COMMITTED keep insert latency flat.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why is switching from `REPEATABLE READ` to `READ COMMITTED` safe in this MySQL 8.0 setup?

Recommended Learning Flow