Header Ad Placement

PostgreSQL SKIP LOCKED: A Claimed Row Is Not a Completed Job

DATABASE QUEUES

Skipping a busy row solves one contention problem. It does not define job completion, fair scheduling or recovery after an external action.

By Hossam

The useful promise is narrower than exactly-once work

A queue table can give several workers the same tempting first row. PostgreSQL offers FOR UPDATE SKIP LOCKED so a locking query can bypass selected rows that it cannot lock immediately. Its SELECT reference explicitly identifies multiple consumers of a queue-like table as a use case.

The important boundary is the row lock, not the business task named in the row. Selecting an available record, recording ownership, running an action and recording completion are distinct steps. A design has to say which steps share a database transaction and what happens between them.

This is a documentation-based design review. The job identifiers and worker schedule below are fictional, not captured SQL output. No PostgreSQL server, driver, queue package, concurrency benchmark or worker-crash experiment was run for this article.

Documentation: SELECT and its locking clause, Explicit locking.

SKIP LOCKED exchanges waiting for omission

With NOWAIT, a selected row that cannot be locked immediately causes an error. With SKIP LOCKED, such a row is skipped. PostgreSQL warns that the resulting view is inconsistent and unsuitable for general-purpose work. That is a deliberate tradeoff for a consumer seeking work it can claim now.

A query returning no job therefore does not establish that the queue contains no matching records. Matching rows may exist but be locked by other transactions. The worker needs an explicit idle policy, such as waiting before polling again, rather than treating one empty selection as proof that all work is complete.

The option applies to row-level locks. The required ROW SHARE table-level lock is still acquired normally. Calling the query universally nonblocking would be wrong: skipping conflicting row locks does not remove table-lock waits, other statements in the transaction or unrelated database errors.

Documentation: SELECT and its locking clause, Explicit locking.

A fictional two-worker schedule separates selection from completion

Assume a simple table with unique job identifiers 101 and 102, both marked pending. Worker A starts a transaction and selects one pending row ordered by identifier, using FOR UPDATE SKIP LOCKED. In this invented schedule it obtains 101 and keeps its transaction open.

Worker B then performs the same locking selection in another transaction. While A holds the conflicting row lock, B can skip 101 and obtain 102. This illustrates the documented selection rule. It does not show that either job action ran, that a worker will finish, or that the queue was processed in order.

If A rolls back without committing a state change, its lock is released and its database changes are discarded. A later consumer can encounter 101 again. That is useful recovery for uncommitted database work, but any action already performed outside the database needs its own analysis.

Documentation: SELECT and its locking clause, Explicit locking, Transactions tutorial.

An autocommit selection is not a lasting reservation

PostgreSQL documents row-level locks as lasting until transaction end, with savepoint rollback also able to release locks acquired within the rolled-back portion. A worker cannot assume the lock remains after COMMIT just because it still holds a copy of the returned row in application memory.

Without an explicit transaction block, PostgreSQL treats each statement as a transaction of its own. A successful standalone locking SELECT therefore reaches its transaction end when that statement completes. If no committed claim changes the eligibility condition, the earlier lock is not protection for later work.

Client libraries can open transaction blocks automatically. Inspect the actual driver and connection configuration instead of diagnosing ownership from SQL text alone. The practical question is when this connection commits or rolls back, not whether the application calls a method whose name sounds transactional.

Documentation: Explicit locking, Transactions tutorial.

Choose between holding a lock and committing a claim

One design keeps the transaction open while it performs database-local work, updates job state and commits. Other cooperating lockers cannot take the same row during that interval. The cost is a transaction and its locks held for the duration of the work. PostgreSQL advises against keeping transactions open for long periods.

Another design selects an eligible row, changes its state to running in the same transaction, then commits before doing long work. Future consumers filter for pending rows and should no longer treat that committed row as eligible. UPDATE RETURNING can return values from rows actually updated, avoiding a separate read to discover the claimed payload.

That second arrangement is an application protocol, not an automatic lease supplied by SKIP LOCKED. A crash after the claim commits can leave the job running indefinitely unless the design includes recovery. Ownership identifiers, expiry decisions and conditional completion updates are design choices that must be tested together; adding a timestamp alone is not a proof.

Documentation: SELECT and its locking clause, Explicit locking, UPDATE and RETURNING.

Committing a claim creates a recovery obligation

Consider a worker that committed a running state and then disappeared. A recovery process may decide to make the job eligible again. The old worker might merely be slow rather than dead, so it can resume after a replacement starts. A durable claim must therefore define how stale ownership is detected and rejected.

For database completion, one possible requirement is that the final update match both the job identifier and the ownership value assigned to that attempt. The worker must check whether it actually updated a row. PostgreSQL treats an UPDATE affecting zero rows as a successful statement, not an error, so ignoring the result can conceal a lost claim.

These are proposed acceptance requirements, not a ready-made production queue implementation. The timeout policy, clock assumptions, retry budget and downstream support determine what is safe. A replacement worker starting successfully does not by itself prove that the previous attempt can no longer cause an effect.

