A Postgres job queue with SKIP LOCKED: leases, retries and dead jobs
Build a job queue on Postgres with FOR UPDATE SKIP LOCKED: a one-statement claim, leases for crashed workers, fenced completion, backoff and dead jobs.
· 7 min read
- Postgres
- Job queues
- Reliability
Most applications need background work: sending emails, resizing images, calling a slow API. The usual answer is a message broker. If you already run Postgres, you can often skip that. A table of jobs, a few workers and one well-written query will carry a surprising amount of load, and a job can commit in the same transaction as the data that caused it.
The query has to be right, though. This article builds a queue that stays correct when a worker crashes, when a slow worker finishes after its job was given to someone else, and when a job fails every time.
Everything here was run against PostgreSQL 16 with Node.js 22 and the pg driver. The SQL is plain Postgres, and SKIP LOCKED has been available since 9.5.
The table
CREATE TABLE jobs (
id bigserial PRIMARY KEY,
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued', 'running', 'done', 'dead')),
attempts int NOT NULL DEFAULT 0,
max_attempts int NOT NULL DEFAULT 5,
run_at timestamptz NOT NULL DEFAULT now(),
locked_until timestamptz,
last_error text
);
CREATE INDEX jobs_ready ON jobs (run_at, id) WHERE status IN ('queued', 'running');
run_at is when a job becomes eligible, which gives you delayed jobs and retry backoff for free. locked_until is a lease: how long a worker may hold the job before others can take it. The partial index covers only unfinished jobs, so it stays small however many completed rows pile up.
Why SELECT then UPDATE fails
The obvious loop reads the next queued job, then marks it taken:
SELECT id FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1;
UPDATE jobs SET status = 'done' WHERE id = $1;
Between those two statements nothing stops another worker reading the same row. We ran 2,000 jobs through eight workers this way and recorded every start. There were over 10,000 executions of 2,000 distinct jobs, more than five runs per job on average. Adding status = 'queued' to the UPDATE and checking the row count would stop the duplicates, but the workers would still fight over the same row.
Claim in one statement
FOR UPDATE SKIP LOCKED lets each worker lock rows that nobody else has locked and ignore the rest. Combine it with an UPDATE and the claim is a single atomic statement:
UPDATE jobs
SET status = 'running',
attempts = attempts + 1,
locked_until = now() + make_interval(secs => $2)
WHERE id IN (
SELECT id FROM jobs
WHERE attempts < max_attempts
AND ((status = 'queued' AND run_at <= now())
OR (status = 'running' AND locked_until < now()))
ORDER BY run_at, id
LIMIT $1
FOR UPDATE SKIP LOCKED)
RETURNING id, payload, attempts;
The subquery picks up to $1 eligible jobs and locks them, skipping rows another transaction has locked. The outer UPDATE marks them running, starts the lease and returns them. Keep the claim to this one table: the mailing-list reports of SKIP LOCKED misbehaving that we found involve joins or filters on other tables.
Eight workers running this claim processed 5,000 jobs with no duplicates.
The PostgreSQL documentation says skipping locked rows gives an inconsistent view of the data, unsuitable for general work but fine for avoiding lock contention between consumers of a queue-like table. That is this case. Do not use it for reports.
Without SKIP LOCKED the claim still works, but it waits. We held an uncommitted claim of five jobs in one session and ran the same claim in another. Without SKIP LOCKED the second waited for the first to commit, then received the next five jobs. With it, the second got the next five straight away. A one-statement claim holds its locks briefly, so eight workers took about the same time either way on 5,000 jobs. The difference matters once locks are held while real work happens, as in the transaction-per-job approach below.
Note that an empty result does not mean the queue is empty: other workers may hold the remaining rows. Treat it as “nothing for me right now”.
Leases: surviving a crashed worker
The claim query also takes any running job whose locked_until has passed. That is the recovery path. A worker that dies mid-job never calls back, its lease runs out, and another worker claims the job and increments attempts.
We tested it with a half-second lease. The first worker claimed the job, and a second worker’s claim returned nothing. After the lease expired, the second claim returned the same job with attempts = 2.
Pick a lease longer than your slowest normal job. A batch shares one lease: claim ten jobs on a 60-second lease and the tenth may be near expiry before it starts. Claim small batches, as the loop below does.
Fenced completion: the late worker
Leases have a catch. A worker whose lease expired may not be dead, only slow. It finishes and reports success for a job that someone else now owns. If completion is just UPDATE jobs SET status = 'done' WHERE id = $1, the slow worker marks the job done while the second worker is still running it, and the second worker’s later failure is lost.
The fix is to make completion conditional on the attempt number you were given, which acts as a fencing token:
UPDATE jobs SET status = 'done', locked_until = NULL
WHERE id = $1 AND status = 'running' AND attempts = $2;
In our test the first worker, with attempts = 1, tried to complete after the second worker had reclaimed the job at attempts = 2. It updated zero rows. The second worker’s completion updated one. Treat zero rows as “I lost this job” and stop quietly.
This protects the queue’s bookkeeping, not the outside world. The slow worker may already have sent the email. Jobs can therefore run more than once, and the handlers must be safe to repeat. The techniques in idempotent payment webhooks apply directly: an idempotency key per job, passed to the downstream service.
Failures, backoff and dead jobs
When a handler throws, schedule a retry with exponential backoff, or give up if the job has used all its attempts:
UPDATE jobs SET
status = CASE WHEN attempts >= max_attempts THEN 'dead' ELSE 'queued' END,
run_at = now() + least(interval '1 hour', interval '10 seconds' * power(2, least(attempts - 1, 10))),
locked_until = NULL,
last_error = $3
WHERE id = $1 AND status = 'running' AND attempts = $2;
The delay doubles with each attempt: 10 seconds after the first failure, 20 after the second, and so on, capped at an hour (the least on the exponent also stops the interval overflowing if you raise max_attempts). We checked the second attempt scheduled a retry 20 seconds out, and that a fifth failure set dead. A dead job stays in the table with its last error, so a person can inspect it and requeue it. Reset attempts when you do, or the claim will ignore it:
UPDATE jobs SET status = 'queued', attempts = 0, run_at = now(), last_error = NULL
WHERE id = $1 AND status = 'dead';
Alert on the count of dead jobs; a queue that silently drops work is worse than no queue.
There is one gap. A job that crashes its worker every time never reaches the failure query. The claim skips it once attempts reaches max_attempts, so it sits as running for ever. We saw exactly that: five claims, then nothing, with the row stuck at running. A periodic sweep closes it:
UPDATE jobs SET status = 'dead', locked_until = NULL,
last_error = coalesce(last_error, 'lease expired on final attempt')
WHERE status = 'running' AND locked_until < now() AND attempts >= max_attempts;
Run it every minute or so from any worker. Done rows pile up too, so delete or archive them after a few days.
The worker loop
Put together, a worker is short:
async function work(pool, handle, signal) {
while (!signal.aborted) {
const { rows } = await pool.query(CLAIM, [3, 60]);
if (rows.length === 0) { await sleep(1000); continue; }
for (const job of rows) {
try {
await handle(job.payload);
await pool.query(DONE, [job.id, job.attempts]);
} catch (err) {
await pool.query(FAIL, [job.id, job.attempts, String(err)]);
}
}
}
}
Here CLAIM, DONE and FAIL are the three statements above, and sleep is a promise-wrapped setTimeout. A real worker also needs a try/catch around the database calls so a brief outage does not kill it. We ran three against 50 jobs, five of which always threw and seven of which failed once. Forty-five finished, the five ended dead after five attempts each, and the seven succeeded on their second try.
Polling once a second is fine for most systems. For lower latency, LISTEN and NOTIFY can wake workers on insert, but keep the poll as a fallback: a session only receives notifications sent while it is listening.
The alternative: hold the transaction open
Another design claims a job, does the work inside the same transaction, and deletes or updates the row at the end. A crash needs no lease, because Postgres releases the row locks when the connection ends. We checked this by locking a row in one session and terminating that session’s backend: a second worker could claim the row immediately afterwards.
The cost is that every in-flight job holds a connection and an open transaction, and long transactions stop vacuum cleaning a table that changes constantly. A rollback also undoes the attempts increment, so a job that crashes its worker is retried for ever with no path to dead. Leases avoid both. Prefer them unless the jobs are quick and rare.
When to use something else
A Postgres queue suits thousands of jobs per hour on a database you already run, especially when enqueueing in the same transaction as your data matters. Reach for a broker when you need fan-out to many consumers, very high throughput or strict ordering across partitions.
If you’re designing background processing, a job system or the APIs around it, see our backend development service.