Deep Engineering
Advanced·Published·55 MIN

A job queue on PostgreSQL: SKIP LOCKED, LISTEN/NOTIFY, and where it runs out

A table, FOR UPDATE SKIP LOCKED and a notification in the same transaction, and you have a queue without a broker. Measured on PostgreSQL 16.15: where it holds up under load, where workers wait for each other, where one job goes to two workers, and how one forgotten transaction nearby makes every claim more expensive.

Full technical treatment

TL;DR

  • A queue on PostgreSQL is a table and a SELECT … FOR UPDATE SKIP LOCKED query: a worker locks a row, and the others skip that row. The PostgreSQL 16 contract permits this for a queue-like table and warns that such a query gives an inconsistent view of the data, so it is unfit for counting the queue or for business checks.
  • One claim is not one execution. A worker that dies after an external effect (an email, a payment, an HTTP call) and before the commit hands the job back, and the next worker runs it again: in our experiment the effect happened twice. A single effect comes not from SKIP LOCKED but from an idempotency key at the receiver.
  • Without SKIP LOCKED, workers line up behind a single row. With a 5 ms job, 16 workers using FOR UPDATE in our measurement got through as many jobs as one — 164 per second versus 170; with SKIP LOCKED, 2,390.
  • Claiming with UPDATE … WHERE id = (SELECT … LIMIT 1) without a lock in the subquery hands one job to two workers. Two workers, one job — reproduced deterministically; under load with 16 workers about half of all claims were repeats.
  • LISTEN/NOTIFY removes the polling delay: on our machine a median of 0.8–0.9 ms versus 52–54 ms when polling every 100 ms. But by contract a notification reaches only sessions that are already listening, so first LISTEN, then check the table, and keep polling as the safety net.
  • Every job removed with DELETE or UPDATE leaves a dead row version. While a transaction with an old snapshot or an assigned transaction number is open in the database (in the experiments, a REPEATABLE READ snapshot and a worker holding a job under FOR UPDATE), VACUUM may not remove it. In our schema, with a REPEATABLE READ snapshot open, three minutes at 1,000 jobs per second took the claim query from a handful of pages to 3,286, and an empty queue after a million jobs answered in 91 ms.

Why know this?

A job queue in the same database as the data is a tempting design. The job is enqueued in the same transaction as the business write, so there is never a job without its record or a record without its job. No extra service, no extra monitoring, no extra failure mode. It is the same argument as for the transaction outbox, and in that article the outbox is also a queue-like table that the relay drains with the same SKIP LOCKED.

There are three questions here, and each has its own measurement. How several workers take jobs without getting in each other's way. How a worker learns about a new job without polling the table every few milliseconds. And what happens to a table that hundreds of thousands of jobs pass through, especially when something else is running alongside.

The benchmark machine has two cores, shared by the server and all the workers. So the absolute numbers are specific to this machine. What carries over is the shape of the curves and the ratios within one experiment, and each measurement notes this.

The model: a job is a row, taking a job is locking a row

The table is simple:

SQL
SQL
CREATE TABLE jobs (
  id bigserial PRIMARY KEY,
  status text NOT NULL DEFAULT 'pending',
  payload text NOT NULL
);
CREATE INDEX jobs_pending ON jobs (id) WHERE status = 'pending';

A worker does the same thing in a loop:

SQL
SQL
BEGIN;
SELECT id, payload FROM jobs
  WHERE status = 'pending'
  ORDER BY id
  LIMIT 1
  FOR UPDATE SKIP LOCKED;
-- work on the job
DELETE FROM jobs WHERE id = $1;
COMMIT;

The row lock is what "this job is taken" means. It lives as long as the worker's transaction is open. If the worker dies, the transaction rolls back, the lock is released, and the row is available again to the next worker. In this scheme there is no "taken by" column and no watchdog that frees stuck jobs: the transaction machinery does that work.

The price of this convenience is a transaction that stays open for the whole job, and only what was done in the database is rolled back. The section "One claim is not one execution" covers what that means for jobs with external effects and for long jobs; the sections after it cover how workers share rows and what an open transaction does to the table.

What SKIP LOCKED promises

language contractPostgreSQL 16, SELECT — The Locking Clause

With SKIP LOCKED, 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.

— PostgreSQL 16, The Locking Clause

"An inconsistent view" is not fine print; it is an exact description of what a worker will see. Three sessions on a table of ten jobs:

measured observationbench/pg-queue/contract.py, PostgreSQL 16.15. No timing here: the result is which rows each session received.
1. SKIP LOCKED: THREE SESSIONS, NO OVERLAP, AN INCOMPLETE VIEW
--------------------------------------------------------------
session A, LIMIT 3 SKIP LOCKED:     [1, 2, 3]
session B, LIMIT 3 SKIP LOCKED:     [4, 5, 6]
session C, no LIMIT, SKIP LOCKED:   [7, 8, 9, 10]
overlap A/B: []
pending rows in the table: 10; returned to C: 4

A and B got different rows — that is the whole point. But session C, which asked for "all jobs" without a LIMIT, got four rows out of ten, although all ten exist and all ten are pending. For a queue this is the right answer: taken jobs should not be taken again. For any other question — "how many jobs are queued", "is there a job for this order" — it is the wrong answer, and nothing reports an error. So SKIP LOCKED belongs only in the claim query, and everything else uses a plain SELECT.

Without SKIP LOCKED, workers wait for each other

language contractPostgreSQL 16, Explicit Locking — Row-Level Locks

FOR UPDATE without SKIP LOCKED does what the documentation promises: SELECT FOR UPDATE will wait for a concurrent transaction that has run any of those commands on the same row, and will then lock and return the updated row (or no row, if the row was deleted).

measured observationbench/pg-queue/contract.py, PostgreSQL 16.15.
2. FOR UPDATE WITHOUT SKIP LOCKED: THE SECOND SESSION WAITS
-----------------------------------------------------------
session A holds:  [1, 2, 3]
session B, lock_timeout 300ms: LockNotAvailable: canceling statement due to lock timeout
session B, NOWAIT: LockNotAvailable: could not obtain lock on row in relation "jobs"
session B, plain FOR UPDATE, while A works 0.5 s and then deletes its rows:
  B waited 0.50 s and then got [4, 5, 6]

