Skip to content
sinc-LLMBook a 15-minute call

How to Claim AI Queue Jobs With PostgreSQL SKIP LOCKED

Claim PostgreSQL queue rows in short transactions, recover expired leases, and test that a stale worker cannot finish a reclaimed job.

On this page

By Mario Alexandre · November 29, 2026 · 25 min read

Use PostgreSQL FOR UPDATE SKIP LOCKED to let competing workers claim different eligible AI jobs. Select and update the queue row in one short transaction, commit, then call the model. If the queue can retry a stalled job, store a new claim version on every assignment and check that version when committing a result. Choose a different queue design if the work must execute in strict order or if you cannot safely reconcile repeated attempts at an external effect.

TL;DR. A queue claim has three separate proofs. The committed row shows who owns the current attempt. A guarded completion shows which attempt saved the result. A read at the external destination shows what, if anything, happened there. Test all three by letting a worker lose its lease and return after another worker has taken over.

Key decision facts

Decision Start here Test before relying on it
Claim from several workers Select an eligible row with a row lock, save the claim, and commit A second connection claims another row while the first stays locked
Recover after worker loss Give running rows a lease and increase the claim version on reassignment An older attempt updates zero rows once the job is reclaimed
Diagnose no available work Check queue age and state through a separate read A locked job appears in backlog even when a claimer skips it
Retry a result or tool call Resolve the operation at its own destination A lost response after commit leaves one durable result
Detect strict ordering requirements Name the ordering key and protect it across attempts A second job for the same entity cannot overtake a predecessor

Decide what one job means

A useful job ID identifies an obligation that a human could recognize. In an invoice review pipeline it could identify the task of interpreting one exact invoice revision under one extraction policy. A second scan of a revised invoice can be a deliberately separate job. A retry of the first scan stays attached to the first job and gets a new claim version. Settle this identity before choosing what to retry. Otherwise the queue may do exactly what its rows say while the application submits the same obligation several times.

Record immutable job input or an immutable reference to it. If the job reads a file whose contents may change between attempts, include the file revision in the queued input and check it when a worker starts. Decide whether a superseding upload invalidates the old job or gives the user two results that are clearly labeled by revision. Either rule can work. A result with no input revision makes the behavior difficult to explain to the person who supplied the document.

Write down the side effects separately from the inference call. An attempt may read a document, pay for an inference request, store a draft result, and send a decision to a review system. Each step has its own consequence if repeated. Letting a model compute a second draft can be acceptable if both calls are budgeted and only the current attempt can publish the draft. Creating a second review ticket under a new ticket ID can be unacceptable even when only one local queue row is completed. The queue design should say which action is safe to repeat and under whose rules.

List what a caller sees for each state. A queued job is eligible only after its scheduled time and prerequisites become true. A running job has an attempt recorded at the database. A completed job has its accepted result bound to the winning attempt. Rejected and canceled jobs need their own terminal meaning. A worker that encounters one of those states on a retry should preserve the recorded decision and report the current state to its caller. It should never use an empty claim result as evidence that a particular job finished.

Choose the scope of this guide's design by walking through three questions. Can another job make progress while one row is locked? Can the application reconcile or tolerate more than one attempt at the same logical job? Can the input arrive at each attempt under the same identity? If those answers are yes, a table-backed queue is a reasonable starting point. If one answer is unclear, build the corresponding fixture before implementing global worker concurrency.

Keep the transaction shorter than the inference call

PostgreSQL applies SKIP LOCKED to row locks. If a selected row cannot be locked immediately, the command can skip it. The PostgreSQL manual explicitly describes the resulting view as inconsistent and suitable for queue-like access by multiple consumers. A required table lock is still taken in the ordinary way. A conflicting maintenance command can therefore delay a claim even though competing worker locks usually get skipped. PostgreSQL SELECT and locking clauses

Use the database transaction to decide which worker has acquired an attempt. Read the next eligible row, increment its version, record its expiry, and return the fields the worker will need. Then commit. Only a confirmed claim may create permission in the application to start the inference attempt. If the commit response is lost, the returned row alone gives uncertain evidence. Read the job from an authoritative connection using the job ID and the claim version. Require both to match before initiating work in an attempt that might already have expired or been replaced.

