Skip to content

Postgres SKIP LOCKED: empty is not drained

Show how a correct claim still produces a false batch-completion decision, then define admission and inventory evidence.

Dopstack Engineering

· 9 min read

Original conceptual illustration: A searchlight passes a visibly locked job while an unfinished inventory remains; midnight blue and lime.

Quick answer

An empty `FOR UPDATE SKIP LOCKED` result means this statement could not claim a qualifying row. It does not prove that every job finished. A row may be locked by another transaction, committed as running, scheduled for later, or outside the worker's filter. Use a separate inventory query and an explicit completion rule before declaring a queue drained.

An empty FOR UPDATE SKIP LOCKED result means this statement could not claim a qualifying row. It does not prove that every job finished. A row may be locked by another transaction, committed as running, scheduled for later, or outside the worker's filter. Use a separate inventory query and an explicit completion rule before declaring a queue drained. [1][2][3]

How can a worker see no job while work remains?#

Scenario: a fictional document service has two accepted exports, one queued and one already done. During maintenance, an operator stops new submissions and starts two workers. The second worker reports no claim, so the maintenance script announces that exports are drained. The first worker is still holding a transaction on one export. If it rolls back, a queued export remains after the announcement. The bug is in the completion decision, even if the claim query correctly prevents simultaneous claims.

Separate three observations: a worker obtained no row, the database contains no eligible queued row, and the business has no unfinished accepted export. Only the first follows directly from an empty claim. Treating those observations as interchangeable makes a maintenance procedure depend on transaction timing.

PostgreSQL documents SKIP LOCKED as a queue-consumer tool that skips unavailable row locks and produces an inconsistent view. Ordinary readers can still see a row held by a row-level lock. That gives us a useful diagnostic: compare what a locking claim can obtain with what an ordinary inventory query can see. Neither query becomes a universal completion proof by itself. [1][2]

This article targets PostgreSQL's Read Committed behavior. Higher isolation levels have their own retry requirements. The example deliberately keeps two database sessions open to expose the observation boundary; a production worker should not hold this transaction while performing a slow remote export. [2][3]

Reproduce the misleading empty result in two sessions#

Use a disposable database. The small table represents accepted exports, with queued, running, and done states. There is no external storage, delivery protocol, or production migration in this fixture. Each statement below is intentionally small enough to inspect by hand.

sql
CREATE TABLE drain_demo (
  id integer PRIMARY KEY,
  state text NOT NULL CHECK (state IN ('queued', 'running', 'done')),
  run_at timestamptz NOT NULL,
  tenant_id text NOT NULL
);
INSERT INTO drain_demo VALUES
  (1, 'queued', '2026-11-01T00:00:00Z', 'alpha'),
  (2, 'done',   '2026-11-01T00:00:00Z', 'alpha');

Scenario observation: In session A, begin a transaction and lock the queued row. Leave the transaction open. The selected ID should be 1. Nothing has changed the committed business state yet; this session merely owns a row lock.

sql
-- Session A: leave this transaction open.
BEGIN;
SELECT id FROM drain_demo
WHERE state = 'queued'
ORDER BY run_at, id
LIMIT 1
FOR UPDATE SKIP LOCKED;

In session B, run the same claim as a separate connection. It should return no rows while session A retains its lock. Then run the ordinary inventory query. The expected count of queued rows is still one, because a row lock does not hide the committed row from an ordinary reader. Those are compatible answers to different questions. [1][2]

sql
-- Session B
SELECT id FROM drain_demo
WHERE state = 'queued'
ORDER BY run_at, id
LIMIT 1
FOR UPDATE SKIP LOCKED;

SELECT state, count(*)
FROM drain_demo
GROUP BY state
ORDER BY state;

Scenario observation: Now roll back session A. Session B can claim ID 1 on a later statement. A controller that terminated the whole batch after session B's first empty result would have stranded work. This is the first acceptance test for a drain procedure: an empty claim during another session's lock must not become a completion event.

Do not use a sleep as the definition of correctness. Coordinate the test by confirming that session A has acquired the row before session B claims it, then explicitly release A. A test that happens to pass because the machine ran one worker slowly has not established the intended interleaving.

What changes when the claim commits as running?#

Most workers need a short claim transaction, followed by processing outside it. In that arrangement, the committed running state keeps the job out of subsequent queued claims after the lock is released. PostgreSQL's UPDATE ... RETURNING returns values from rows actually updated; it is a convenient way to obtain the claimed identity. Put the locking clause inside the candidate query. [1][5]

