Measured on PostgreSQL 18.4: what plain FOR UPDATE and SKIP LOCKED workers see, how a dead worker frees its job, and why leases need a guarded finish.
A queue table that already exists
Belgavi's Book Store sends shipping-label requests, refund checks and reminder emails through background jobs. Geetha's team already runs PostgreSQL, and adding a message broker for a few thousand jobs a day felt like more infrastructure than the problem deserved. So the jobs live in a table, and workers take them with SELECT ... FOR UPDATE SKIP LOCKED.
That is a well-known pattern, and it works. It also has sharp edges that are easy to miss until a worker crashes in production: what happens to its job, how long other workers wait, what ordering you actually get, and how a slow worker can finish a job someone else has already re-claimed. This guide measures each of those on PostgreSQL 18.4 with two to four connections, then builds a claim query that handles them. Every result below comes from the companion probe, run on Windows 11 against a disposable local cluster at the default read committed isolation level.
The table and the claim
CREATE TABLE jobs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
payload text NOT NULL,
status text NOT NULL DEFAULT 'queued', -- queued, running, done, dead
attempts int NOT NULL DEFAULT 0,
lease_until timestamptz,
worker text
);
CREATE INDEX jobs_claimable ON jobs (id) WHERE status IN ('queued', 'running');The simplest claim holds a row lock for the whole job, inside one transaction:
BEGIN;
SELECT id, payload FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED;
-- do the work, then
UPDATE jobs SET status = 'done' WHERE id = $1;
COMMIT;The PostgreSQL documentation for the locking clause describes SKIP LOCKED precisely: "any selected rows that cannot be immediately locked are skipped. Skipping locked rows provides an inconsistent view of the data, so this is not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue-like table."
Measured: with and without SKIP LOCKED
With plain FOR UPDATE, two workers contend on the same first row. Worker A claimed job 1 and held its transaction open. Worker B's identical query blocked; after one second it was still waiting. When A marked job 1 done and committed, B's query returned job 2. PostgreSQL rechecked the locked row, found it no longer matched status = 'queued', and continued to the next row, so B did not get a wrong row, but it waited for as long as A worked. With N workers, every claim queues behind the slowest job at the head of the table.
With SKIP LOCKED, the same situation is concurrent. Four connections each ran the claim inside an open transaction: A got job 1, B got job 2 and C got job 3 at once, without waiting, and D, with all three jobs locked, got an empty result immediately rather than blocking.
The plan for the claim, with 2,000 rows and the partial index, was Limit -> LockRows -> Index Scan using jobs_claimable on jobs with a filter on status. The LockRows node is where locked rows are skipped. Keep the partial index small by moving finished jobs out of queued and running; a claim that has to scan past thousands of locked or finished rows gets slower as the table grows.
Measured: a worker that dies
The value of holding the claim in a transaction shows when a worker dies. The probe claimed job 1 from connection A, then terminated A's backend with pg_terminate_backend, the same outcome as a crashed worker process or a dropped connection. Connection B's next claim returned job 1 at once. The transaction was rolled back, the lock vanished, and the row was still queued.
The cost is that a long job holds a transaction and a connection for its whole duration. PostgreSQL connections are not cheap, long transactions hold back vacuum, and a job that calls a slow external service can keep a transaction open for minutes. So many queue designs commit the claim immediately and track ownership in the row instead, with a lease.
Leases: claim, commit, renew
A lease claim marks the job as running with an expiry, and commits:
UPDATE jobs
SET status = 'running', attempts = attempts + 1,
lease_until = clock_timestamp() + make_interval(secs => $1), worker = $2
WHERE id = (SELECT id FROM jobs
WHERE status = 'queued'
OR (status = 'running' AND lease_until < clock_timestamp())
ORDER BY id LIMIT 1
FOR UPDATE SKIP LOCKED)
RETURNING id, attempts, worker;SKIP LOCKED now protects only the instant of claiming; the lease protects the job afterwards. clock_timestamp() is used rather than now(), because now() is fixed at the start of the transaction.
The probe used a two-second lease. Worker w1 claimed job 1 and stopped, as if paused or partitioned. Worker w2 claimed job 2, then asked again before the lease expired and got nothing: job 1 was still leased. After 2.5 seconds, w2's claim returned job 1 with attempts = 2. So far, correct.
Then w1 woke up and finished job 1 with a plain UPDATE jobs SET status = 'done' WHERE id = 1. It updated one row. w1 had marked done a job that now belonged to w2. Adding ownership to the finish closed that:
UPDATE jobs SET status = 'done', lease_until = NULL
WHERE id = $1 AND worker = $2 AND attempts = $3; -- 0 rows means: you lost the leaseWith the guard, w1's update affected zero rows, and w1 learns that its work no longer counts. The attempts value from the claim acts as a fencing token: even if the same worker name re-claims a job later, an old attempt cannot finish the new one.
The guard keeps the table consistent. It does not undo side effects. If w1 already sent an email before its guarded finish failed, w2 will send it again. A lease converts "a crashed worker's job is stuck forever" into "a slow worker's job may run twice", so the work itself must be idempotent, for example by passing a key derived from the job id to the email service, and long jobs should renew their lease with a guarded UPDATE ... SET lease_until = ... well before it expires.
Measured: the order you give up
Nine jobs, three workers, job 1 taking 0.6 s, job 5 taking 0.3 s and the rest 0.1 s. Completion order: 2, 3, 4, 6, 7, 5, 8, 1, 9. Jobs are claimed in id order, but they finish in whatever order their durations allow, and a retried job runs after jobs queued behind it. SKIP LOCKED queues give no ordering guarantee beyond "roughly oldest first". If two jobs for the same order must run in sequence, encode that dependency: claim only jobs whose predecessor is done, or serialise per key, for example by keeping one running job per customer with a partial unique index on the key where status = 'running'.
Enqueue in the same transaction
The strongest argument for a table queue is not its claim query but its enqueue. Because the jobs table lives in the same database as the orders, the code that records a refund can insert the refund-check job in the same transaction. Either both commit or neither does, so there is no window in which a refund exists without its job or a job points at a refund that was rolled back. A separate broker needs an outbox table or a similar mechanism to get the same guarantee.
Workers that poll an empty queue waste queries and add latency. PostgreSQL's LISTEN and NOTIFY can wake them: the enqueuing transaction runs NOTIFY jobs_ready, and idle workers LISTEN on that channel. The documentation states that a notification sent inside a transaction is delivered only if and when the transaction commits, so a worker is never woken for a job it cannot yet see. Keep a slow poll as a fallback anyway, because a notification sent while no worker was listening is not queued for later.
Poison jobs and dead letters
A job that crashes its worker every time is re-claimed after every lease expiry, forever. Cap attempts in the claim and move exhausted jobs aside:
UPDATE jobs SET status = 'dead'
WHERE status = 'running' AND lease_until < clock_timestamp() AND attempts >= 5;Run it before claiming, or fold the condition into the claim query, and alert on the dead count. The interactive lab lets you vary lease length, attempt limits and crash timing and see which jobs end up done twice, stuck or dead.
When a table queue is the wrong choice
A PostgreSQL table queue is a good fit for moderate volumes where jobs and business data live in the same database, so that enqueuing a job can be part of the transaction that creates the order. It becomes the wrong tool when throughput is high enough that claim contention, index churn and vacuum dominate, when consumers need fan-out to many independent subscribers, or when jobs need strict per-key ordering at high volume. Measure claim latency and table bloat as volume grows, and move to a broker when either starts to climb.
Limits
The measurements come from one local PostgreSQL 18.4 cluster with at most four connections and synthetic jobs; they demonstrate behaviour, not throughput. Timings depend on the machine. Lease expiry relies on the database server's clock, which is consistent for all workers because every comparison runs on the server.
Interactive experiment
Postgres job queue: SKIP LOCKED claims, crashes and leases. Synthetic browser-local fixtures, adjustable inputs, decision traces and JSON export.