Holding the transaction open across inference has a different cost. It ties up a connection, retains conflicting locks on the selected row, and stops the claim record from being visible to other sessions until commit. Framework logging may show the model call in progress while a separate observer continues to see the old committed queue state. After an interrupted worker, the transaction can roll back and erase the provisional ownership record. The actual inference or external call may already have happened. Making the claim durable before the network call gives recovery an observable starting point. PostgreSQL row-level locking

The following sample assumes a unique job ID, a non-null claim version starting at zero, and a lease expiry for each running row. It selects one job by ID to keep the concurrency fixture easy to read. A production queue can add a readiness time, tenant scope, retry limit, or priority field. Include the same eligibility rule in the tests and the diagnostic query. The example's 30-second lease is a fixture setting. Choose a production value from measured processing time, renewal behavior, and the recovery consequences of expiry.

WITH next_job AS (
    SELECT id
    FROM ai_jobs
    WHERE status = 'queued'
       OR (status = 'running' AND lease_until <= statement_timestamp())
    ORDER BY id
    LIMIT 1
    FOR UPDATE SKIP LOCKED
)
UPDATE ai_jobs AS job
SET status = 'running',
    claim_version = job.claim_version + 1,
    lease_until = statement_timestamp() + interval '30 seconds'
FROM next_job
WHERE job.id = next_job.id
RETURNING job.id, job.claim_version, job.lease_until;

Run this statement in a short claim transaction at the isolation level your application actually uses. PostgreSQL's Read Committed behavior for updates can recheck the search condition on a newer version of a concurrently updated row. Other isolation levels have different concurrency behavior and can require restarting a transaction. An application that retries a failed database transaction should discard information from that failed transaction and obtain a fresh committed claim before working. Test the real driver transaction boundary, including whether an ambient transaction lets a request handler keep a claim open beyond the call. PostgreSQL transaction isolation

A single claim statement gives one useful outcome even if it returns no rows. Zero means the statement found nothing it could claim now under its eligibility and locking rules. There might still be locked rows it skipped, future rows waiting for a readiness time, or rows at a retry cap. A brief wait with jitter before polling again can help when many workers see the same quiet period. A delay policy belongs outside the transaction. Sleeping while a claim transaction is open uses resources while preserving locks that other work could have made unnecessary.

Treat the returned claim as a credential to modify one queue row under constraints the database verifies. A worker should carry the job ID, the version it received, and the expiry it can report for diagnosis. Avoid reloading a job solely to obtain its latest claim version before writing the original result. That would allow a worker to overwrite the protection designed to distinguish its attempt. If it reloads for diagnosis, record any observed newer version separately and preserve the original version with the result it computed.

Design the lease for the failure you can test

A lease is a time-bounded invitation for another worker to recover a running job. It cannot tell you whether the old worker was terminated, paused, lost its connection, or finished a model call whose result is still in memory. You can permit lease renewal if attempts legitimately take longer than the initial lease. Renewal should guard the same job, attempt version, and required state. Otherwise a delayed renewal can revive a claim already assigned to someone else.

Select an expiry convention before implementing renewals. This guide uses a strict convention in which completion needs both the current claim version and a still-valid lease when the completion statement begins. If that rule is in force, a worker whose renewal or completion affects zero rows should stop claiming ownership and read the current committed state. You could choose a convention that accepts an expired attempt until a new claim version exists. Such a rule changes which results can win near lease expiry, so make it explicit and test both possible orders of completion and reassignment.

Use database time consistently for the rule. In the example, statement_timestamp() marks the start of the statement. PostgreSQL distinguishes that from the transaction start time and from the current time measured during statement execution. A statement that begins just before expiry can run or wait until after expiry. Under the example's chosen definition, the lease check is still based on the earlier statement time. If you need a clock-time guarantee at a later boundary, state the boundary and redesign the check or use a shorter time-bounded operation. Use timings comfortably away from expiry in the acceptance drill, and use an additional fixture for whichever boundary rule you choose. PostgreSQL date and time functions