sql
WITH candidate AS (
  SELECT id FROM drain_demo
  WHERE state = 'queued' AND run_at <= statement_timestamp()
  ORDER BY run_at, id
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
UPDATE drain_demo AS job
SET state = 'running'
FROM candidate
WHERE job.id = candidate.id
RETURNING job.id, job.state;

After this statement commits, another queued claim can return nothing even when no locks are contested. The inventory now says running = 1. Waiting for locks would not repair the completion decision. The worker has moved work into a different state, and the drain controller has failed to count that state.

Name the owner of each state transition. Who marks a running export done? What happens if the process dies after the claim commits? How is an interrupted export reconciled? The fixture leaves recovery implementation out, but a release procedure cannot leave the answers out. An indefinitely running row is unfinished work, not permission to ignore it.

In this claim statement, the candidate query inside WITH reads rows and the outer UPDATE changes their state. PostgreSQL also supports data-modifying statements inside WITH, which execute to completion even when their output is not consumed. Do not assume that abandoning result iteration undoes a modifying statement. Preserve the returned identity and the committed transition outcome; a connection failure around commit still needs a durable-state reread. [4][5]

Which completion rule fits the maintenance task?#

Before writing the drain query, define the set you intend to finish. For a schema maintenance window, that might be every export accepted before a recorded cutoff. For a recurring worker, it might be only currently due work for one tenant. The latter is a useful work-selection rule, but it is a weaker completion rule.

ObservationWhat it establishesWhat still needs evidence
Empty locking claimNo row obtained by this statementLocked, running, delayed or excluded work
No queued rows in a snapshotNo visible rows in that state and scopeRunning work and future submissions
No unfinished rows before cutoffSnapshot satisfies the defined inventory ruleProducer barrier and external delivery contract
Every accepted export has a final receiptApplication completion rule is metWhether that receipt covers the maintenance requirement
These are different completion questions. The classification is a proposed operational method built on PostgreSQL's locking and snapshot rules. [1][2][3]

For our fictional service, choose a concrete rule: stop accepting exports into this maintenance batch, identify every accepted export at or before its cutoff, and wait until none of those exports is queued or running. Keep the cutoff identity in the maintenance record. The goal is to avoid chasing a moving population while someone continues adding jobs.

A timestamp alone is not a producer barrier. A transaction might have captured an earlier application timestamp and commit after the controller's inventory query. Coordinate admission with the producer's actual commit protocol, or create an explicit batch membership record under the same database rules used to accept work. Record what the barrier guarantees and which producers participate.

Do not infer a cluster-wide barrier from one API instance returning maintenance mode. A scheduler, retry service, operator command, or older deployment may still insert exports. Identify the accepted-work producers before closing admission. If that inventory is unknown, report that drain completion cannot yet be established.

How do filters create a false drain signal?#

Suppose the worker selects tenant_id = 'alpha', while the maintenance window covers both alpha and beta. An empty alpha claim says nothing about beta. A due-time filter creates a similar mismatch: a job accepted yesterday but scheduled for tomorrow may remain unfinished even when there is no work due now.

Write the worker scope and the maintenance scope beside each other. Include tenant, queue, batch ID, scheduled time, status, and any retry or failure states. A useful review exercise is to construct one accepted row that the worker excludes and ask whether the maintenance operation still requires it to finish. If yes, the worker query cannot own the completion decision.

Retryable failures require particular care. If a controller counts only queued and running states, moving a job into failed can make the count reach zero without producing an export. Decide whether failed work blocks maintenance, is explicitly cancelled, or is transferred into a separate recovery batch. That decision belongs in the run record, with an owner and the affected job IDs.

The same distinction matters for empty result handling in code. Return a status such as NO_CLAIM from the worker. Reserve BATCH_COMPLETE for the coordinator that has checked the admission barrier and full completion rule. Different names make it harder for a later refactor to turn a local observation into a global guarantee.

Will retries or a larger index prove completion?#

A brief polling delay can reduce a worker's idle loop and allow contested rows to become claimable. It cannot prove that no unfinished work exists. Ten empty polls may all occur while the same row is locked, while a job is running, or while an excluded retry waits for tomorrow. Set polling policy for responsiveness and load; set completion policy from durable inventory.

A partial index can help the claim find queued work, but its predicate must match the query's conditions in a way the planner recognizes. It does not change the meaning of an empty result. Inspect plans against realistic queue sizes and state distributions instead of promising that a particular index makes drain detection correct. [6]

sql
CREATE INDEX drain_demo_queued_due
ON drain_demo (run_at, id)
WHERE state = 'queued';

Remember that SKIP LOCKED applies to row locks. A claim can still wait for the required table-level lock. A blocked schema operation and an empty claim are different symptoms; preserve query timeouts and database diagnostics so operators can tell them apart. Do not add a blanket no-wait claim to a queue design simply because its SQL contains these two words. [1][2]

There is also no strict processing-order guarantee. A locked older row may be passed over while a newer row starts. If the export contract requires per-tenant sequencing, model that constraint explicitly rather than reading it into ORDER BY. For drain work, completion is about the accepted set reaching its final state, not workers finishing in the same order they selected candidates.

What should the verification record contain?#

Run the two-session lock case, the committed-running case, and an excluded-row case. Record the claim result and ordinary inventory for each. Then prove that the coordinator stays open until its own rule is met. Test a rollback, a worker crash after claim commit, and a producer that attempts to submit after the barrier.

For every test, preserve the database version, isolation level, exact predicates, expected job IDs and actual state transitions. The SQL above follows PostgreSQL 18 documentation. A disposable PostgreSQL execution can verify those particular statements and interleavings; it cannot establish your application's remote export guarantees or operational capacity. [1][3]

For production, track oldest unfinished batch member, running age, recovery count, failed members and admission-barrier state. A chart of successful claims alone misses the failure we started with. Alert on a batch whose completion evidence stops advancing, with links to its unresolved job IDs, rather than declaring success from a quiet worker.

Example verification: the article SQL was exercised in an isolated PostgreSQL 17.11 database with separate sessions. Checks covered a locked queued row, rollback, committed running work, tenant and future-time exclusions, partial-index creation and a table-lock timeout despite SKIP LOCKED. The versioned PostgreSQL documentation was reviewed; no production queue, producer barrier or remote export was tested.

Frequently asked questions#

Does an empty SKIP LOCKED query mean the table is empty?
No. Qualifying rows may be locked, and other rows may be excluded by the predicate. Use an ordinary inventory query to inspect committed state and a separate completion contract for the batch. [1][2]
Can a plain SELECT see a row another worker has locked?
Row-level locks do not prevent ordinary data querying. Under Read Committed, an ordinary SELECT reads its statement snapshot, which can include a queued row held by another transaction. [2][3]
Should a worker keep polling until it sees the queue empty?
Polling can keep the worker available, but repeated empty claims do not establish global completion. The coordinator must check the accepted set, running and failure states, and the producer barrier.
Does moving a claim into one UPDATE solve drain detection?
It can make ownership transitions explicit and return the updated identity. Once the claim commits as running, that job disappears from queued claims while remaining unfinished. Count it in the completion inventory. [5]

Technologies

  • PostgreSQL

Sources

  1. [1]
    SELECT, PostgreSQL

    Read 2026-11-06T08:03:31.820763+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: SKIP LOCKED skips unavailable row locks.

  2. [2]
    Explicit locking, PostgreSQL

    Read 2026-11-06T08:03:31.820881+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: Ordinary reads are not blocked by a row lock.

  3. [3]
    Transaction isolation, PostgreSQL

    Read 2026-11-06T08:03:31.821008+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: The baseline isolation is Read Committed.

  4. [4]
    WITH queries, PostgreSQL

    Read 2026-11-06T08:03:31.821141+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: A modifying WITH statement executes to completion.

  5. [5]
    UPDATE, PostgreSQL

    Read 2026-11-06T08:03:31.821298+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: RETURNING is based on updated rows.

  6. [6]
    Partial indexes, PostgreSQL

    Read 2026-11-06T08:03:31.821454+00:00; publication/update date not asserted; dated event specified in article where relevant. Supports: A partial index covers a predicate-defined subset.

Written by

Dopstack Engineering

Engineering team

The engineering team at Dopstack. Illustrative scenarios are composites written to explain a pattern, not accounts of client work.

All articles Website

Get new articles by email

Engineering notes on AI, cloud and SaaS. Occasional, never sold or shared.

Send me new Dopstack Insights articles by email. I can unsubscribe at any time. We’ll email you once to confirm. Privacy

Continue reading