The second session waited for exactly as long as the first one worked, and only then received the next rows. NOWAIT and lock_timeout do not remove the wait; they turn it into an error: the worker does not wait, but it does not get a job either. In a queue that means every worker but one is busy waiting or retrying.

Claiming with UPDATE: one job, two workers

A common way to claim avoids holding a transaction open during the work: the status flips in a short UPDATE, and the work happens afterwards.

SQL
SQL
UPDATE jobs SET status = 'running'
  WHERE id = (SELECT id FROM jobs WHERE status = 'pending' ORDER BY id LIMIT 1)
  RETURNING id;

It looks atomic — one statement. It is not. The subquery runs with the snapshot taken at the start of the statement and finds row 1. If another transaction is already changing that row, the UPDATE waits, and after that transaction commits it rechecks only the outer condition, id = 1. That condition still holds, and the row is updated a second time:

measured observationbench/pg-queue/contract.py, PostgreSQL 16.15, READ COMMITTED. Two sessions; the second starts while the first has not committed yet.
3. CLAIMING WITH UPDATE ... WHERE id = (SELECT ... LIMIT 1)
-----------------------------------------------------------
naive               A got [1], B got [1] after waiting 0.30 s; running 1, pending 9
status rechecked    A got [1], B got [] after waiting 0.30 s; running 1, pending 9
SKIP LOCKED inside  A got [1], B got [2] after waiting 0.00 s; running 2, pending 8

First line: both workers got job 1, and the table holds a single running row, so nothing reveals the duplicate. Second line: with AND status = 'pending' added to the outer condition there is no duplicate, but the second worker waited 0.3 s and came back empty-handed while nine jobs sat in the queue. Third line: with FOR UPDATE SKIP LOCKED in the subquery, the second worker got job 2 at once. That is the correct form of a claim "without a long transaction", and below it is measured alongside the others. But for a dead worker's job to come back, this form also needs a lease deadline and an owner token — the next section covers them.

One claim is not one execution

SKIP LOCKED guarantees that two workers do not hold the same row at the same time. It does not guarantee that a job is executed only once: a rollback returns the job to the queue, but does not undo what the worker managed to do outside the database.

A crash after an external effect

The "external effect" in the experiment is a write over a separate connection in autocommit mode, which is how any outbound call behaves. A worker took a job, performed the effect, and was killed with signal 9 before COMMIT:

measured observationbench/pg-queue/delivery.py, PostgreSQL 16.15. No timing here: the result is how many times the job was claimed and how many effects reached the receiver.
1. A CRASH AFTER THE EXTERNAL EFFECT AND BEFORE COMMIT
------------------------------------------------------
external effect = an autocommit insert into table sent from its own connection
receiver without an idempotency key:
  worker 1: claimed job 1; effect done; killed before COMMIT
  worker 1 exit signal: 9
  worker 2: claimed job 1 again; effect done; committed
  jobs left: 0; claims of the job: 2; external effects recorded: 2 (worker 1, worker 2)
receiver with a unique key on job_id:
  worker 1: claimed job 1; effect done; killed before COMMIT
  worker 1 exit signal: 9
  worker 2: claimed job 1 again; effect skipped: this job_id was already handled; committed
  jobs left: 0; claims of the job: 2; external effects recorded: 1 (worker 1)

The job was claimed twice with either receiver — that is a property of the queue: the first worker's transaction rolled back, and the row came back. How many times the effect happens is up to the receiver. Without an idempotency key, twice. With a unique key on job_id, once: the second attempt sees that the effect has already happened and does nothing. So making the effect happen once is the receiver's job (a key it checks), not the queue's.

Two execution models

language contractPostgreSQL 16, idle_in_transaction_session_timeout

Model A is the one above: the transaction and the row lock live for the whole job. Model B is a short claim with a lease: an UPDATE sets status = 'running', a lease deadline locked_until, an attempt number and an owner token, and commits at once; the work happens outside a transaction, and an expired lease can be taken by another worker. The documentation warns that an open transaction prevents vacuuming away recently-dead tuples that may be visible only to this transaction — and that applies to a model A worker holding a job too:

measured observationbench/pg-queue/delivery.py, block 2, PostgreSQL 16.15, READ COMMITTED. One worker holds a job for 3 s; another takes and deletes 10,000 jobs meanwhile.
2. A LONG JOB UNDER AN OPEN TRANSACTION HOLDS BACK VACUUM
---------------------------------------------------------
one worker holds its job for 3 s; meanwhile another worker takes and deletes 10000 jobs
READ COMMITTED, autovacuum off for the table
model A: row lock held for the whole job:
  the holding session: state 'idle in transaction', backend_xid age 101, backend_xmin None
  VACUUM while the job is held: tuples: 0 removed, 20001 remain, 10000 are dead but not yet removable
  VACUUM after its COMMIT:      tuples: 10001 removed, 5038 remain, 0 are dead but not yet removable
model B: lease, no transaction during the job:
  job 1 is leased and being worked on; sessions holding an xid: 0
  VACUUM while the job is leased: tuples: 5331 removed, 10001 remain, 0 are dead but not yet removable

The model A worker has no snapshot (backend_xmin is empty — this is READ COMMITTED), but it has a transaction number: the row lock assigns one. That is enough for the 10,000 rows deleted by the other worker to stay "dead but not yet removable". A one-minute job under an open transaction is the same as a one-minute long transaction next to the queue, and the section on dead rows shows what that costs. Model B does not hold the horizon back.

So model A suits short jobs, and model B long ones. The price of model B is that "this job is taken" is now a record, not a lock, and the question "who is the owner" has to be answered explicitly:

