Writing · Postgres, performance, queues

Adding workers made my Postgres queue 5× slower

Four workers did 1,638 jobs a second. Eight did 306. What pg_stat_activity showed, and the three changes that took eight workers to 2,152.

pg-lease-queue is a job queue I wrote on plain Postgres. Workers claim jobs with FOR UPDATE SKIP LOCKED, hold them on a lease they keep renewing, and can only finish a job while they hold its current lease token. Before calling it done I wrote a benchmark: start N worker processes, insert 20,000 no-op jobs in one transaction, and time how long it takes until the last one is done. No-op jobs measure the queue’s own overhead and nothing else.

The first run looked healthy up to four workers. Then it didn’t.

Throughput of the first version
jobs per second05001,0001,5002,00092211,37821,63843068worker processes

20,000 no-op jobs, 16 in flight per worker process, Postgres 16 on the same 2-core laptop. One run per setting.

Show the numbers as a table
Throughput of the first version
worker processesFirst version (jobs/s)
1922
21,378
41,638
8306

Going from four workers to eight cut throughput by a factor of five. A flat line would have meant a bottleneck: some shared resource running at its limit. A line that falls means the workers were actively making each other slower.

Measure before guessing

The obvious suspect is contention on the head of the queue, every worker fighting over the same few rows. But that is exactly what SKIP LOCKED exists to prevent: a claimer that meets a locked row skips it instead of waiting. So instead of guessing, I asked Postgres what its connections were doing. pg_stat_activity shows, for every connection, the statement it is running and what it is waiting for, if anything. A query along these lines, run every half second during the 8-worker run:

sampling pg_stat_activity
select coalesce(wait_event_type || ':' || wait_event, 'running')
         as doing,
       left(query, 60) as statement
from pg_stat_activity
where backend_type = 'client backend'
  and state = 'active'
  and pid <> pg_backend_pid();

An active connection with no wait event is executing, which is as close to “on CPU” as this view gets. Fifteen snapshots, grouped by statement and wait:

What busy connections were doing during the 8-worker run
Claim queryrunning71
Mark donewaiting on a row lock (Lock:transactionid)35
Mark donewaiting on the WAL (LWLock:WALWrite, IO:WALSync)33

Connections seen in each state, summed over 15 snapshots taken 0.5 s apart.

Three things stand out. Claims, which should take well under a millisecond, were what the database was most often busy running. Completions, a single-row update by primary key, were stuck waiting for some other transaction’s lock. And when they weren’t, they were waiting for the write-ahead log to reach the disk. Each of these turned out to have its own cause, and they made each other worse.

1. A queue table is a dead-tuple factory

The table statistics in pg_stat_user_tables explained the slow claims:

Dead row versions
91,185n_dead_tup
Live rows (estimate)
0n_live_tup
HOT updates
0n_tup_hot_upd
pg_stat_user_tables for pglq_jobs during the 8-worker benchmark.

The live count of zero is an estimate that only vacuum and analyze refresh, so the zero says on its own that autovacuum had not processed the table during the runs. The dead count says what it would have found.

Postgres never changes a row in place. An update writes a new version of the row and marks the old one dead, and vacuum reclaims dead versions later. A job lives through three versions:

One job, three row versions
  1. v1status = 'queued'written by enqueuedead after the claim
  2. v2status = 'running'written by the claimdead after mark done
  3. v3status = 'done'written by mark donelive until pruned

pglq_jobs_ready (the partial index, where status = 'queued') still holds an entry for v1 until vacuum removes it. Every claim that walks the head of the index visits it, checks the table, and finds a dead row.

Postgres has an optimisation for frequent updates, the heap-only tuple (HOT) update, which skips writing new index entries when no indexed column changes. It can’t apply here. Every transition changes status, and status decides whether the row belongs in the partial index the claim reads. So every claim and every completion also leaves index entries behind for rows that are no longer ready. The claim walks that index in order, which means stepping over every stale entry at the head of the queue, checking the table to learn each one is dead, before it reaches a row it can take.

Autovacuum’s default trigger is 20% of the table plus 50 rows. That is sensible for a table of customers. For a table that rewrites itself three times per job, it means vacuum arrives long after the head of the index has filled with dead entries. The fix is per-table storage settings, so nothing else in the database changes (the migration sets the same values when it creates the table):

per-table autovacuum for the queue
alter table pglq_jobs set (
    -- vacuum after 1% churn instead of 20%
    autovacuum_vacuum_scale_factor = 0.01,
    autovacuum_vacuum_insert_scale_factor = 0.05,
    autovacuum_analyze_scale_factor = 0.05,
    -- and let it work faster when it runs
    autovacuum_vacuum_cost_delay = 1
);

Pruning finished jobs on a schedule (pglq prune --older-than 7d) keeps the table, and every scan of it, small.

2. One claim per job

Each worker kept 16 jobs in flight. Whenever one finished, a slot opened, and the worker claimed again: for one job. With no-op jobs that is one claim per job, 20,000 locking index scans that each wade through the dead entries above and each return a single row. A claim costs about the same whether it returns one row or sixteen, so the fix is to take more per trip. A worker now claims only when at least a quarter of its slots are free, or when it is idle, and then fills all of them at once:

