SKIP LOCKED: Due Jobs, Empty Batch
The worker logged claimed=0 and went back to sleep. COUNT(*) on jobs where status = 'pending' AND run_at <= now() was 40. A session that started with BEGIN and SELECT … FOR UPDATE was still idle in transaction after an HTTP call that never returned. SKIP LOCKED does not mean "give me the next available work." It means "do not wait: omit every row that currently has a conflicting lock." If those rows are the whole due set, the batch is empty on purpose.
The job scheduler post treats FOR UPDATE SKIP LOCKED as the claim. This post is the clause: what it skips, why a full table can still return nothing, and why the row lock and the lease column are not the same hide.
WAIT, NOWAIT, SKIP LOCKED
Postgres takes a row lock when the statement says FOR UPDATE. What happens when another transaction already holds a conflicting lock on that row is a separate choice:
-- default: wait until the locker commits or rolls back
SELECT id FROM jobs
WHERE status = 'pending' AND run_at <= now()
ORDER BY run_at, id
LIMIT 10
FOR UPDATE;
-- if any chosen row cannot be locked immediately, error
SELECT id FROM jobs … FOR UPDATE NOWAIT;
-- if a row cannot be locked immediately, omit it and keep scanning
SELECT id FROM jobs … FOR UPDATE SKIP LOCKED;
WAIT (the default) is the convoy. Every worker’s scan starts at the same oldest due row. Worker A locks it. B and C block on that tuple, not on "the queue," even when later rows are free.
NOWAIT fails the whole statement the moment it hits a locked row. Retrying it on a busy head-of-line is a tight loop on the same tuple.
SKIP LOCKED walks the index in ORDER BY order and omits locked tuples. Scanning continues until this session has locked LIMIT rows, or until there are no more candidates. MySQL 8 has the same three shapes on InnoDB. The lock is held until this transaction ends, not until the statement ends.
The count and the claim disagree
Forty pending rows. One backend is idle in transaction holding FOR UPDATE on all forty — it selected them, then called a payment API, then hung. A second worker runs the claim:
UPDATE jobs
SET status = 'running',
locked_until = now() + interval '5 minutes',
attempts = attempts + 1
WHERE id IN (
SELECT id FROM jobs
WHERE status = 'pending' AND run_at <= now()
ORDER BY run_at, id
LIMIT 10
FOR UPDATE SKIP LOCKED
)
RETURNING *;
The subquery’s WHERE matches forty rows. All forty are locked. SKIP LOCKED omits them. LIMIT 10 never fills. RETURNING is empty.
COUNT(*) of the same WHERE does not take row locks and does not skip. It reports 40. The dashboard is counting rows this worker is forbidden to wait for.
SKIP LOCKED plus LIMIT 10 is not "look at ten rows and drop the locked ones." It keeps walking until it has locked ten, or the matching set is exhausted. Ten locked rows and ninety unlocked ones still yield a full batch. Forty locked and zero unlocked yield this incident. An empty batch means every remaining matching row is locked right now.
The lock outlives the statement when:
- Work happens inside the transaction.
SELECT … FOR UPDATE SKIP LOCKED, then HTTP, thenCOMMIT. The row lock is the claim. The pool loses a backend for every in-flight job, and every other worker skips those rows until commit or rollback. - A forgotten
BEGIN. An exception path that logs and returns withoutROLLBACK.idle_in_transaction_session_timeoutdefaults to 0 in Postgres — disabled. The locker lives until someone kills the backend. - A process that died without closing the TCP connection. The server notices after keepalive or the proxy idle timeout. Until then
SKIP LOCKEDkeeps omitting the rows. A clean SIGTERM that closes the socket is a rollback. A hung client behind a load balancer is not.
The lock and the lease are different hides
locked_until is not what SKIP LOCKED looks at. Two mechanisms hide a job, and they fail independently.
The row lock lasts until COMMIT or ROLLBACK. Only SKIP LOCKED (or a waiter) sees it. After commit the lock is gone. If you did not also flip status / locked_until, the next claim takes the same row again.
The lease column lasts until a timestamp. Other workers miss the row because WHERE status = 'pending' no longer matches. SKIP LOCKED is then irrelevant: there is nothing matching to skip. A crash after the claim commits is not released by rolling back a lock you no longer hold. It is released by a sweeper that treats an expired lease as pending again.
Mixing them is the usual bug. Claim with SKIP LOCKED, commit, never write locked_until: other workers reclaim the job the moment the lock drops. Or write status = 'running' and hold the transaction open for the HTTP: you serialize the job and hold a pool connection, and a crash before commit rolls back the status change. The payment API does not roll back.
Keep the hides in their lanes. Run the UPDATE … RETURNING above as a short transaction: lock, write the lease, COMMIT. Then the HTTP. Then a second transaction marks done, or pending with a backoff run_at. SKIP LOCKED only has to be right for the milliseconds of the claim. The lease covers the minutes of the work. Expired leases re-enter pending; that is at-least-once, so the handler still has to tolerate a retry. A lock is not a fencing token. Two workers who both observe an expired lease can both run. That is the sweeper, not a SKIP LOCKED failure.
Fairness, joins, and isolation
ORDER BY run_at, id looks like FIFO. SKIP LOCKED is allowed to jump the line: a locked oldest row is omitted and the next unlocked row is claimed. An old job sits untouched while newer jobs drain, for as long as its locker is alive. If you needed "nobody jumps the head," you wanted WAIT, and you accepted the convoy.
Joins lock every table in the FROM list unless you name one:
SELECT j.id
FROM jobs j
JOIN customers c ON c.id = j.customer_id
WHERE j.status = 'pending' AND j.run_at <= now()
ORDER BY j.run_at, j.id
LIMIT 10
FOR UPDATE OF j SKIP LOCKED;
Without OF j, Postgres also tries to lock matching customers rows. A support session that opened the customer and parked the transaction will skip every job for that tenant.
Isolation: Postgres defaults to READ COMMITTED. Each statement sees the latest committed versions. In REPEATABLE READ or SERIALIZABLE you scan a snapshot — later commits are invisible, and locked rows still in the snapshot are skipped. The docs call this an inconsistent view. A queue claim belongs in READ COMMITTED.
lock_timeout does not substitute. It caps how long WAIT will block, then errors. Setting it on a claim query turns a convoy into a retry loop.
When SKIP LOCKED is the wrong clause
You need this exact row. Serializing updates to one order or one balance: FOR UPDATE without skip. The second session should wait, then see the committed version. Skipping would mean you did not update the balance, or you picked a different order because the one in the URL was locked.
The transaction already did the work. Side effects that must commit or roll back with the claim belong in the same transaction as the lock. Then you do not want a lease, and you do not want to hold that transaction across HTTP. Do the external call after commit, or write an outbox row next to the claim.
You are measuring queue depth. COUNT(*) is not claimable depth. Treat claimed=0 while pending > 0 as its own signal: look for idle in transaction in pg_stat_activity, not for missing workers.
| Need | Clause |
|---|---|
| Many workers, disjoint batches, short claim txn | FOR UPDATE SKIP LOCKED, then lease + commit |
| This row, no substitute | FOR UPDATE (wait) |
| Fail if this row is busy | FOR UPDATE NOWAIT |
| Hide work across process death | Lease column + sweeper, not a row lock |
| Depth of claimable work | Not COUNT(*) of pending |
The worker that logged claimed=0 did not have a bug in LIMIT. It asked Postgres not to wait, the due rows were all locked, and the statement obeyed. End the forgotten transaction — or stop holding the lock across the HTTP call, write a lease, and commit. The forty jobs were never gone. They were skipped.
Keep reading
FOR UPDATE: No Row, No Lock
SELECT … FOR UPDATE locks tuples that exist. An empty scan is not a lock on the key. Two sessions both insert; a unique violation is the lucky case.
OFFSET Pagination: Page Two Skipped a Row
OFFSET counts rows from a moving table. An insert or delete between pages skips or duplicates. Keyset on a unique sort key is the stable window.
Transactional Inbox: The Handler That Ran Twice
Outbox makes the event exist. It does not make the consumer run once. Record the message id in the same transaction as the side effect, or a retry will do the work again.
Two-Phase Commit: Why Distributed Transactions Stall
Two-phase commit makes two resources atomic until the coordinator dies. Here is why it blocks, why 3PC did not save it, and what you run instead.
Write Skew: The Anomaly Snapshot Isolation Does Not Catch
Two transactions each read what the other writes, both commit, and an invariant dies. Snapshot isolation allows write skew — here is how to close the hole.
Designing a Shopping Cart: Price Snapshots, Merge, and No Inventory Hold
A cart is a per-user document, not a reservation. What to store on the line, how to merge an anonymous cart at login, and when the price is allowed to change.
Newsletter
New posts, straight to your inbox
One email when a new post goes up. Double opt-in, unsubscribe anytime. Not a daily digest.
Comments
- No comments yet. Be the first.