measured observationbench/pg-queue/delivery.py, block 3, PostgreSQL 16.15. A 1 s lease; the first worker stalls for 1.5 s after claiming.
3. A LEASE WITH AN OWNER TOKEN: THE OLD OWNER COMES BACK LATE
-------------------------------------------------------------
lease 1 s; worker 1 stalls for 1.5 s after claiming; worker 2 claims the expired lease
completion by id only, receiver checks nothing:
  worker 1: claimed job 1, token 1, attempt 1
  worker 2, right away: nothing, the lease is still valid
  worker 2, after 1.5 s: claimed job 1, token 2, attempt 2
  worker 2: external effect with token 2: accepted
  worker 1 wakes up: external effect with token 1: accepted
  worker 1 completes: 1 row deleted
  worker 2 completes: 0 rows deleted (the job was already gone)
  external effects accepted by the receiver: 2
completion and receiver check the token:
  worker 1: claimed job 1, token 1, attempt 1
  worker 2, right away: nothing, the lease is still valid
  worker 2, after 1.5 s: claimed job 1, token 2, attempt 2
  worker 2: external effect with token 2: accepted
  worker 1 wakes up: external effect with token 1: rejected: a newer token was already seen
  worker 1 completes: 0 rows deleted (stale token rejected)
  worker 2 completes: 1 row deleted
  external effects accepted by the receiver: 1

The lease expired while the first worker was stalled, and the second worker rightly took the job — as it should, or a dead worker's job would never come back. But the first worker does not know it is no longer the owner. If completion is DELETE … WHERE id = …, it deletes a job the second worker is still working on, and the receiver accepts both effects. If completion checks the token (… AND token = $2), the late owner gets 0 rows. But the effect it has already sent can be stopped only by a receiver that checks the token itself: in the experiment it accepts an effect only if it has not seen a newer token.

A job that always fails

Model B has room for an attempt counter and a next-attempt time, and they are needed for one more reason: a job that fails on every attempt would otherwise return to the queue forever.

measured observationbench/pg-queue/delivery.py, block 4, PostgreSQL 16.15. Backoff 0.2 s × 2^(attempt − 1) plus up to 50% random jitter, at most three attempts.
4. A JOB THAT ALWAYS FAILS: ATTEMPTS, BACKOFF, FAILED
-----------------------------------------------------
job 1 always raises, job 2 succeeds; at most 3 attempts; backoff 0.2 s * 2^(attempt-1) plus up to 50% jitter
  0.00 s  job 1 attempt 1: ValueError; next try in 0.27 s
  0.00 s  job 2 attempt 1: done
  0.30 s  job 1 attempt 2: ValueError; next try in 0.47 s
  0.78 s  job 1 attempt 3: ValueError; marked failed
  left in the table: job 1, status failed, attempts 3, last_error 'ValueError: bad payload'

The neighbouring job ran at once while the first one waited out its backoff; after the third failure the job stayed in the table with status failed and the error text — it can be inspected and rerun by hand. The numbers here are parameters of the experiment, not a recommendation: the attempt limit and the backoff are chosen according to what a retry costs the receiver.

How many jobs per second

We measure four ways to claim a job with one to sixteen workers, each a separate process with its own connection. The work on a job is a sleep of 0 ms (the bare cost of claiming and committing) or 5 ms (a job that waits on the network). For the UPDATE methods the work happens outside the transaction; for the others, inside it, with the row locked.

measured observationbench/pg-queue/throughput.py, PostgreSQL 16.15, synchronous_commit = on, two cores shared by the server and all workers. Median of three 4 s passes; duplicates per pass.

5 ms of work per job, jobs per second, bench/pg-queue/throughput.py, block 2:

workersSKIP LOCKEDFOR UPDATEUPDATE, naive: claimsof them uniqueUPDATE + SKIP LOCKED
1166170162162159
2328167321171319
4643163622316610
8128216612447301178
162390164231111302174

Three curve shapes, and the shape is the point.

SKIP LOCKED grows almost linearly: 16 workers process 14.4 times as many jobs as one. A worker spends most of its time asleep inside a job, and while it sleeps the others take the next rows. Having only two cores does not get in the way: a sleeping worker does not occupy them.

FOR UPDATE does not grow at all: 163 to 170 jobs per second whatever the number of workers. That is exactly one job at a time: every worker waits for the first free row, one gets it, and the rest wait for its commit.

The naive UPDATE grows, but counts the wrong thing. Sixteen workers make 2,311 claims per second, and only 1,130 of them are unique jobs: the rest are repeat claims of a job already taken, 4,480–4,726 per pass, and each of them is work done twice. With two workers there are 171 unique jobs per second — almost as many as with one: most of the time the second worker takes the same job as the first. The correct form, with SKIP LOCKED in the subquery, scales the same way without a single duplicate.

With no work (a 0 ms sleep) the shape is the same, but the ceiling is different: it is set by the two cores and the fsync at commit, not by the workers.

0 ms of work, jobs per second, bench/pg-queue/throughput.py, block 1:

workersSKIP LOCKEDFOR UPDATEUPDATE + SKIP LOCKED
1216620121442
4418215982480
16415613623929

SKIP LOCKED already hits the machine's limit at four workers — about four thousand jobs per second when each job is its own transaction with an fsync. FOR UPDATE drops as workers are added, from 2,012 to 1,362: waiting on the lock adds context switches, not work. That ceiling is a property of our disk and our two cores and will be different elsewhere; what carries over is that adding workers is useless without SKIP LOCKED and useful with it, up to the point where commits become the limit.

Batches are cheaper than workers

If commits are the ceiling, make fewer of them. The same SKIP LOCKED, four workers, but each claim takes LIMIT 10 or LIMIT 100 rows and deletes them with one DELETE:

3. BATCH SIZE: SKIP LOCKED, 4 WORKERS, NO WORK
----------------------------------------------
4 s per cell, 3 passes; jobs per second, median [range]
  batch   1  jobs/s   3967 [3438-3973]  x1.0 vs batch 1  dups 0  left min 384107
  batch  10  jobs/s  31438 [28588-33102]  x7.9 vs batch 1  dups 0  left min 267590
  batch 100  jobs/s 123125 [113225-123725]  x31.0 vs batch 1  dups 0  left min 1505100

The price of a batch is semantic: the jobs in it commit together, and a worker that dies midway returns all of them to the queue, finished ones included. If the work on a job is idempotent (and with any at-least-once queue it has to be), that is acceptable.

How a worker learns about a new job