worker loop
free = self.concurrency - len(self._inflight)
if free >= self.claim_batch or (free > 0 and not self._inflight):
    jobs = await self._claim(free)  # one round trip, up to `free` rows

The trade-off is written down in the decision record: a worker with fewer than claim_batch free slots waits for more to finish before it takes new work. For long jobs where pickup latency matters more than overhead, set claim_batch to 1.

3. The lock that was not mine

The row-lock waits were stranger. A completion updates one row, by primary key, that the same worker claimed a moment ago. Nobody else has any business touching it. Yet the samples kept catching completions in Lock:transactionid, waiting for another transaction to end.

The explanation that fits is a detail of how FOR UPDATE behaves under READ COMMITTED, Postgres’s default isolation level. A claim scans with the snapshot it started with. When it reaches a row that another transaction changed and committed after that snapshot, for example a row another worker has just claimed, it does not simply skip it. It follows the row to its newest version, locks that version, and only then re-checks the WHERE clause. The re-check fails, because the newest version is running and not queued, so the row is not returned. But the lock has been taken, and row locks in Postgres last until the transaction ends.

A claim locks a row it does not take
timeClaim C (another worker)Worker A (owns row 42)
t0Claim C starts and takes its snapshot. In it, row 42 is queued.·
t1·Worker A's claim commits. Row 42 is now running, owned by A.
t2C reaches row 42. The row has a newer version than its snapshot, so C follows it, locks the newest version, then re-checks status = 'queued'. False: the row is skipped, and the lock is kept.·
t3C keeps scanning, slowly, past dead index entries.A's job is done. update … set status = 'done' on row 42 waits for C: Lock:transactionid.
t4C commits. Its row locks are released.A's update goes through.

So the worker that owns the job goes to mark it done, finds its own row locked by someone else’s claim, and waits for that claim to commit. With fast claims the wait is too short to notice. With claims slowed down by dead index entries (1) and repeated 20,000 times (2), it becomes a queue of its own. SKIP LOCKED skips rows that are already locked when the scan reaches them. It says nothing about the locks the scan takes itself.

I did not fix this one head on. Making claims short and rare shrinks the window until the waits stop mattering, which is why the three causes have to be read together.

4. One commit per job

The last third of the samples were completions waiting on WALWrite and WALSync. Each completion was its own transaction, and with synchronous_commit = on (the default, and what you want for a queue that promises not to lose work) each commit waits until its WAL record is flushed to disk. Postgres already groups concurrent commits into one flush when it can, but thousands of separate commits a second still meant a lot of flushes on a laptop SSD.

Batching completions sounds as if it must add latency: wait ten milliseconds, collect, write. It doesn’t have to. The completer writes a completion at once if nothing is being written. Completions that arrive while a write is in flight wait for it to finish, then go out together as one statement and one commit:

mark a batch done, each row fenced by its own token
update pglq_jobs j
set status = 'done', result = v.result, finished_at = now(),
    lease_token = null, lease_until = null
from unnest(%(ids)s::bigint[],
            %(tokens)s::uuid[],
            %(results)s::jsonb[]) as v(id, token, result)
where j.id = v.id
  and j.lease_token = v.token
  and j.status = 'running'
returning j.id

Every row is still checked against its own lease token, so a batch can never finish a job that someone else holds now. The kill -9 chaos test, which kills workers at random while they drain 3,000 jobs and then counts effects, runs against this code on every push. Under light load every batch holds a single job and nothing waits that would not have waited anyway. Under load, batches grow by themselves, which is exactly when commits are the bottleneck.

After

Throughput before and after the changesBeforeAfter
jobs per second01,0002,0003,000121,6382,74743062,1528worker processes

Same machine and workload. Before: one run per setting. After: median of three runs.

Show the numbers as a table
Throughput before and after the changes
worker processesBefore (jobs/s)After (jobs/s)
19221,428
21,3782,144
41,6382,747
83062,152

Eight workers went from 306 to 2,152 jobs a second, and four from 1,638 to 2,747. The full runs, including the spread between them, are in BENCHMARKS.md.

Eight is still slower than four, but for a duller reason: eight Python processes and their eight Postgres backends share two physical cores. On a database server with cores of its own I would expect the line to keep rising. I haven’t measured that, so treat it as a guess.

What I am keeping

  • Sample wait events before forming a theory. Fifteen snapshots of pg_stat_activity pointed at three separate causes. Any single guess would have found one at most.
  • A queue table is churn. Tune autovacuum per table, prune finished rows, and remember that HOT updates can’t help when the column you change is the one your index filters on.
  • SKIP LOCKED is not lock-free. Under READ COMMITTED, a locking scan can lock rows it then skips, and someone else waits for it.
  • Batch the expensive round trips, but only when there is a queue to batch. Writing at once when idle and batching while busy gives you the throughput under load without the latency when it is quiet.

The code is at github.com/Kage7047/pg-lease-queue, and the decision record for these changes is ADR 0004. To run the benchmark on your own machine:

shell
pglq bench --jobs 20000 --workers 1,2,4,8 --concurrency 16