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 job queue can live right inside PostgreSQL: a job is a row in a table, and taking a job means holding that row while you work on it.
- The key words are
SKIP LOCKED: "skip the ones that are taken". Without them workers line up one behind another, and in our measurement sixteen worked no faster than one. - Taking a job once is not the same as doing it once. A worker that managed to send something out and then crashed returns the job, and it gets done again.
- Instead of asking about new jobs every few milliseconds, a worker can listen for a bell —
LISTEN/NOTIFY. But the bell does not ring twice: anyone who was not there misses it. So first stand by the bell, then look at the rail. - Finished jobs do not vanish at once; they stay in the table until the cleaner —
VACUUM— removes them. One long transaction nearby prevents the cleaner from cleaning, and each next job costs more to take.
A kitchen and tickets on a rail
Picture a restaurant kitchen. Waiters clip order tickets onto a rail, and cooks take them one at a time and cook. The rail is the table, a ticket is a row, a cook is a worker that does jobs.
A cook who has taken a ticket holds it in hand while cooking. That is the row lock: while the ticket is in someone's hand, no other cook will take it. If the cook drops the ticket — say, leaves the kitchen in the middle of the job — the ticket goes back onto the rail by itself and the next cook takes it. In the database, a transaction rollback does this.
Skip the tickets that are taken
The simplest rule: each cook walks up to the rail and takes the first
ticket. If the first one is already in a colleague's hand, the cook stands and
waits until the colleague is done. That is how plain FOR UPDATE works.
The result is that one cook is always cooking and the rest are standing around. In the measurement for this article a job took 5 ms, and one cook did 170 jobs per second while sixteen did 164. More cooks, same speed.
SKIP LOCKED means "if the first ticket is taken, take the next free one". The
same sixteen cooks did 2,390 jobs per second — more than fourteen times as many
as one.
This is what it looks like in a worker written in Python:
import psycopg
with psycopg.connect("dbname=postgres") as conn:
while True:
with conn.transaction():
row = conn.execute(
"SELECT id, payload FROM jobs WHERE status = 'pending' "
"ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED"
).fetchone()
if row is None:
break
print("cooking order", row[0])
conn.execute("DELETE FROM jobs WHERE id = %s", (row[0],))Ticket taken, order cooked, ticket thrown away — all in one transaction.
Two cooks, one ticket
There is another rule: the cook does not hold on to the ticket but writes "mine" on it, clips it back, and then cooks. It sounds sensible. But suppose the cook glances at the number of the first ticket, and on the way to the rail a second cook glances at the same one: both will write "mine" on the same ticket, and the dish gets cooked twice. The ticket carries a single mark, and nothing on it shows the problem.
In the measurement that is exactly what happened: two sessions got the same job,
number 1. Under load with sixteen workers about half of all claims were
repeats. The fix is the same words: glance at the number with SKIP LOCKED.
The dish is with the guest, and the ticket is back
A cook took a ticket and cooked the dish, a waiter carried it to the guest — and then the cook felt ill and left the kitchen without throwing the ticket away. The ticket went back onto the rail, as it should, and the next cook made the same dish again. The guest got two.
This is not the rail's fault: it honestly returned a ticket nobody closed. In the measurement that is exactly what happened: a worker performed an "external action" and was stopped before the end of its transaction, a second worker took the job, and the action happened twice. Only the side that receives the dishes can prevent this: if the pass writes down the ticket number and does not send out a second dish with the same number, the guest gets one. In the database this is called an idempotency key at the receiver.
For long dishes there is a second technique: instead of holding the ticket for a whole hour, hang a tag on it — "Ivan is cooking, until noon, second attempt". If Ivan disappears and the time runs out, another cook takes the ticket with a tag of their own. And if Ivan comes back later, his tag is no longer the current one, and he cannot close the ticket — in the article's experiment a late worker with an old tag was refused. But the pass turns him away only if it checks tags too.
A bell instead of rounds
While there are no tickets, a cook can walk up to the rail every few seconds and check. The more often the cook checks, the sooner a new ticket is noticed — and the more walks are wasted. That is polling the table: with polling every 100 ms, half the jobs waited longer than about 52 ms and half less.
You can hang a bell instead: a waiter clips a ticket, rings, and the cook goes
to the rail at once. That is LISTEN/NOTIFY. In the measurement a job waited
less than a millisecond.
The bell has two properties worth remembering.
- It rings only after the ticket is clipped. If the waiter changes their mind and never clips the ticket, there is no ring at all. In the database, this means the notification is delivered at commit and not at all on rollback.
- The bell does not ring twice. If the cook was out of the kitchen at that moment, the ring is missed, and nobody repeats it. The ticket is still on the rail. So the rounds stay, but rare ones — once a second, in case a ring was missed.
- First stand by the bell, then look at the rail. Do it the other way round, and a ticket clipped in between is noticed by neither the glance nor the bell. In the article's experiment that is exactly what happened: with "look, then stand by the bell" the job was left lying there, with the reverse order it was found at once. The same applies after every return to the kitchen.
And one more thing: every cook hears the bell. Four cooks means four people walk to the rail for one ticket, and three come back empty-handed.
Used tickets and the inspector
The most surprising part is what happens to tickets that have been taken. The
cook throws the ticket away, but a crossed-out stub stays on the rail. A
cleaner — VACUUM — removes the stubs, not right away but from time to time.
While there are few stubs, cooks barely notice them: a crossed-out stub carries a mark saying "empty, don't look", and the cook skips past without reading it.
Now an inspector walks into the kitchen and says: "Throw nothing away until I am done — I may need any ticket that was on the rail when I came in." That is a long transaction in the same database — a report, say, or a cook who has been holding one ticket in hand for half an hour. The cleaner is no longer allowed to remove a single stub, and the cooks are no longer allowed to mark stubs "empty": for the inspector that ticket is not empty yet. So to find a fresh ticket, every cook has to leaf through every stub that has piled up since the inspector arrived.
In the measurement — a thousand jobs per second and three minutes of such an inspector — the database had to go through 3,286 pages to take a job, instead of a few. The inspector left — and fifteen seconds later it was 12 pages again: the stubs got their "empty" marks. And if a million jobs went through under such an inspector, even the question "is there anything?" put to an empty rail took 91 ms.
What follows
- When several workers take jobs, put
SKIP LOCKEDin the query that selects the job — both in a plainSELECTand in the subquery inside anUPDATE. Count the jobs in the queue with an ordinary query, without it. - Expect a job to be done twice and guard against it at the receiver: an idempotency key at the pass. Run long jobs on a lease tag rather than holding the ticket in hand.
- Hang the bell (
LISTEN/NOTIFY) for speed, and keep the rounds (polling) for reliability; firstLISTEN, then check the table. - Keep long inspectors out of the kitchen: no open transactions hanging around
in the queue's database; cap them with
idle_in_transaction_session_timeout. - Throw finished tickets away rather than marking them "done": a marked ticket is both a live row and a dead one, and in our measurement the table nearly doubled in size.
The detailed version — with query output, measurement tables, how the index skips dead rows, and when a queue in the database is no longer enough — is in the "In depth" tab.
TL;DR
- A queue on PostgreSQL is a table and a
SELECT … FOR UPDATE SKIP LOCKEDquery: 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 LOCKEDbut from an idempotency key at the receiver. - Without
SKIP LOCKED, workers line up behind a single row. With a 5 ms job, 16 workers usingFOR UPDATEin our measurement got through as many jobs as one — 164 per second versus 170; withSKIP 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/NOTIFYremoves 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 firstLISTEN, then check the table, and keep polling as the safety net.- Every job removed with
DELETEorUPDATEleaves a dead row version. While a transaction with an old snapshot or an assigned transaction number is open in the database (in the experiments, aREPEATABLE READsnapshot and a worker holding a job underFOR UPDATE), VACUUM may not remove it. In our schema, with aREPEATABLE READsnapshot 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:
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:
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
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.
"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:
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
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)
.
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.
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:
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:
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
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:
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:
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.
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.
5 ms of work per job, jobs per second, bench/pg-queue/throughput.py, block 2:
| workers | SKIP LOCKED | FOR UPDATE | UPDATE, naive: claims | of them unique | UPDATE + SKIP LOCKED |
|---|---|---|---|---|---|
| 1 | 166 | 170 | 162 | 162 | 159 |
| 2 | 328 | 167 | 321 | 171 | 319 |
| 4 | 643 | 163 | 622 | 316 | 610 |
| 8 | 1282 | 166 | 1244 | 730 | 1178 |
| 16 | 2390 | 164 | 2311 | 1130 | 2174 |
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:
| workers | SKIP LOCKED | FOR UPDATE | UPDATE + SKIP LOCKED |
|---|---|---|---|
| 1 | 2166 | 2012 | 1442 |
| 4 | 4182 | 1598 | 2480 |
| 16 | 4156 | 1362 | 3929 |
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
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
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:
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.
One consumer, bench/pg-queue/latency.py, block 1, range over three passes:
| mode | median, ms | p99, ms | claim queries per pass | of them empty |
|---|---|---|---|---|
| poll every 10 ms | 5.5–6.0 | 11.1–12.2 | 843 | 593–597 |
| poll every 100 ms | 52.2–54.2 | 100.1–100.7 | 135–139 | 65 |
| poll every 1000 ms | 570.7–574.5 | 984.7–999.4 | 15–16 | 8 |
LISTEN/NOTIFY + a poll every 1 s | 0.8–0.9 | 1.8–3.0 | 601 | 301 |
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:
| mode | median, ms | claim queries per pass | of them empty |
|---|---|---|---|
| poll every 100 ms, 4 consumers | 28.4–51.9 | 331–370 | 260–263 |
LISTEN/NOTIFY, 4 consumers | 0.9 | 1504 | 1204 |
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
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.
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.
A selection from the run record, 15 s windows, bench/pg-queue/bloat.py, block 1:
| window end, s | phase | claim median, ms | p99, ms | pages per claim | n_dead_tup | table, MB | xmin age |
|---|---|---|---|---|---|---|---|
| 60 | normal | 0.20 | 0.48 | 2 | 54180 | 1.7 | 2 |
| 75 | long transaction | 0.51 | 1.73 | 326 | 14760 | 2.5 | 3008 |
| 120 | long transaction | 2.67 | 6.61 | 1256 | 59930 | 8.5 | 11993 |
| 180 | long transaction | 1.68 | 3.74 | 2524 | 119950 | 17.1 | 24027 |
| 240 | long transaction | 2.44 | 5.63 | 3286 | 180060 | 25.6 | 1 |
| 255 | closed | 0.28 | 2.57 | 12 | 9260 | 25.8 | 0 |
| 315 | closed | 0.21 | 0.57 | 254 | 8600 | 1.9 | 0 |
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:
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.
An empty queue after N jobs, bench/pg-queue/bloat.py, block 2:
| N | old snapshot open: claim, ms | pages per claim | snapshot closed: claim, ms | pages | after VACUUM, ms |
|---|---|---|---|---|---|
| 100000 | 4.63 | 2094 | 0.26 | 275 | 0.11 |
| 1000000 | 90.71 | 20917 | 2.14 | 2735 | 0.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:
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
- A partial index on pending jobs —
CREATE INDEX … ON jobs (id) WHERE status = 'pending'. It holds nodonerows, 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. - Bound the lifetime of transactions in the same database.
idle_in_transaction_session_timeoutis off by default; turn it on for roles that have no business sitting in a transaction, and watchage(backend_xmin)inpg_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. - 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. - 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.
- For very long tails, time-based partitions.
TRUNCATEand dropping a partition give space back immediately, and according to the documentation such commandsentirely avoid the VACUUM overhead caused by a bulk DELETE
. A partition can be dropped only once no unfinished jobs remain in it. - 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, statusfailed. 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 byidalone.
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.
| what | where from | which failure it shows |
|---|---|---|
| backlog and age of the oldest job | count(*) and min(created_at) over status = 'pending' (a creation-time column has to be added) | workers fall behind or stall |
| claim query time | timed in the worker | dead rows piling up before the first live job |
attempts and jobs in failed | the attempts and status columns | poison jobs, an unavailable receiver |
| expired leases | status = 'running' AND locked_until < now() | stuck or dead workers |
| transaction age | age(backend_xid), age(backend_xmin) in pg_stat_activity | the cleanup horizon held back |
| dead rows and sizes | n_dead_tup, last_autovacuum in pg_stat_user_tables, pg_relation_size of the table and indexes | cleanup cannot keep up or cannot proceed |
| notification queue | pg_notification_queue_usage() | a listener stuck in a transaction |
| empty wake-ups | a counter in the worker | the 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:
| requirement | queue in PostgreSQL | broker or log |
|---|---|---|
| the job is atomic with the database write | one transaction | needs an outbox |
| one executor per job | SKIP LOCKED | a consumer group |
| several independent receivers | a queue for each | built in |
| reread from an arbitrary point | no: rows are deleted | built in, within retention |
| long transactions in the same database | claiming degrades | no effect |
| a single external effect | an idempotency key at the receiver | the 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.
This is neither a retelling nor a separate text: everything below is taken from the article itself — its own summary, the section headings, the “actually” column and the version table. Which is why these theses cannot drift from the article.
The gist
- A queue on PostgreSQL is a table and a
SELECT … FOR UPDATE SKIP LOCKEDquery: 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 LOCKEDbut from an idempotency key at the receiver. - Without
SKIP LOCKED, workers line up behind a single row. With a 5 ms job, 16 workers usingFOR UPDATEin our measurement got through as many jobs as one — 164 per second versus 170; withSKIP 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/NOTIFYremoves 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 firstLISTEN, then check the table, and keep polling as the safety net.- Every job removed with
DELETEorUPDATEleaves a dead row version. While a transaction with an old snapshot or an assigned transaction number is open in the database (in the experiments, aREPEATABLE READsnapshot and a worker holding a job underFOR UPDATE), VACUUM may not remove it. In our schema, with aREPEATABLE READsnapshot 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.
In fact
- 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 LOCKEDgot 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. - 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 singlerunningrow. Under load with 16 workers and 5 ms of work, about half of all claims were repeats. The fix isFOR UPDATE SKIP LOCKEDin the subquery. SKIP LOCKEDkeeps 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 beforeCOMMIT; a second worker took the job, and a receiver without an idempotency key recorded the effect twice. With a unique key onjob_idat 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.- Only if the workers do not wait for each other. With
FOR UPDATEand noSKIP 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 UPDATEeven dropped as workers were added — from 2,012 to 1,362. WithSKIP LOCKED, 16 workers reached 2,390 — 14.4 times as many as one. - 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. - 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 openREPEATABLE READsnapshot autovacuum ran three times,n_dead_tuponly 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”, andVACUUM VERBOSEreported1000000 are dead but not yet removable. - In PostgreSQL an
UPDATEcreates 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, defaultfillfactor) 100,000 jobs markeddoneleft 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.DELETEleft the same 14.2 MB, all of it reusable after VACUUM.
What is covered
- Why know this?
- The model: a job is a row, taking a job is locking a row
- What SKIP LOCKED promises
- Without SKIP LOCKED, workers wait for each other
- Claiming with UPDATE: one job, two workers
- One claim is not one execution
- How many jobs per second
- How a worker learns about a new job
- The other side: dead rows
- What to tune
- Up to what scale this is reasonable
- Reproducing the numbers
- What measured this
Take to work
- When several workers claim jobs, put
FOR UPDATE SKIP LOCKEDin the statement that selects the job — theSELECTor the subquery of anUPDATE: without it workers wait for each other or two of them get the same job. Count the queue and run business checks with a plainSELECT. - 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/NOTIFYas an accelerator, not as delivery: firstLISTEN, 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_timeoutand watchage(backend_xmin)andage(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
“SKIP LOCKED is just a way to avoid waiting; it shows the same data”
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.
“UPDATE … WHERE id = (SELECT … LIMIT 1) is one statement, so one worker gets the job”
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.
“With SKIP LOCKED every job runs exactly once”
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.
“More workers, more jobs per second”
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.
“With LISTEN/NOTIFY you no longer need to poll”
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.
“Autovacuum removes dead rows, so you don't need to think about them”
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.
“Marking jobs done is cheaper than deleting them: deletion is heavy”
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
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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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