An empty queue is the normal state. The worker asks "is there work", hears "no", and has to decide when to ask again. The less often it asks, the longer a job waits; the more often, the more empty queries.

PostgreSQL has LISTEN/NOTIFY for this: in the same transaction that enqueues the job, the producer runs NOTIFY jobs, and a worker that has run LISTEN jobs receives the notification and goes for the job at once.

What NOTIFY promises

language contractPostgreSQL 16, NOTIFY and LISTEN

Four properties, and all four matter for a queue.

Delivery at commit: if a NOTIFY is executed inside a transaction, the notify events are not delivered until and unless the transaction is committed. That is exactly what a queue needs: the notification about a job cannot arrive before the job is visible.

The recipient is whoever is listening now: to each client application that has previously executed LISTEN. Nothing stores notifications for sessions that connect later.

A listener inside a transaction gets the notification only after the transaction ends.

And the limits: the payload must be shorter than 8000 bytes, the notification queue is quite large (8GB in a standard installation), and if it does fill up, transactions calling NOTIFY will fail at commit.

Checked

measured observationbench/pg-queue/contract.py, PostgreSQL 16.15. Blocks 4–9, as the script prints them.
4. NOTIFY IS DELIVERED AT COMMIT, AND NEVER AFTER A ROLLBACK
------------------------------------------------------------
inside the producer's transaction, listener got: []
after COMMIT, listener got: ['committed'] in 0.5 ms
after ROLLBACK, listener got within 1 s: []
5. A NOTIFY WITH NOBODY LISTENING IS NOT KEPT
---------------------------------------------
3 notifications sent, then a session runs LISTEN; it gets within 1 s: []
one more after its LISTEN: ['sent after LISTEN']

Block 5 is the one that matters for the design. A worker that was reconnecting while three jobs were enqueued will get no notifications about them. The jobs are safe — they are in the table — but they will wait until the next poll. So LISTEN/NOTIFY is an accelerator, not a delivery mechanism: polling, however rare, remains mandatory. The LISTEN page advises the same order: commit the LISTEN first, then check the state of the database, and only then rely on notifications. An experiment shows why the order matters:

measured observationbench/pg-queue/delivery.py, block 5, PostgreSQL 16.15.
5. LISTEN ORDER: CHECK THEN LISTEN LOSES A WAKE-UP, LISTEN THEN CHECK DOES NOT
------------------------------------------------------------------------------
check, then LISTEN:
  check found: nothing; a job is enqueued; LISTEN; notifications within 1 s: []
  pending jobs nobody was told about: 1
LISTEN, then check:
  LISTEN; a job is enqueued; check found: job 1; notifications within 1 s: ['jobs']
reconnect: 3 jobs enqueued while disconnected, then LISTEN, then check:
  notifications after reconnect: []; check found: [1, 2, 3]

"Check, then subscribe" loses a job enqueued in between: neither the check nor a notification tells anyone about it. "Subscribe, then check" finds it, and the extra notification is harmless — the worker simply asks the table once more. Hence the order for a worker: a dedicated connection; LISTEN and end the transaction; check the table; wait for a notification with a timeout (1 s in the experiments) and check again; after a reconnect, start over from LISTEN. A notification is a signal to check the table, not the job itself.

6. A LISTENER INSIDE A TRANSACTION GETS NOTHING UNTIL IT ENDS
-------------------------------------------------------------
listener in a transaction, waits 1 s: []
listener after COMMIT: ['while the listener is in a transaction']
7. IDENTICAL NOTIFICATIONS IN ONE TRANSACTION ARE FOLDED
--------------------------------------------------------
sent in one transaction: ['x', 'x', 'x', 'y', 'x']; received: ['x', 'y']
'x' sent in two separate transactions; received: ['x', 'x']

Folding means a notification cannot be used as a job counter: a producer that enqueues a hundred jobs in one transaction with the same NOTIFY jobs wakes a listener once. For a queue this is actually convenient — the worker takes jobs from the table anyway, not from the notifications.

8. PAYLOAD LIMIT
----------------
7999 bytes: ok
8000 bytes: InvalidParameterValue: payload string too long
9. THE NOTIFICATION QUEUE GROWS WHILE A LISTENER SITS IN A TRANSACTION
----------------------------------------------------------------------
queue usage before: 0.000000
after 20000 notifications of 7000 bytes, listener still in its transaction: 0.019073
listener committed and read 20000 notifications; queue usage now: 0.000000

140 MB of notifications took 1.9% of the queue — in practice, the eight gigabytes do not run out. The danger is elsewhere: a listener stuck in a transaction holds back the whole notification queue, which is not cleaned up until that listener leaves its transaction. pg_notification_queue_usage() is the function to watch.

Latency: polling against notification

The producer enqueues 300 jobs with gaps averaging 20 ms, each in its own transaction. Latency is measured from just before the producer's commit to the moment the worker receives the row.

measured observationbench/pg-queue/latency.py, PostgreSQL 16.15. The same sequence of gaps for every mode, three passes of 300 jobs.

One consumer, bench/pg-queue/latency.py, block 1, range over three passes:

modemedian, msp99, msclaim queries per passof them empty
poll every 10 ms5.5–6.011.1–12.2843593–597
poll every 100 ms52.2–54.2100.1–100.7135–13965
poll every 1000 ms570.7–574.5984.7–999.415–168
LISTEN/NOTIFY + a poll every 1 s0.8–0.91.8–3.0601301

With polling, the median latency is about half the interval and p99 is almost the whole interval: a job waits half a period on average and a full period at worst. Shortening the interval means paying in empty queries: with polling every 10 ms, 593–597 of 843 queries came back empty, and that is with a flow of 50 jobs per second. On an empty queue such a worker runs about a hundred queries per second without doing a single job.

LISTEN/NOTIFY achieves a median under a millisecond — faster than any polling interval in the table — at the same load. Its price is in the last column: exactly one empty query per job. The worker gets a notification, takes the job, asks again, hears "no", and waits again. That is 301 empty queries for 300 jobs — fewer than polling every 10 ms, with six to seven times lower latency.

Four consumers on one queue, bench/pg-queue/latency.py, block 2:

modemedian, msclaim queries per passof them empty
poll every 100 ms, 4 consumers28.4–51.9331–370260–263
LISTEN/NOTIFY, 4 consumers0.915041204

A notification goes to every listener on the channel: for each job all four wake up, one gets the job, three run an empty query, and the one that got it runs one more empty query when it comes back for the next. 1,204 empty queries for 300 jobs — four per job. This cost grows linearly with the number of workers, and with dozens of workers on one channel a notification wakes dozens of processes for a single row. With four polling consumers the median was 28.4 ms in the first pass and about 52 in the other two: when the consumers' polls are spread out in time, the queue as a whole is polled more often; when they line up, there is no gain. Neither outcome can be relied on.

The other side: dead rows

language contractPostgreSQL 16, Routine Vacuuming; idle_in_transaction_session_timeout

Every job taken is a DELETE (or a status UPDATE), and in PostgreSQL an UPDATE or DELETE of a row does not immediately remove the old version of the row. VACUUM removes old versions, and only when it is safe: the row version must not be deleted while it is still potentially visible to other transactions.

For an ordinary table this is background noise. For a queue it is the main mode of operation: a constant stream passes through it, and at any moment it can hold orders of magnitude more dead rows than live ones. The documentation also says what prevents the cleanup:

Even when no significant locks are held, an open transaction prevents vacuuming away recently-dead tuples that may be visible only to this transaction; so remaining idle for a long time can contribute to table bloat.

— PostgreSQL 16, idle_in_transaction_session_timeout

That transaction can be working with a different table and need not read from the queue at all. What holds the cleanup horizon back is a snapshot (in the experiment below, a REPEATABLE READ transaction that ran one SELECT) or an assigned transaction number (a model A worker with FOR UPDATE, shown above in "Two execution models"). A READ COMMITTED transaction that only reads and sits idle between queries holds no snapshot between them; our experiments did not measure that case. Replication slots hold the horizon too: in the section on transaction ID wraparound the documentation advises looking for slots where age(xmin) or age(catalog_xmin) is large.

Under load, with and without a long transaction

The producer enqueues 1,000 jobs per second; two consumers take them in batches of up to 10 and delete them. For a minute everything runs normally. Then a neighbouring session opens a REPEATABLE READ transaction, runs one SELECT, and sits idle for three minutes. Then it closes. Autovacuum runs with default settings.

measured observationbench/pg-queue/bloat.py, block 1, PostgreSQL 16.15. Pages per claim — EXPLAIN (ANALYZE, BUFFERS) of the claim query from a fresh session at the end of the window; the median covers every claim query of both consumers in the window.

A selection from the run record, 15 s windows, bench/pg-queue/bloat.py, block 1:

window end, sphaseclaim median, msp99, mspages per claimn_dead_tuptable, MBxmin age
60normal0.200.482541801.72
75long transaction0.511.73326147602.53008
120long transaction2.676.611256599308.511993
180long transaction1.683.74252411995017.124027
240long transaction2.445.63328618006025.61
255closed0.282.5712926025.80
315closed0.210.5725486001.90

What the table shows.

In normal operation there are many dead rows, yet claiming is cheap. By second 60, n_dead_tup is 54,180: autovacuum, with a threshold of "50 rows plus 20% of the table" and a one-minute pause, does not keep up with the flow. But the claim query touches 2–12 pages: the index entries of dead rows are marked and skipped.

With the transaction open, pages per claim grow with its age: 326, 1,256, 2,524, 3,286 — by the end of the third minute, hundreds of times more than in normal operation. In the windows with the transaction open, the median claim was 0.51 to 2.67 ms versus 0.20–0.24 in normal operation, and it did not rise steadily: the 2.67 ms peak came at second 120, then the median dropped as low as 1.28 and by the end climbed back to 2.44–2.45; p99 reached 6.61 ms. The queue kept up: the backlog was 0–10 jobs. At this pace and with this flow, claims became several times slower but did not fail; with a longer transaction or a faster flow the slope is the same and the values are larger, as shown below.

Autovacuum ran but did not help. While the transaction was open, autovacuum ran three times — the counter went from 1 to 4. The first run, within 15 seconds of the transaction opening, removed the rows that had died before it: n_dead_tup fell from 54,180 to 14,760. After that the counter only grew, reaching 180,060 by the end; the next two runs did not bring it down, and pages per claim did not drop either: dead rows that the old snapshot can still see may not be removed by VACUUM.

Close the transaction, and within one window it is back to normal: 12 pages, 0.28 ms. This happens before any VACUUM. (In the last two windows the measurement showed 254 pages per claim again, at a median of 0.21–0.25 ms; the run does not show the cause of that jump.) Claims get cheaper before VACUUM because of how the B-tree works:

implementation detail · PostgreSQL 16.15src/backend/access/nbtree/README, tag REL_16_15, section Simple deletion

An index scan that runs into a row dead to all open transactions marks that row's index entry, and later scans no longer go to the table for it. While the old snapshot is open, "dead to all" does not hold, no marks are set, and every claim goes to the table to check every dead row that precedes the first live job in the index. Hence the linear growth: a query with ORDER BY id LIMIT 10 starts at the oldest end of the index, and that is where everything taken during the transaction lies.

The space did not come back at once. The table grew to 25.8 MB and stayed at that size until a later autovacuum found an empty tail at the end of the file and truncated it, shrinking the table to 1.9 MB. The index stayed at 4.0 MB: a B-tree recycles empty pages for reuse rather than giving them back to the operating system.

An empty queue after a million jobs

The same effect in its pure form: put N jobs into the queue, open an old snapshot, drain the queue completely in batches of 100, then ask the empty queue "is there work". Autovacuum is off for the table.

measured observationbench/pg-queue/bloat.py, block 2, PostgreSQL 16.15. Median of twenty claim queries.

An empty queue after N jobs, bench/pg-queue/bloat.py, block 2:

Nold snapshot open: claim, mspages per claimsnapshot closed: claim, mspagesafter VACUUM, ms
1000004.6320940.262750.11
100000090.71209172.1427350.10