Give a lease enough time to survive ordinary pauses before renewal. Start by measuring inference and result preparation on a representative workload, including the request type that usually runs longest. Then recover an intentionally paused worker and observe how much time passes before another worker can act. A longer lease gives the original attempt more time to recover from a transient pause. It also delays reassignment after a genuine loss. A shorter lease provides faster reassignment and can increase duplicate inference work if normal requests frequently outlast it. Treat that tradeoff as a decision with two measured costs rather than a universal default.

Batch claims change the lease calculation. A worker that claims twenty jobs before processing them one at a time has started twenty lease clocks. Later jobs may expire before inference begins even though the worker still appears healthy. If the worker can process only two concurrent tasks, use a claim batch that fits that capacity or explicitly account for waiting while owned. A staging burst that queues slower and faster classes together can reveal the same problem if a small average hides the wait for one slow tail class.

Give completion an authoritative readback

Complete the job with a conditional update that requires the original attempt version. Commit the result reference and terminal state together when they reside in the same database and can be written in one transaction. Count actual affected rows and handle the zero case as a failure of the update's conditions. Read the row to distinguish a replaced lease, an expired lease, cancellation, and an already-completed job. These states lead to different operator actions even when all produce the same zero.

UPDATE ai_jobs
SET status = 'complete',
    result_ref = $3,
    lease_until = NULL
WHERE id = $1
  AND status = 'running'
  AND claim_version = $2
  AND lease_until > statement_timestamp()
RETURNING id, claim_version, result_ref;

Use a test result reference that lets the reviewer identify the saving attempt from the actual row. A check that only asserts status = 'complete' can pass when the wrong attempt's result won. In the fixture below, the old attempt produces a reference visibly associated with version one, and the valid attempt produces a different reference associated with version two. The conjunction of job ID, finished status, version, and result reference detects incorrect winners. If results are stored separately, inspect the pointer the consumer follows as well as the storage record that pointer names.

An exception after a completion call is an ambiguous observation. The caller might have lost the response after the transaction committed, or the database might have rolled back. A fresh read distinguishes those cases when the row remains available and the expected version and result can still be recognized. Use the authoritative server or a read path with evidence that it includes the write. A lagging replica can make a committed result look absent. When the durable record is missing or ambiguous, leave the attempt unresolved rather than recomputing or replaying writes as though failure had been established. sinc-LLM guide to reconciliation after a timeout

The write may have committed even when the worker fails before logging it. Build a fixture that drops the network response after the test database has accepted the transaction, then checks what a different connection sees. A control that simply throws an exception before touching the database exercises a different branch. Keep both because they expose retry handlers that either repeat an already committed result or stop forever when the write never happened.

Run a two-session crash and recovery drill

Use a disposable database or a test-only queue with no real invoice data and a fake inference result. Configure the two claim sessions through the same driver and pool settings as the workers. Keep a third observer connection available. Give each connection a recognizable label and record its backend identity in the fixture log. If session labels are swapped, the test can misattribute a claim while the SQL trace still looks reasonable.

Seed two queued jobs, J1 and J2, ordered in that sequence. Before claiming either, have the observer record the two rows, their initial versions, and whether each meets the eligibility rule. Keep session A's claim for J1 open after obtaining its returned values. Start session B in a separate transaction and run the claim statement. B should obtain J2 without spending the test interval waiting for A. Commit B while A stays open. The observer should now see J1's original committed row and J2's running claim. After committing A and starting a fresh observer statement, it should see both running claims. Record the two commit observations alongside the IDs. Returned IDs alone would not distinguish an uncommitted assignment from the durable state the next process receives.

Next simulate the loss of A. Do not complete J1 from that attempt. Leave a version-one result ready in the harness, with no permission to act until the observer has confirmed reassignment. Use either a test clock mechanism that preserves the database predicate or wait until database time is safely past the lease. In a small local test, a new statement can confirm that the stored expiry is in the past before another session claims J1. Avoid proving only that the client slept for some number of seconds, since clock differences and delays in the original commit can make the intended ordering unclear.

Let a fresh session claim J1. Require the returned version to increase from one to two. Commit the claim and confirm from the observer that J1 is running at version two. Now resume the version-one result and attempt the guarded completion. It should return zero rows. Immediately read J1 and check that it remains running at version two and holds no result reference from version one. Complete from version two with its own distinct result reference and verify that the application reader sees the same result. If the resulting row is merely marked complete, continue checking until you know which result and version won.

