SELECT ... FOR UPDATE on an unindexed column locked every row in the table
A job that claimed work items with FOR UPDATE meant to lock one row. Without an index on the filter column, InnoDB locked every row it scanned, and all other workers queued behind it. How data_locks showed the real lock set and why an index fixed it.
We run a pool of workers that send outgoing webhooks. Each worker claims one pending delivery at a time from a MySQL table, sends it, and marks it done. After we doubled the number of workers from 8 to 16 to clear a backlog, throughput did not double. It dropped by half, and workers started logging:
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction
The claim query:
START TRANSACTION;
SELECT id, url, payload FROM webhook_deliveries
WHERE status = 'pending' AND tenant_id = 4182
ORDER BY id
LIMIT 1
FOR UPDATE;
-- send the webhook, then:
UPDATE webhook_deliveries SET status = 'sent', sent_at = NOW() WHERE id = ?;
COMMIT;
Each worker handled one tenant at a time (tenants were assigned round-robin), so in our heads, workers for different tenants could not possibly block each other. They were blocking each other constantly.
Looking at the real locks
MySQL 8.0 exposes every lock InnoDB currently holds in performance_schema.data_locks. With one worker
paused inside its transaction, right after the SELECT ... FOR UPDATE:
SELECT object_name, index_name, lock_type, lock_mode, lock_status, count(*) AS locks
FROM performance_schema.data_locks
WHERE object_name = 'webhook_deliveries'
GROUP BY object_name, index_name, lock_type, lock_mode, lock_status;
+--------------------+------------+-----------+---------------+-------------+--------+
| object_name | index_name | lock_type | lock_mode | lock_status | locks |
+--------------------+------------+-----------+---------------+-------------+--------+
| webhook_deliveries | NULL | TABLE | IX | GRANTED | 1 |
| webhook_deliveries | PRIMARY | RECORD | X | GRANTED | 214388 |
+--------------------+------------+-----------+---------------+-------------+--------+
One worker, one row wanted, 214,388 exclusive record locks on the primary key: every row in the table at that moment. Another worker for a different tenant was waiting:
SELECT waiting_engine_transaction_id, blocking_engine_transaction_id, waiting_query
FROM sys.innodb_lock_waits;
| 912441 | 912398 | SELECT id, url, payload FROM webhook_deliveries WHERE status = 'pending' AND tenant_id = 5507 ... FOR UPDATE |
The plan
EXPLAIN SELECT id FROM webhook_deliveries
WHERE status = 'pending' AND tenant_id = 4182 ORDER BY id LIMIT 1 FOR UPDATE;
| id | select_type | table | type | possible_keys | key | rows | filtered | Extra |
| 1 | SIMPLE | webhook_deliveries | index | NULL | PRIMARY | 214388 | 1.00 | Using where |
No index on tenant_id or status. MySQL walked the primary key in id order, checking each row
against the WHERE.
InnoDB locks what it scans, not what it returns
A locking read in InnoDB sets locks on the index records it scans to find the result, not only on the
rows that match. The MySQL manual says this directly: a locking read, UPDATE or DELETE sets record
locks on every index record scanned in processing the statement, regardless of WHERE conditions that
would exclude the row.
With a good index on the filter columns, "rows scanned" and "rows matched" are almost the same set, so you lock roughly what you asked for. Without one, the scan is the whole table (or a large part of it), and every scanned row is locked with an exclusive lock until the transaction commits.
Under the default REPEATABLE READ level, InnoDB also uses next-key locks, which lock the gaps before each
record as well, to prevent phantoms. That is why the lock mode shows X rather than X,REC_NOT_GAP. So
even inserts of new deliveries were blocked while a worker held its transaction open.
Why LIMIT 1 did not help
LIMIT 1 stops the scan once one matching row is found. For a tenant whose first pending delivery was near
the start of the table, few rows were locked. For a tenant whose pending deliveries were all recent, the
scan went through almost the whole table first. Workers for "late" tenants locked most of the table, and
everyone else waited. The lock pile-up depended on data distribution, which is why it appeared suddenly
when the backlog grew.
Why more workers made it worse
With 8 workers, the transactions were short enough that waits mostly resolved. With 16, the number of
overlapping transactions doubled, lock waits chained, and the 50 second innodb_lock_wait_timeout began
to expire. Each timeout rolled back a delivery that had to be retried later.
Environment
| Item | Value |
|---|---|
| Database | MySQL 8.0.39, InnoDB, REPEATABLE READ |
| Table | webhook_deliveries, 200k to 2M rows depending on backlog |
| Indexes | primary key on id only |
| Workers | 16, one transaction per delivery, webhook call inside the transaction (up to 10 s) |
That last row is a second problem. The webhook HTTP call happened inside the transaction, so locks were held for up to ten seconds per delivery. We fixed both.
1. Index that matches the claim query
ALTER TABLE webhook_deliveries
ADD INDEX idx_claim (tenant_id, status, id),
ALGORITHM=INPLACE, LOCK=NONE;
Equality columns first (tenant_id, status), then the sort column (id), so MySQL can jump straight to
the first pending row for a tenant in id order. New plan:
| 1 | SIMPLE | webhook_deliveries | ref | idx_claim | idx_claim | 1 | 100.00 | Using where; Using index |
And the lock set for the same claim:
| webhook_deliveries | NULL | TABLE | IX | GRANTED | 1 |
| webhook_deliveries | idx_claim | RECORD | X | GRANTED | 1 |
| webhook_deliveries | PRIMARY | RECORD | X,REC_NOT_GAP | GRANTED | 1 |
| webhook_deliveries | idx_claim | RECORD | X,GAP | GRANTED | 1 |
Four locks instead of 214,388: the matching secondary index entry, the row itself, and a gap lock next to it.
2. Skip rows other workers have claimed
Even with the index, two workers for the same tenant would still queue on the same first row. MySQL
8.0 supports SKIP LOCKED, which skips rows that another transaction has locked instead of waiting:
SELECT id, url, payload FROM webhook_deliveries
WHERE tenant_id = ? AND status = 'pending'
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED;
This is the standard pattern for job queues in a relational table. Worker two gets the second pending row instead of waiting for worker one.
3. Do not hold the lock during the HTTP call
Claim, then commit, then send:
START TRANSACTION;
SELECT id FROM webhook_deliveries WHERE tenant_id = ? AND status = 'pending'
ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
UPDATE webhook_deliveries SET status = 'sending', claimed_at = NOW(), claimed_by = ? WHERE id = ?;
COMMIT;
-- send webhook (no transaction open)
UPDATE webhook_deliveries SET status = 'sent', sent_at = NOW() WHERE id = ? AND claimed_by = ?;
A sweeper resets sending rows older than five minutes to pending, for workers that crashed mid-send.
Receivers already deduplicate by delivery ID, so an occasional duplicate after a crash is acceptable.
4. Consider READ COMMITTED for queue tables
Under READ COMMITTED, InnoDB does not take gap locks for searches and index scans, and for UPDATE and
DELETE it releases locks on non-matching rows after evaluating the WHERE. For this workload we set the
level per session in the worker connection:
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
It is not a replacement for the index, but it narrows the lock footprint further and removes the gap locks that were blocking inserts.
1. Lock count per claim. A test runs the claim query in one connection and counts locks from another:
SELECT count(*) FROM performance_schema.data_locks
WHERE object_name = 'webhook_deliveries' AND lock_type = 'RECORD';
Before: equal to the number of rows scanned (214,388 in the incident snapshot). After: 2 or 3, regardless
of table size. We assert < 10 in the test with a table of 100,000 rows.
2. Concurrency test. Sixteen workers against a table with 50,000 pending deliveries across 40 tenants:
| Version | Throughput | Lock wait timeouts |
|---|---|---|
| Original | 31 deliveries/s | 212 in 10 minutes |
| Index only | 410 deliveries/s | 0 |
| Index + SKIP LOCKED + claim/commit/send | 1,480 deliveries/s | 0 |
3. Production. The backlog of 1.9 million deliveries cleared in under three hours. Lock wait timeouts in the application log dropped to zero and have stayed there.
4. Ongoing check. A monitoring query alerts when any transaction holds more than 10,000 record locks,
using information_schema.innodb_trx.trx_rows_locked. That catches the same class of problem in other
tables, which it did once since, for a cleanup job deleting by an unindexed date column.
5. Security implications. None directly, but the lock pile-up was effectively a denial of service that
any tenant with a large backlog could trigger for every other tenant. Per-tenant isolation in a shared
table depends on indexes as much as on WHERE clauses.
Takeaways
- InnoDB locking reads lock every index record they scan, not just the rows they return.
- An index matching the filter and sort keeps the scanned set, and therefore the locked set, small.
- Use
FOR UPDATE SKIP LOCKEDfor job-claiming queries, and commit before doing slow work. performance_schema.data_locksshows exactly what a transaction holds. Check it, do not assume.
References: MySQL locks set by different SQL statements, MySQL InnoDB locking, performance_schema.data_locks, Locking read concurrency with NOWAIT and SKIP LOCKED.
Add a label
Embed this post
<iframe src="https://hibug.me/select-for-update-without-index-locks-table" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I started as an application developer and drifted toward the database because that is where our incidents kept ending up. For the last eight years I have looked after PostgreSQL and MySQL clusters for e-commerce and SaaS teams, from schema reviews to late-night failovers. Relational databases are well documented, yet the same surprises keep catching good engineers: a NOT IN that returns nothing because of one NULL, an index silently skipped after a type conversion, a FOR UPDATE that locked far more than intended, a replica that disagreed with its primary after promotion. In each post I reproduce the problem on a small dataset, read the plan or lock output together with you, explain the rule behind it and show the fix with numbers before and after. Where engines differ, I run the same test on both and show the results side by side.
Related Stories
Integration tests passed on SQLite and the same code failed on MySQL in production
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.