The queue is empty, and the query "give me a job" takes 91 ms and reads 20,917 pages — more than 160 MB of pages for every idle poll. A worker polling such a queue every 100 ms spends almost all its time asking. VACUUM is honest about it:

    VACUUM VERBOSE: tuples: 0 removed, 1000000 remain, 1000000 are dead but not yet removable

Close the snapshot, and the very first query reads 23,650 pages and sets the marks; the following ones cost 2.14 ms: all that is left is walking the index pages that hold the marked entries. VACUUM removes those too, and then a claim costs 0.10 ms. TRUNCATE on the same table took 31.8 ms and gave back all the space at once — but only because the queue was empty.

DELETE or a status UPDATE

A job that has been taken can be deleted, or kept with status = 'done'. The second looks gentler — the history is at hand — but it costs the table more:

measured observationbench/pg-queue/bloat.py, block 3, PostgreSQL 16.15. 100,000 jobs, autovacuum off.
3. DELETE VERSUS UPDATE STATUS: WHAT 100000 JOBS LEAVE BEHIND
-------------------------------------------------------------
100000 jobs, taken in batches of 100 with SKIP LOCKED; autovacuum off for the table
DELETE:
  before: table 14.2 MB, jobs_pending 2.2 MB, jobs_pkey 2.2 MB
  after:  table 14.2 MB, jobs_pending 2.2 MB, jobs_pkey 2.2 MB
  n_live_tup 0, n_dead_tup 100000, updates 0, of them HOT 0
UPDATE:
  before: table 14.2 MB, jobs_pending 2.2 MB, jobs_pkey 2.2 MB
  after:  table 26.5 MB, jobs_pending 2.2 MB, jobs_pkey 4.3 MB
  n_live_tup 100000, n_dead_tup 100000, updates 100000, of them HOT 0

DELETE left the same 14.2 MB, but every row in it is dead and the space will be reused after VACUUM. UPDATE left 100,000 live done rows and 100,000 dead versions: the table is almost twice as large, and so is the primary key. In our schema not one update was HOT, and the first condition in the documentation is enough to explain it: HOT is possible only if the update does not modify any columns referenced by the table's indexes, but status is part of the partial index's condition. The second condition is room for the new version on the same page; the table was filled with the default fillfactor, but we did not check separately whether there was room. For that condition the documentation suggests decreasing a table's fillfactor. In a schema without an index on the status and with spare room on the pages the result may differ — we did not measure such a schema. The sizes here are specific to this table of 100,000 short rows. What carries over is that UPDATE leaves both a live and a dead version, while DELETE leaves one dead version. If job history is needed, it is cheaper to write it to a separate table and keep the queue short.

What to tune

  1. A partial index on pending jobs — CREATE INDEX … ON jobs (id) WHERE status = 'pending'. It holds no done rows, and after VACUUM on an empty queue not a single entry remains in it, although the index file keeps its size. The outbox article covers the same technique.
  2. Bound the lifetime of transactions in the same database. idle_in_transaction_session_timeout is off by default; turn it on for roles that have no business sitting in a transaction, and watch age(backend_xmin) in pg_stat_activity. In our measurement three minutes of an open snapshot made a claim several times more expensive, and a million jobs under an old snapshot pushed an idle poll to 91 ms.
  3. Vacuum the queue table more often than the rest. The default threshold is 50 rows plus 20% of reltuples, and it can be set per table with storage parameters: ALTER TABLE jobs SET (autovacuum_vacuum_scale_factor = 0, autovacuum_vacuum_threshold = …). The pause between rounds (autovacuum_naptime, one minute) is server-wide.
  4. Delete rather than mark; claim in batches. Batches of 10 gave 7.9 times as many jobs per second as single-job claims, with ten times fewer commits.
  5. For very long tails, time-based partitions. TRUNCATE and dropping a partition give space back immediately, and according to the documentation such commands entirely avoid the VACUUM overhead caused by a bulk DELETE. A partition can be dropped only once no unfinished jobs remain in it.
  6. Long jobs on a lease, not under an open transaction. A lease with locked_until, an attempt counter and an owner token; completion and the external effect check the token; after the attempt limit, status failed. A lease does not help if the effect's receiver checks neither the token nor an idempotency key: then a job with an expired lease can run twice, as in the experiment with completion by id alone.

What to monitor in production

This list follows from the mechanisms covered in this article: each metric matches a failure shown above and a place in PostgreSQL where it can be read.

whatwhere fromwhich failure it shows
backlog and age of the oldest jobcount(*) and min(created_at) over status = 'pending' (a creation-time column has to be added)workers fall behind or stall
claim query timetimed in the workerdead rows piling up before the first live job
attempts and jobs in failedthe attempts and status columnspoison jobs, an unavailable receiver
expired leasesstatus = 'running' AND locked_until < now()stuck or dead workers
transaction ageage(backend_xid), age(backend_xmin) in pg_stat_activitythe cleanup horizon held back
dead rows and sizesn_dead_tup, last_autovacuum in pg_stat_user_tables, pg_relation_size of the table and indexescleanup cannot keep up or cannot proceed
notification queuepg_notification_queue_usage()a listener stuck in a transaction
empty wake-upsa counter in the workerthe cost of polling or of waking every listener

Up to what scale this is reasonable

This is a conclusion drawn from our numbers, not a rule. On two cores and an ordinary disk, a single queue table with SKIP LOCKED handled about 4,000 jobs per second when each job is its own transaction, and 31,438 with batches of 10. For jobs that wait on the network it scaled almost linearly to 16 workers. For most services that is plenty, and then the main argument — a transaction shared with the data — wins: the job is enqueued atomically with the record it is about.

The limit lies not where speed runs out but where your control over the database does:

  • If the same database hosts long transactions you do not control — reports, analytics, manual sessions — the queue will degrade every time they run. No index fixes that; what fixes it is having no such transactions in this database, or keeping them short.
  • If one event is needed by several independent consumers. A queue row is taken by one worker and deleted. Handing it to three consumer groups means three queues, or keeping the row until everyone has read it — and then the dead rows become a live log.
  • If you need history and rereading from an arbitrary point — that is a property of a log, not of a queue that deletes.
  • If the flow is high enough that commits to a single table become the bottleneck. Where that happens depends on the disk and on what else the database writes; on our machine, about 4,000 single-job commits per second. Batches move the boundary but do not remove it.