Trial Held condition Expected durable observation
Simultaneous claim A keeps the first row locked while B claims B owns J2 after commit and cannot obtain J1 through that statement
Reassign after expiry A's running claim is committed and its lease expires A later claim commits version two on J1
Stale completion Version one returns after version two commits Zero updates, and J1 remains owned by version two
Current completion Version two has time remaining and a distinct result One update, and the observer finds the version-two result reference
Roll back before claim commit A exits with its first claim uncommitted J1 can be claimed as queued, with no durable record of A's provisional assignment
Response lost after commit The destination accepts the winning result, then the caller loses the response The fresh observation resolves the result without a second write

The strongest adverse test is a deliberately broken test-only completion implementation that uses the job ID alone. Repeat the stale completion step through it in a throwaway fixture. Your acceptance check should reject the resulting version-one reference, a premature completed state, or both. Restore the real guarded update before repeating the complete drill. If the verifier passes the broken implementation anyway, the test still lacks a meaningful check of the result that reached the consumer.

Run a cancellation case as well if users can withdraw work. Commit the cancellation while the inference attempt is still outstanding. Then let that attempt return with a well-formed result. The status guard should prevent the canceled job from becoming complete. Test the rule your product needs for a successful inference result retained for diagnostics. The critical distinction is whether the user's visible workflow can proceed based on that result. The underlying model call may already be paid for even if the cancellation wins.

Diagnose an empty claim without guessing at backlog

One useful control starts with a queue containing only J1. Keep a claim transaction open on J1 and run a second claim with ordinary settings. The second claim should find no immediately claimable row, but a separate ordinary read can still see the last committed version. After the first transaction rolls back, a fresh claim should succeed. This fixture demonstrates why counts from the claim operation describe consumer opportunity and counts from a queue snapshot describe committed rows under their respective predicates. PostgreSQL row locks block competing writers and lockers while ordinary reads use the visible version. PostgreSQL row-level locking

Check the shape of a backlog as well as its size. An illustrative monitoring report might distinguish rows ready for work, rows scheduled for the future, running rows with leases past due, and rows blocked on a product prerequisite. A claim consumer will never obtain several of those categories under the normal rule. Comparing total rows with claim throughput makes those categories look like stalled work. Conversely a count limited to ready jobs can hide old expired running rows if the reclaim loop is failing. Use the consumer's actual eligibility predicate when designing queue reports, then show the other categories when they are relevant to the operator's action.

Pair counts with age and a small list of stable row references for investigation. Tenant A can accumulate its oldest job while workers make quick progress for tenant B. An aggregate throughput line may remain healthy, and a scheduling preference can make the pattern persist. Review the longest wait by the fairness key your product promises. If work should be ordered only within a document or conversation, the important question is whether its next operation overtook an earlier operation for the same key. A global oldest-first sort by ID cannot answer that question for you.

Keep polling metrics at meaningfully different stages. Measure successful claim transaction commits, accepted completions, expired claims reclaimed, stale attempts rejected, and time spent waiting for the model. A run in which claims rise rapidly but completions remain flat should lead to an inspection of execution capacity and lease duration. A run in which workers poll, the ready age grows, and claim transaction latency rises can point to connection or lock waits. These signals each have possible causes. Confirm the cause from a real transaction or row observation before changing worker counts.

When maintenance could block the table, distinguish a lock timeout from an empty successful statement. Review the exception path at the driver and capture the affected operation in the queue logs. A test can hold a conflicting table lock in the disposable database, then run a claimer with a short test lock wait. Verify that it surfaces the configured failure and releases the ongoing transaction before another attempt. If the service returns a normal empty response and continues polling, it can hide a migration-related stall from the on-call operator. PostgreSQL table-level lock modes

Set the maximum effort per logical job

Store the attempt budget and scheduling policy with the facts that survive worker restarts. A per-process retry counter can reset when a new node picks up the same job. Distinguish the retry budget for database transactions from the budget for model calls. A transaction aborted before commit may have initiated no inference. A worker crash after a model response can consume an inference attempt even though the queue never accepted a completion. A decision about spending or escalation needs a ledger that reflects the boundary being controlled.