Documentation: UPDATE and RETURNING.

A database rollback cannot unsend an external action

Suppose a job means sending a notification through another service. The service accepts it, but the worker loses its connection before it can record completion. A later retry may send the notification again. The row lock coordinates database access; it is not a transaction spanning that independent service.

Reversing the order has a different failure window. If the worker marks the job complete and commits before requesting the external action, a crash between those steps can leave a completed row with no action. This is a reasoned failure analysis, not a claim that PostgreSQL provides either cross-service behavior.

The application needs evidence about the external effect: for example, a destination-supported deduplication key and a way to reconcile an uncertain result. Those mechanisms have their own scope and retention rules. Neither a successful locking SELECT nor a database completion flag is sufficient evidence of exactly-once execution outside the database.

Documentation: Explicit locking, Transactions tutorial.

Ordering and batching do not establish fairness

ORDER BY with a unique tie-breaker makes the requested selection order explicit. Without ORDER BY, PostgreSQL does not promise which subset LIMIT will return. But an earlier candidate can still be skipped because it is locked, so an ordered claim query is not a guarantee that jobs start or finish in first-in, first-out order.

The SELECT reference also warns that ORDER BY and a locking clause at Read Committed can return rows out of order if ordering values change while the query waits for locks. Its suggested subquery workaround can lock many more rows. It should not be copied into a queue path without reviewing the change in lock scope.

LIMIT stops locking once enough rows have been returned to satisfy the limit, while rows skipped by OFFSET still get locked. Large batches also keep more work attached to an attempt. Batch size, polling delay and treatment of repeatedly bypassed jobs need workload-specific tests rather than an assumption that more workers always improve completion time.

Documentation: SELECT and its locking clause, Explicit locking.

Isolation and retry handling remain part of the worker

Read Committed uses a fresh snapshot for each command. For concurrent updates, PostgreSQL describes re-evaluating the search condition against the updated row. Keep eligibility in the locking or update protocol, rather than relying on a separate earlier read that said the job was pending.

Repeatable Read and Serializable can produce serialization failures. The locking documentation says these levels can reject locking a row changed since the transaction started. SKIP LOCKED is not permission to ignore a serialization error merely because currently locked rows can be skipped.

PostgreSQL identifies serialization failures with SQLSTATE 40001 and says to retry the complete transaction, including the decisions that produced its SQL and values. Deadlock failures may also need retries. Blindly retrying only the last statement with stale decisions is not equivalent, and retrying database work does not settle whether an earlier external action happened.

Documentation: Explicit locking, Transaction isolation, Serialization failure handling.

Test ownership, final state and uncertain outcomes separately

A useful isolated test plan starts with overlapping worker transactions. Check that they claim different eligible rows while locks are held, that rollback makes uncommitted work eligible again, and that a committed running state remains excluded from the normal pending selection after the row lock ends.

Then test the boundaries the SQL cannot explain alone: termination after claim commit, delayed workers resuming after reassignment, completion updates affecting zero rows, and a missing response after an external service accepted an action. Count actual effects at that service, not only completed rows in the queue table.

Monitor pending, running, expired and repeatedly retried work according to the chosen protocol. A plain SELECT is not blocked by a row-level lock, so a pending count can include rows currently held by workers if they have not committed a state change. Document what each metric measures before treating an empty claim result or a green dashboard as a drained queue.

Documentation: SELECT and its locking clause, Explicit locking, Serialization failure handling, UPDATE and RETURNING.

Related reading

The Redis transaction boundaries guide separates isolated command execution from rollback and durability. PostgreSQL has different transaction semantics; the comparison is about identifying the promise, not treating the systems as interchangeable. The idempotency-key lifetime guide examines duplicate actions and uncertain external outcomes.

Sources and scope

Documentation checked November 24, 2026 using the official PostgreSQL current-documentation pages. These are primary SQL and concurrency references, not independent performance measurements. The worker schedule, recovery requirements and external-action failure analysis are illustrative engineering reasoning. No server experiment, process termination, queue implementation, production throughput test or cross-service transaction was executed or verified.


 

Comments

Docker Build Contexts: What .dockerignore Excludes and COPY Does Not

CONTAINER BUILD INPUTS The context decides which files a build can access. A copy instruction decides what one step puts into a stage. Review those boundaries separately. By Hossam Start with the input boundary, not the final image A Dockerfile that copies only application files can still have a wider build context than its author intended. The context is the set of files available to the build, while COPY describes one operation using a source. A selective copy is useful, but it is not the same control as excluding an input from the context. Docker documents .dockerignore as a way to remove matching files and directories from the context before it is sent to the builder. That makes context selection and ignore rules worth reviewing even when the final runtime image appears small. A final-image inspection answers a different question from a build-input review. This guide analyzes Docker documentation. Its example repository layout and review steps are illustrative, not captured b...

Editorial Governance & Pages