The same, summarized by requirement, with no jobs-per-second thresholds:

requirementqueue in PostgreSQLbroker or log
the job is atomic with the database writeone transactionneeds an outbox
one executor per jobSKIP LOCKEDa consumer group
several independent receiversa queue for eachbuilt in
reread from an arbitrary pointno: rows are deletedbuilt in, within retention
long transactions in the same databaseclaiming degradesno effect
a single external effectan idempotency key at the receiverthe same

The last row is the same in both columns: neither a queue nor a broker makes an external effect happen once on its own. If the requirements point to the right column, you need a broker, and then the combination of a database write and a broker message brings back the dual-write problem that the transaction outbox solves — the same queue-like table, only with a single consumer, the relay.

Reproducing the numbers

Every script brings up its own PostgreSQL cluster in a temporary directory, listens only on a unix socket on port 55432, and removes the cluster after the run.

cd bench/pg-queue
./run.sh                 # all five scripts
./run.sh latency bloat   # only the named ones

You need PostgreSQL 16 binaries (PGBIN, by default /usr/lib/postgresql/16/bin) and Python 3 with venv; the script installs psycopg 3 into a .venv next to it. The run records are in bench/pg-queue/runs/: each one's header lists the server and client versions and the settings the numbers depend on.

The published run: PostgreSQL 16.15 with default settings (fsync = on, synchronous_commit = on, shared_buffers = 128MB, autovacuum on), psycopg 3.3.9 with libpq 18, Python 3.13.16, two Intel Xeon 2.30GHz cores (the delivery.py experiments, which measure no timings, ran on 2.10GHz), November 2026. Every speed measurement is ultimately bound by fsync and the two cores; on another machine what carries over is the shape of the curves and the ratios within an experiment, not the absolute values.

What measured this

The numbers in this article come from these scripts. Each one opens from here, together with the record of the run: what it was measured on, what came out, and with what spread.

Take to work

  • When several workers claim jobs, put FOR UPDATE SKIP LOCKED in the statement that selects the job — the SELECT or the subquery of an UPDATE: without it workers wait for each other or two of them get the same job. Count the queue and run business checks with a plain SELECT.
  • Expect a job to run twice: a crash after an external effect and before the commit returns it to the queue. Making the effect happen once takes an idempotency key at the receiver, and long jobs are better run on a lease with an owner token than under an open transaction.
  • Treat LISTEN/NOTIFY as an accelerator, not as delivery: first LISTEN, then check the table, and the same after every reconnect; a notification sent before the subscription is not stored. Keep polling, even if only once a second, as a safety net.
  • Keep long transactions out of the queue's database: turn on idle_in_transaction_session_timeout and watch age(backend_xmin) and age(backend_xid). While a transaction holding a snapshot or a transaction number is open, every claim walks through all the dead rows accumulated since it began.
  • Delete taken jobs and claim them in batches, and write history to a separate table: UPDATE status = 'done' leaves both a live and a dead version of the row — in our schema the table grew almost twofold.

Common misconceptions

Claim

“SKIP LOCKED is just a way to avoid waiting; it shows the same data”

Actually

It does not show all of the data. The documentation says so outright: Skipping locked rows provides an inconsistent view of the data, so this is not suitable for general purpose work. In the measurement a session that asked for “all jobs” with SKIP LOCKED got 4 rows out of the 10 that exist — six were held by two other sessions. For claiming a job that is right; for counting the queue or checking “is there a job for this order” it is silently wrong.

Claim

“UPDATE … WHERE id = (SELECT … LIMIT 1) is one statement, so one worker gets the job”

Actually

The subquery runs once, with the snapshot from the start of the statement. The second worker waits for the first to commit and rechecks only the outer condition id = 1 — which still holds. In the measurement both sessions got job 1, while the table held a single running row. Under load with 16 workers and 5 ms of work, about half of all claims were repeats. The fix is FOR UPDATE SKIP LOCKED in the subquery.

Claim

“With SKIP LOCKED every job runs exactly once”

Actually

SKIP LOCKED keeps two workers from holding the same row at the same time — and that is all. A rollback returns the job to the queue but does not undo what the worker did outside the database. In the experiment a worker performed an external effect and was killed before COMMIT; a second worker took the job, and a receiver without an idempotency key recorded the effect twice. With a unique key on job_id at the receiver, once. A lease is no different: a late owner whose lease expired sends its effect, and only a receiver that checks the token can stop it.

Claim

“More workers, more jobs per second”

Actually

Only if the workers do not wait for each other. With FOR UPDATE and no SKIP LOCKED, with 5 ms jobs in the measurement one worker managed 170 jobs per second and sixteen managed 164: they all queue behind the first row. With no work, FOR UPDATE even dropped as workers were added — from 2,012 to 1,362. With SKIP LOCKED, 16 workers reached 2,390 — 14.4 times as many as one.

Claim

“With LISTEN/NOTIFY you no longer need to poll”

Actually

A notification goes only to those listening at commit time, and it is not stored. In the measurement a new session received none of three notifications sent before its LISTEN — not one in a second of waiting. A worker that was reconnecting misses everything sent meanwhile, and those jobs sit in the table until the next poll. So polling stays, just less frequent: in the measurement, once a second.

Claim

“Autovacuum removes dead rows, so you don't need to think about them”

Actually

Autovacuum removes only rows that no transaction can see anymore. While a transaction with an old snapshot or an assigned transaction number is open in the same database — for example, a worker holding a job under FOR UPDATE — it runs but does not help: in the measurement, during three minutes of an open REPEATABLE READ snapshot autovacuum ran three times, n_dead_tup only grew after the first run, and the claim query still went from a handful of pages to 3,286. After a million jobs under an old snapshot an empty queue took 91 ms to answer “is there work”, and VACUUM VERBOSE reported 1000000 are dead but not yet removable.

Claim

“Marking jobs done is cheaper than deleting them: deletion is heavy”

Actually