Run a failure fixture in which the external model always returns a retriable error. Observe what happens when the job reaches the chosen cap. The queue should retain a durable disposition and show who can make the next decision. It should also preserve the approved input identity so a replacement attempt cannot accidentally use a newer invoice while being billed and audited as the old job. If a human authorizes another attempt beyond the cap, record it as an explicit extension or a new obligation according to the application's rules. Avoid silently clearing the retry counter whenever the row changes owner.

A terminal outcome for one job may depend on another system receiving or resolving a related effect. Decide when the queue should mark a job complete if the result itself is written locally but the associated notification has not arrived. One defensible design commits the local effect and a durable request to notify in the same database transaction, then tracks notification delivery separately. A different application may define completion to require an acknowledged external disposition. Write the decision in the contract the product exposes. The database's success status cannot fill in missing workflow semantics on its own.

For a retried remote effect, choose a stable operation identifier for the same requested effect and verify the receiver's behavior under overlapping attempts. A queue attempt version is usually the wrong deduplication key because a reassignment changes it. If the external receiver accepts a job-scoped key and checks the intended parameters, the worker can ask whether the original effect was already applied. Verify the scope and lifespan of that protection. A key remembered for hours yields uncertain protection for a retry resumed days later. Use the destination's current record instead of assuming the key will still be known. sinc-LLM guide to application-side operation identity

Decide when a PostgreSQL queue fits

Compare designs by the guarantees they can demonstrate for the same driver path and workload. The relevant conditions include eligible work per tenant, throughput available on the primary, how many workers can run in parallel, duplicate-cost limits, needed replay history, and fair execution requirements. Capture one ordinary burst and a deliberately interrupted worker in each candidate design. A flattering throughput comparison with no interruptions will rarely expose the extra work required to deliver the promised end state.

Workload shape A reasonable starting design Requirement that changes the choice
Low to moderate dispatch volume, shared database, jobs independent Table-backed short-transaction claims Primary load or maintenance impacts make queue behavior unacceptable under the representative burst
A small number of strongly ordered actions for each account Serialize the ordering key while allowing different keys in parallel A second worker can process a later action for a key whose first action remains in flight
High fan-out across hosts with separate retention and delivery needs Evaluate a dedicated queue or broker under delivery, ordering, and acknowledgment rules The consumer lacks a stable request identity or receiver-side evidence after a retry
A multi-stage business process with timers, human decisions, and uncertain effects Consider a durable workflow engine and design each activity's recovery The team cannot retain or interpret the event evidence needed to reconstruct a run

Turn this into a one-page decision worksheet. Write down one unit of work, the time by which a stalled attempt must be recoverable, the maximum duplicate inference cost you can tolerate, and the owner of each externally visible effect. Add one line showing how an operator can distinguish a lost response from an absent write. Record your fairness key and which jobs can overtake others when one is blocked. If a system promise is stated in the worksheet, pair it with a rejection test. It becomes much easier to explain a migration later when the worksheet says which promise the old design failed to meet and where the new design proves it.

Test performance on the data shape you will actually maintain. A queue table with mostly completed rows and a small active set can behave differently from a freshly seeded small table. Update churn, retention, and regular database maintenance affect the workload alongside the claim query itself. Observe query plans and latencies in a production-like copy, then measure what happens after the system has repeatedly claimed, retried, and archived its target number of jobs. Treat an index change as a measured improvement for a query and state distribution at a given time. Keep the replay and completion tests when tuning, because faster statements bring little benefit if the change widened the eligible set or bypassed an ownership check. PostgreSQL routine maintenance

Check what batching changes on a busy shift

In a synthetic load check, use one worker slot, three queued jobs, and identical model calls that each take twenty seconds. Assume the claim and result writes occur immediately for this calculation. If the worker claims all three at second zero with a thirty-second lease, the first result arrives at second twenty, the second at forty, and the third at sixty. The last two cannot pass the strict expiry guard, even though the worker never stalled. If it claims one job at a time, the same calls can finish twenty seconds into their respective leases. Measure actual transaction and scheduling delays before carrying those numbers into your system.

