GROW WITH ATARAXYBuild skills. Get real experience.Explore internships and education support.

MVPs & SaaS Projects

PostgreSQL Work Queues: Claim Rows with SKIP LOCKED and Recover Abandoned Jobs

Design a PostgreSQL-backed work queue with bounded claims, SKIP LOCKED, worker leases, and explicit recovery for uncertain side effects.

LET’S BUILD SOMETHING USEFUL

Have a project in mind?

Talk to ATARAXY DEVELOPERS (SMC-PRIVATE) LIMITED about your website, app, or custom software.

Two background workers inspect the same pending export job at nearly the same time. Without a coordinated claim, both may start building the file. Adding a database row lock can prevent the immediate collision, but it does not answer what happens when a worker crashes after claiming the job or finishes an external action before recording success. A useful queue design must cover the full lifecycle, not only the first select statement.

PostgreSQL can support a modest application work queue when its operational tradeoffs fit the product. Consider a hypothetical SaaS that generates account reports from queued requests. The design needs bounded claims, visible ownership, recovery after interrupted work, and protection against duplicate external effects. SKIP LOCKED helps workers avoid waiting on each other’s selected rows, while the application supplies the larger processing contract.

Understand what SKIP LOCKED does and does not promise

The PostgreSQL SELECT documentation explains that SKIP LOCKED skips selected rows whose row locks cannot be acquired immediately. It produces an inconsistent view unsuitable for general-purpose reads, but can help multiple consumers of a queue-like table. It applies to row locks; it does not remove all possible waiting, including ordinary table-lock behavior. Use it for choosing available work, not for calculating an authoritative queue total.

Keep reporting queries separate from claim queries. A worker receiving no rows means it found no immediately claimable rows under its conditions, not necessarily that the queue is empty. Another worker may hold locks, jobs may be scheduled for later, or eligibility rules may exclude them. Operational dashboards should distinguish pending, leased, delayed, failed, and completed work using definitions that match the application’s state model.

Define a job record that supports recovery

A practical job record can include an identifier, tenant, task type, payload reference, status, available time, attempt count, lease token, lease expiry, and last outcome. Use only the fields the workflow needs, and keep sensitive payloads appropriately scoped. Version the task input when worker code may change while older jobs remain queued. A job should identify the work requested without depending on mutable context that can silently change its meaning.

For the report example, store the report parameters and authorized account scope explicitly. Decide whether the report uses a snapshot or the data available when processing begins. Display that choice to the requesting user where it affects interpretation. An AI-generated narrative attached to the report should reference the same dataset version. Otherwise, the table and summary may describe different information even though they were produced by the same nominal job.

Claim a small batch inside one transaction

Select eligible pending rows in a deterministic order with a bounded limit and the appropriate row-locking clause. In the same transaction, update the selected jobs to record their lease, attempt, and ownership token, then return the claimed work and commit. A separate unlocked selection followed later by an update leaves a race between workers. The claim must be one coordinated database operation, whether implemented as a carefully scoped transaction or a suitable statement.

Use an ordering that includes a unique tie-breaker, such as availability time followed by job ID. PostgreSQL recommends a unique order when using LIMIT to obtain a predictable subset. Recognize that skipping locks can still let later work proceed first; this is not a strict global FIFO guarantee. Keep claim batches modest so one worker does not reserve more work than it can start before leases expire. Measure query behavior with representative queue volume and indexes.

Release database locks before doing slow external work

After committing the claim, perform report generation outside the claim transaction. Do not keep database row locks open while waiting for a remote service, rendering a large file, or asking an AI model to generate text. The durable lease represents the worker’s temporary ownership after the transaction ends. This reduces the chance that slow processing monopolizes database connections or holds locks far longer than intended.

Choose lease duration from observed task behavior and the recovery objective. If long-running work renews its lease, make renewal conditional on the current token. Keep renewals bounded and observable rather than letting a stuck process extend ownership forever. The worker should know when it has lost ownership and stop making further state changes where possible. Cancellation of local computation is helpful, but it does not automatically undo an external request that was already accepted.

Fence completion against a newer owner

When a worker records success or failure, require both the job ID and its current lease token to match. If the update affects no row, the worker must treat its ownership as lost rather than overwriting a newer attempt. A recovery process can return expired jobs to an eligible state or assign a new token according to the queue policy. The token makes old completion messages distinguishable from current work.

This database check does not by itself fence an external service. A stale worker might still finish uploading a file or sending a message after a replacement worker starts. Use a stable business idempotency key where the external system supports it, or design an explicit reconciliation process. Separate attempt identifiers from the logical operation identifier: attempts may change, while the intended customer-visible action should remain recognizable as the same request.

Make retry outcomes and exhausted work visible

Classify failures into retryable conditions, invalid input, and uncertain external outcomes. Apply an appropriate delay and attempt policy instead of immediately returning every failure to the front of the queue. Preserve useful diagnostic context without copying secrets or full private payloads into error messages. A permanently invalid report request should be explained to the user or operator rather than consuming worker capacity indefinitely.

For an uncertain upload outcome, inspect the destination using the logical operation identity before creating another artifact. If the artifact already exists and matches the expected request, reconcile the job record. If the outcome cannot be established, surface that uncertainty for the appropriate recovery path. Provide an operator view for exhausted jobs with clear actions such as inspect, correct input, retry, or cancel. Each action should preserve history so repeated incidents can be understood.

Test interruption points and monitor queue health

Exercise the workflow with two workers claiming simultaneously, a worker stopping before commit, a crash after commit, lease expiry during processing, and a late completion from an old token. Add a scenario where the external action succeeds but the database success update fails. These tests reveal whether the system has designed recovery or merely assumes the happy path will eventually repeat safely.

Monitor the age of the oldest eligible job, expired leases, retry volume, execution duration, and exhausted work. Review tenant fairness if one account can submit enough jobs to crowd out others. Clean up completed records according to a defined retention policy while keeping the evidence needed for support and reconciliation. A database-backed queue remains a product subsystem with operational responsibilities; moving selection into SQL does not eliminate the need to observe and manage its lifecycle.

Conclusion

SKIP LOCKED is a useful claim primitive within a broader queue design. Pair short transactions with bounded batches, durable leases, conditional completion, and explicit recovery. Treat external effects as potentially repeated or uncertain and reconcile them by logical operation identity. The goal is not merely to keep workers busy, but to make every requested job’s ownership, progress, and final outcome understandable.

LET’S BUILD SOMETHING USEFUL

Turn what you’ve learned into your next project.

Talk to ATARAXY DEVELOPERS (SMC-PRIVATE) LIMITED about your website, app, or custom software.

ATARAXY DEVELOPERS (SMC-PRIVATE) LIMITED — Turning Digital Visions Into Reality

ATARAXY DEVELOPERS (SMC-PRIVATE) LIMITED builds websites, mobile apps and custom software for businesses in the US, Pakistan and beyond.

Join Our Newsletter

Get insights on software, digital products and automation from our development team.

You have been successfully Subscribed! Ops! Something went wrong, please try again.