In PostgreSQL an UPDATE creates a new version of the row and leaves the old one dead. In the measurement on our schema (the status is part of a partial index's condition, default fillfactor) 100,000 jobs marked done left 100,000 live rows and 100,000 dead ones: the table grew from 14.2 to 26.5 MB, the primary key from 2.2 to 4.3 MB, and not one update was HOT. DELETE left the same 14.2 MB, all of it reusable after VACUUM.

Knowledge check

Question 1 of 5

Four workers claim jobs with SELECT … ORDER BY id LIMIT 1 FOR UPDATE and keep the transaction open while they work. A job takes 5 ms. What happens if you add twelve more workers?

Sources & further reading

10 SOURCES

  1. PostgreSQL 16 — SELECT, The Locking ClauseOfficial documentation. The contract the whole queue rests on: «To prevent the operation from waiting for other transactions to commit, use either the NOWAIT or SKIP LOCKED option», «With SKIP LOCKED, any selected rows that cannot be immediately locked are skipped», and the key caveat: «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». Also: «If a LIMIT is used, locking stops once enough rows have been returned to satisfy the limit».https://www.postgresql.org/docs/16/sql-select.html
  2. PostgreSQL 16 — Explicit Locking, Row-Level LocksOfficial documentation. What FOR UPDATE without SKIP LOCKED does: «other transactions that attempt UPDATE, DELETE, SELECT FOR UPDATE, SELECT FOR NO KEY UPDATE, SELECT FOR SHARE or SELECT FOR KEY SHARE of these rows will be blocked until the current transaction ends; conversely, SELECT FOR UPDATE will wait for a concurrent transaction that has run any of those commands on the same row, and will then lock and return the updated row (or no row, if the row was deleted)».https://www.postgresql.org/docs/16/explicit-locking.html
  3. PostgreSQL 16 — NOTIFYOfficial documentation. Who receives a notification: «The NOTIFY command sends a notification event together with an optional "payload" string to each client application that has previously executed LISTEN channel for the specified channel name in the current database». When: «if a NOTIFY is executed inside a transaction, the notify events are not delivered until and unless the transaction is committed», and to a listener that is inside a transaction it will «not be delivered to its connected client until just after the transaction is completed». Folding: «If the same channel name is signaled multiple times with identical payload strings within the same transaction, only one instance of the notification event is delivered to listeners». Limits: the payload «must be shorter than 8000 bytes»; the queue is «quite large (8GB in a standard installation)», «If this queue becomes full, transactions calling NOTIFY will fail at commit», and «no cleanup can take place if a session executes LISTEN and then enters a transaction for a very long time».https://www.postgresql.org/docs/16/sql-notify.html
  4. PostgreSQL 16 — LISTENOfficial documentation. «LISTEN takes effect at transaction commit», and what a new listener will get: «the session will receive all events committed after an instant during the transaction's commit step». Hence the page's advice: commit the LISTEN first, then inspect the database state, and rely on notifications from then on.https://www.postgresql.org/docs/16/sql-listen.html
  5. PostgreSQL 16 — Routine VacuumingOfficial documentation. Why a queue table accumulates dead rows: «In PostgreSQL, an UPDATE or DELETE of a row does not immediately remove the old version of the row» and «the row version must not be deleted while it is still potentially visible to other transactions». What VACUUM gives back: plain VACUUM «will not return the space to the operating system, except in the special case where one or more pages at the end of a table become entirely free». The autovacuum threshold: «vacuum threshold = vacuum base threshold + vacuum scale factor * number of tuples». Replication slots hold the cleanup horizon too — in the section on transaction ID wraparound: «Use pg_replication_slots to find slots where age(xmin) or age(catalog_xmin) is large». And on TRUNCATE: «TRUNCATE removes the entire content of the table immediately, without requiring a subsequent VACUUM or VACUUM FULL to reclaim the now-unused disk space».https://www.postgresql.org/docs/16/routine-vacuuming.html
  6. PostgreSQL 16 — Client Connection Defaults, idle_in_transaction_session_timeoutOfficial documentation. The documentation ties an open transaction to table bloat directly: «Even when no significant locks are held, an open transaction prevents vacuuming away recently-dead tuples that may be visible only to this transaction; so remaining idle for a long time can contribute to table bloat». The default: «A value of zero (the default) disables the timeout».https://www.postgresql.org/docs/16/runtime-config-client.html
  7. PostgreSQL 16 — Automatic Vacuuming (parameters)Official documentation. The defaults the measurement ran with: autovacuum_naptime — «The default is one minute (1min)», autovacuum_vacuum_threshold — «The default is 50 tuples», autovacuum_vacuum_scale_factor — «The default is 0.2 (20% of table size)»; for the threshold and the scale factor «the setting can be overridden for individual tables by changing table storage parameters».https://www.postgresql.org/docs/16/runtime-config-autovacuum.html
  8. PostgreSQL 16 — Table Partitioning, OverviewOfficial documentation. «Dropping an individual partition using DROP TABLE, or doing ALTER TABLE DETACH PARTITION, is far faster than a bulk operation. These commands also entirely avoid the VACUUM overhead caused by a bulk DELETE».https://www.postgresql.org/docs/16/ddl-partitioning.html
  9. PostgreSQL 16 — Heap-Only Tuples (HOT)Official documentation. The conditions for a HOT update, without which every row update adds index entries: «The update does not modify any columns referenced by the table's indexes, not including summarizing indexes» and «There is sufficient free space on the page containing the old row for the updated row». On the second condition, the same page: «You can increase the likelihood of sufficient page space for HOT updates by decreasing a table's fillfactor».https://www.postgresql.org/docs/16/storage-hot.html
  10. postgres/src/backend/access/nbtree/README, tag REL_16_15 — Simple deletionSource code. Why a claim gets cheap right after the long transaction closes, before any VACUUM: «If a process visits a heap tuple and finds that it's dead and removable (ie, dead to all open transactions, not only that process), then we can return to the index and mark the corresponding index entry "known dead", allowing subsequent index scans to skip visiting the heap tuple». While a transaction with an old snapshot is open, the condition «dead to all open transactions» does not hold, and no marks are set. This is how the version 16 B-tree works, not a promise of the documentation.https://github.com/postgres/postgres/blob/REL_16_15/src/backend/access/nbtree/README