Now introduce a model response tail rather than an oversized batch. Let the middle job take forty seconds while the others still take twenty. With one-at-a-time claims and a thirty-second lease, the middle job now expires even with no local backlog among owned jobs. This distinguishes two remedies with different effects. Shrinking batch size addresses delay before inference begins. Renewal or a changed lease covers a long-running attempt, with a different recovery delay after a worker stops entirely. Save the stage times for each job so a successful configuration change has an explanation you can check on the next workload.

Include the user-visible waiting time in the comparison. Taking fewer jobs under lease may move waiting out of worker memory and back into the queue, where a ready-age report can see it. Review whether your dashboard treats that change as an increase in waiting even though the same amount of work remains unfinished. For a fair comparison, measure from the moment the job becomes ready to the moment its accepted result is available. Compare the separate claimed and unclaimed intervals afterward to see which design changed the delay or the amount of repeated work.

Make a decision from the drill

Promote the claim logic only when the two-session fixture proves both distinct committed ownership and rejection of a stale result. Record the live driver isolation level, where the commits occur, and how an operator reads the queue and consumer result. Then separately decide whether the lease can be used for the job classes you measured. Give attention to slower classes and pressure on the database during the same test. A convenient setting on a workstation can fail either by expiring healthy work constantly or by retaining stalled work beyond the product's waiting time.

Hold if the claim returns the same active attempt to two workers, if a canceled job can become complete, or if a former attempt can overwrite a newer result. Hold when the external destination cannot resolve a potentially repeated costly action. For performance findings that do not violate correctness, decide whether a narrower rollout can provide representative evidence while keeping the workload within bounds. The release record should identify the unresolved question and specify which observation would permit the next step. That gives the next on-call engineer a useful action even if you finish the drill outside their shift.

Keep independent disposition fields for the committed queue row and the effect at the destination. An operator may know that a replacement worker now owns the row while the first worker's external effect still needs reconciliation. Close the external obligation only after reading its authoritative outcome under the original operation identity.

FAQ

Does SKIP LOCKED guarantee that jobs run in ID order?

No. Sorting selects which eligible rows a statement tries to lock first. A row can be skipped while another session holds its lock, and two workers can finish in a different order from their claims. If the product requires one sequence per conversation, account, or document, use that ordering key in the model and test that the second operation cannot pass the first while it is delayed. If the sequence applies globally, compare a single ordered consumer or another design that can show the order at the destination. PostgreSQL SELECT locking clause

Can I execute the model call before committing a claim?

The proposed procedure commits the claim first. This makes ownership visible to a different connection and releases the locks before the network call. If code executes inference inside an ambient transaction, its returned claim rows may never commit and its result may outlive a rollback. Inspect the actual transaction boundary in the worker and try closing the worker connection after it begins the model call. The presence of a committed claim in the observer is the check that makes the intended call order meaningful.

Can I count a completion when the database returned one row but the commit timed out?

Keep that completion unresolved until you read the durable result. A returned row describes the statement's effect inside its transaction. The database can commit and the connection can then lose the reply, or the transaction can fail before committing. A separate reader that sees the completed state with the intended attempt version and result reference can resolve the first case. If you read through a replica, confirm it can see the relevant write before relying on absence.

What should a stale worker do with the result it already computed?

It should keep its original attempt version for diagnosis, report that the guarded completion had no effect, and follow the service's existing rule on retaining a losing result. The queue application should choose whether to retain that result for cost analysis or discard it under its data policy. Attempt recovery should never change the saved association between one inference output and the version that produced it. A late result with no claim identity can hide an ownership error in later analysis.

Should a retry always create a new job ID?

Use a new ID for a new business obligation. Use a new attempt version when recovering the same obligation. Reissuing the same job under a fresh ID can sidestep the retention, deduplication, and cost rules the original job already had. Include the input revision when deciding whether an uploaded correction counts as new work. That decision belongs to the application's relationship with the caller, and it should be visible in the accepted result.

What evidence is enough to close an incident?

Inspect the row for the affected job and the result the application serves. Confirm which attempt owned the terminal state and what outcome was presented to the caller. If the job could write outside the queue database, also reconcile the external operation under its stable identity. Review the affected time window for other rows that can have the same bug. A healthy current worker pool can show that service recovered while an earlier job still needs correction.

Sources