SKIP LOCKED vs FOR UPDATE vs Advisory Locks: A Postgres Benchmark

SKIP LOCKED vs FOR UPDATE vs Advisory Locks: A Postgres Benchmark

Published Updated

We benchmarked the three common ways to claim jobs from a PostgreSQL queue table (plain FOR UPDATE, FOR UPDATE SKIP LOCKED, and advisory locks) on PostgreSQL 15, 16, 17, and 18, with 1 to 64 concurrent workers: 216 runs, three repeats per setting. The short version:

  • FOR UPDATE stops scaling at 4 to 8 workers, around 5,800 to 6,500 jobs claimed per second, and falls to about 2,800 at 64 workers, where 57 of 64 sessions are waiting on row locks.
  • SKIP LOCKED scales to about 12,200 to 12,800 claims per second at 16 workers on PostgreSQL 15 to 17, roughly 3.5 times a single worker. It is limited by WAL writes first and by contention on the queue's head pages at 64 workers.
  • Advisory locks claim the most rows at 16 to 32 workers, but at 64 workers 58 to 69% of calls return no job. pgbench's own transactions-per-second figure overstates them by 2.4 to 3.2 times.
  • Autovacuum mattered more than the strategy. In a 150-second run with default settings, SKIP LOCKED fell from 15,231 to about 3,100 claims per second and autovacuum never ran. With autovacuum tuned for the queue table, it held about 15,800.
  • PostgreSQL 18 claimed 18 to 46% fewer rows per second than 17 with SKIP LOCKED at 8 to 64 workers in our setup. Data checksums and the new asynchronous I/O do not explain it; we have not found the cause.

Everything is in the lab repository at codenotes-tech/labs/postgres-queue-claim-locks: the Docker setup, the claim functions, the Node.js runner, and the raw pgbench output of every run.

For the rest of the queue design around the claim (retries, leases, stuck-job recovery, monitoring), see PostgreSQL Job Queues with SKIP LOCKED. This article is about the claim itself.


What We Ran

The queue is one table with a partial index on runnable jobs:

CREATE TABLE jobs (
  id bigserial PRIMARY KEY,
  status text NOT NULL DEFAULT 'queued',
  run_at timestamptz NOT NULL DEFAULT now(),
  locked_at timestamptz,
  payload jsonb NOT NULL DEFAULT '{}'::jsonb
);
CREATE INDEX jobs_runnable_idx ON jobs (run_at, id) WHERE status = 'queued';

The two row-locking strategies differ by one clause. Each worker picks the oldest queued job and marks it done in one statement:

WITH picked AS (
  SELECT id FROM jobs
  WHERE status = 'queued'
  ORDER BY run_at, id
  LIMIT 1
  FOR UPDATE              -- or: FOR UPDATE SKIP LOCKED
)
UPDATE jobs j SET status = 'done', locked_at = now()
FROM picked WHERE j.id = picked.id
RETURNING j.id;

The advisory strategy reads up to 32 candidates without locking rows, takes the first one whose id it can lock with pg_try_advisory_xact_lock, re-checks the status, and returns NULL if all 32 are taken:

FOR candidate IN
  SELECT id FROM jobs WHERE status = 'queued' ORDER BY run_at, id LIMIT 32
LOOP
  IF pg_try_advisory_xact_lock(candidate) THEN
    UPDATE jobs SET status = 'done', locked_at = now()
    WHERE id = candidate AND status = 'queued';
    IF FOUND THEN RETURN candidate; END IF;
  END IF;
END LOOP;
RETURN NULL;

Jobs do no work after being claimed, so the runs measure the claim path only. The full functions are in sql/setup.sql.

SettingValue
MachineApple M1 Pro (10 cores, 16 GB), macOS 26.7
DockerDocker Desktop 29.7, Linux VM with 8 CPUs and 13.6 GiB
PostgreSQL15.20, 16.16, 17.11, 18.3 (official postgres images)
Server settingsshared_buffers = 1GB, max_wal_size = 8GB; fsync and synchronous_commit on
Queue1,000,000 jobs, refilled, vacuumed, and checkpointed before every run
Matrix3 strategies × 1, 4, 8, 16, 32, 64 workers × 4 versions × 3 repeats, 20 seconds each
Load generatorpgbench in the database container, -j = min(workers, 4)

Three choices matter when reading the numbers:

  • "Claims per second" counts rows actually marked done. pgbench's tps also counts advisory calls that claimed nothing, so it is the wrong number for that strategy.
  • All four versions ran as separate containers at the same time, and all 216 runs executed in one seeded random order. Slow drift on the host cannot line up with one version or strategy.
  • Every number is a median of three runs. Repeats differed by up to 26%. Five consecutive runs collapsed together during a three-minute window, across unrelated versions and strategies, which points to interference on the host; we set them aside (they are in excluded-runs.csv with the reason) and reran them.

While each run executed, a sampler read pg_stat_activity four times a second to record what the workers were waiting on.


Claims Per Second By Strategy

Line chart of rows claimed per second against worker count on PostgreSQL 17: FOR UPDATE peaks at 4 workers, SKIP LOCKED and advisory locks peak at 16 workers

PostgreSQL 17, medians of three runs:

WorkersFOR UPDATESKIP LOCKEDAdvisory locks (claimed)Advisory calls with no job
13,6283,5494,1840%
46,2197,4638,3170%
85,77310,92011,7940%
163,93112,16313,3480%
322,89110,64213,06613%
642,7198,2908,66858%

PostgreSQL 15 and 16 follow the same shape: within about 10% of these numbers at most points, and 14 to 18% higher than 17 with SKIP LOCKED at 32 and 64 workers. PostgreSQL 18 has the same shape at a lower level; it gets its own section below.

p95 latency per claim tells the same story from the worker's side:

WorkersFOR UPDATESKIP LOCKEDAdvisory locks
10.35 ms0.37 ms0.33 ms
82.74 ms1.11 ms1.05 ms
3212.62 ms5.98 ms4.20 ms
6412.33 ms21.34 ms7.67 ms

Why FOR UPDATE Stops At 4 To 8 Workers

Every worker runs the same query, so every worker tries to lock the same first row. One wins; the others queue behind its row lock. When the winner commits, PostgreSQL re-checks the row for the next waiter, finds it no longer matches status = 'queued', and moves that waiter to the next row, where the rest of the queue piles up again. The claims are correct, but they happen roughly one at a time.

The wait sampler shows exactly that. At 4 to 16 workers, the waiting sessions sit on Lock:transactionid (waiting for the winner's transaction to end). At 64 workers most sit on Lock:tuple, queued for the row lock itself: on average 57 of 64 sessions were waiting at any moment. Adding workers past 4 made the queue slower, from 6,219 claims per second at 4 workers to 2,719 at 64.

Why SKIP LOCKED Stops At 16

With SKIP LOCKED, a worker that hits a locked row skips to the next one, so claims run in parallel. The PostgreSQL SELECT documentation describes skipping locked rows as unsuitable for general queries but suitable for exactly this case: multiple consumers of a queue-like table.

It scaled about 3.4 times from one worker to 16 on PostgreSQL 17 (3,549 to 12,163). The waits explain where it stopped:

  • 1 worker: each claim waits for its own WAL flush (IO:WalSync). With synchronous_commit on, every claim is a durable commit.
  • 8 to 32 workers: sessions wait on LWLock:WALWrite, from about 2.5 sessions at 8 workers to 21 at 32. Concurrent commits share WAL flushes, which is why throughput grows at all, until the WAL writer is the limit.
  • 64 workers: about 46 of 64 sessions wait on LWLocks at any moment, mostly LWLock:BufferContent. Every claim's index scan starts at the same few pages at the head of the queue, and 64 workers contend for the locks on those pages. Throughput drops to 8,290 and p95 latency to 21 ms.

Advisory Locks: The Highest Numbers, With A Catch

Advisory locks claimed the most rows: 13,348 per second at 16 workers on PostgreSQL 17, about 10% more than SKIP LOCKED, and they were also faster with a single worker (4,184 against 3,549).

The catch is the empty claims. Every worker reads the same 32 oldest candidates. With 32 workers, 13% of calls found all 32 taken and returned NULL; with 64 workers, 58 to 69% did, depending on the version. A worker that gets NULL has to call again, so those are wasted round trips. pgbench reported 20,854 transactions per second for advisory locks at 64 workers on PostgreSQL 17, while only 8,668 rows were actually claimed. Measured by tps, advisory locks look like the clear winner at high concurrency; measured by rows claimed, they are no better than SKIP LOCKED.

If you run advisory-lock claims, size the candidate batch to your worker count and track rows claimed per second, not calls per second.


The Queue Gets Slower As It Runs

Each 20-second run started from a freshly vacuumed queue, and throughput did not stay flat within a run. Comparing the first quarter of each run with the last quarter on PostgreSQL 15 to 17:

  • SKIP LOCKED lost 28 to 48% at 1 to 32 workers.
  • Advisory locks lost 31 to 57%.
  • FOR UPDATE lost about 55% at 32 and 64 workers.

The cause is what a claim leaves behind. Marking a job done creates a new row version and leaves the old one dead. The dead version's entry stays in the partial index until vacuum removes it, and every later claim's index scan starts at the head of the queue and walks past those entries. We measured this directly from pg_stat_database on PostgreSQL 17: each SKIP LOCKED claim touched 117 to 130 buffer pages with one worker, 329 to 337 with 8, and 380 to 395 with 32. A claim that should read a handful of pages read hundreds.

So we ran a longer test: a queue of 5,000,000 jobs, SKIP LOCKED, 16 workers, 150 seconds, sampling every 5 seconds, once with PostgreSQL's default autovacuum settings and once tuned for the queue table.

Line chart of claims per second over 150 seconds: with default autovacuum, throughput falls from about 15,000 to about 3,000 on PostgreSQL 17 and to about 3,000 on PostgreSQL 18; with tuned autovacuum it stays near 15,000 on 17 and 8,600 on 18
PostgreSQL 17, SKIP LOCKED, 16 workersFirst 5 secondsLast 30 seconds (mean)Autovacuum runsDead rows
Default autovacuum15,2313,0860743,522 at the end
Tuned autovacuum17,31015,7816976,455 at the peak

With default settings, autovacuum never ran. PostgreSQL vacuums a table when its dead rows exceed autovacuum_vacuum_threshold plus autovacuum_vacuum_scale_factor times the row count, 50 plus 20% by default, as described in the autovacuum documentation. For 5,000,000 jobs that is about 1,000,000 dead rows; the run reached 743,522 and throughput settled around 3,100 claims per second, 80% below where it started. The bigger the backlog, the longer the default waits.

The tuned run changed four settings:

ALTER TABLE jobs SET (
  autovacuum_vacuum_scale_factor = 0,      -- do not scale the trigger with table size
  autovacuum_vacuum_threshold = 20000,     -- vacuum after ~20,000 dead rows
  autovacuum_vacuum_cost_delay = 0         -- do not throttle vacuum on this table
);

-- Server-wide: check tables every second instead of every minute.
ALTER SYSTEM SET autovacuum_naptime = '1s';
SELECT pg_reload_conf();

Autovacuum ran 69 times in 150 seconds, dead rows never exceeded 76,455, and throughput held at about 15,800 claims per second, five times the default run. PostgreSQL 18 repeated the pattern: 8,347 falling to 2,969 claims per second with defaults and zero autovacuum runs, against a steady 8,650 tuned, with 52 vacuum runs.

The per-table settings are storage parameters and affect only the queue table. autovacuum_naptime is server-wide, and we did not measure what frequent vacuuming costs other workloads on the same server; 20,000 was a reasonable threshold for this test, not a tuned optimum. The direction is clear, though: in our runs, the autovacuum settings changed throughput by 5×, more than the gap between any two claim strategies.

For the operational side of keeping a queue table small (deleting or archiving completed jobs), see Background Jobs in Production.


PostgreSQL 18 Was Slower In This Test

Line chart of SKIP LOCKED claims per second by version: PostgreSQL 15, 16, and 17 overlap and peak near 12,000 to 12,800, PostgreSQL 18 peaks near 9,000

PostgreSQL 16 and 17 performed like 15. PostgreSQL 18 was lower in almost every cell, for all three strategies:

SKIP LOCKED, workersPostgreSQL 17PostgreSQL 18Difference
810,9208,971−18%
1612,1638,693−29%
3210,6427,327−31%
648,2904,510−46%

PostgreSQL 18 changed two defaults that could plausibly matter, according to its release notes: new clusters enable data checksums by default, and reads go through a new asynchronous I/O subsystem (io_method = worker). We tested both in a separate batch of runs, with SKIP LOCKED, three repeats each:

Variant8 workers32 workers
PostgreSQL 1710,39710,015
PostgreSQL 18, defaults8,2416,612
PostgreSQL 18, checksums off8,3475,601
PostgreSQL 18, io_method = sync8,0256,470
PostgreSQL 18, both changed8,6676,372

Neither closes the gap. PostgreSQL 18 also did not do more work per claim: at 32 workers it touched fewer buffer pages per claim than 17 (263 against 380 to 395) and wrote about 6% more WAL. What differs is where sessions wait. At 32 workers, PostgreSQL 17's sessions mostly wait on WAL writes, while 18's wait on buffer content locks (LWLock:BufferContent).

We have not found the cause. Treat this as a reason to benchmark your own queue before upgrading, not as a general verdict on PostgreSQL 18: it is one machine, PostgreSQL running in Docker on macOS, and one workload.


Choosing A Claim Strategy

SituationReasonable choiceWhat we measured
Standard claim-and-mark queueFOR UPDATE SKIP LOCKEDScaled to about 12,000 claims/s at 16 workers on PostgreSQL 15 to 17, with no wasted calls
Up to about 4 workers, simplicity above allPlain FOR UPDATE is acceptable6,219 claims/s at 4 workers on 17, but every worker beyond 8 made it slower
Ownership must last across transactions in one sessionSession advisory locksNot covered by this benchmark; transaction-scoped advisory claims wasted 58 to 69% of calls at 64
Existing advisory-lock queue that worksKeep it; measure rows claimed, not tpspgbench tps overstated rows claimed by 2.4 to 3.2× at 64 workers
Any strategy under sustained loadTune autovacuum for the queue table5× throughput after 150 seconds compared with default settings
Strict global FIFOReconsider parallel consumersNot measured here; concurrent claimers cannot guarantee strict order with any of the three

SKIP LOCKED was not the fastest strategy at every point; advisory locks claimed slightly more rows at 16 and 32 workers. It was the one that combined high throughput with no wasted calls and the simplest code. Plain FOR UPDATE is correct and fine for a few workers, but it is the one strategy that gets slower as you add capacity. If you need to prevent other races around the same rows, How to Prevent Race Conditions in Backend Systems covers the row-lock options in more detail.


What This Benchmark Does Not Cover

  • Absolute numbers. PostgreSQL ran in Docker Desktop's Linux VM on a laptop, with pgbench in the same container. Compare strategies and versions against each other; a dedicated Linux server will produce different absolute numbers.
  • Job execution. Workers claimed and immediately finished jobs. When each job takes tens or hundreds of milliseconds, the claim is a small share of total time, and the differences above shrink.
  • Commit settings. synchronous_commit stayed on, so every claim waited for a durable WAL flush. Turning it off would change the single-worker numbers and the WAL-bound range.
  • Producers. The queue was pre-filled; concurrent inserts add index work for every strategy.
  • The cost of aggressive autovacuum on other workloads sharing the server.

Rerun It On Your Hardware

The whole benchmark needs Docker and Node.js 18 or newer, with no npm packages:

git clone https://github.com/codenotes-tech/labs.git
cd labs/postgres-queue-claim-locks

# A quick check: one version, three worker counts, 5-second runs
node bench.mjs --tag smoke --versions 17 --clients 1 8 64 --reps 1 --duration 5

# The full matrix (about 1.5 hours), then medians, a report, and charts
node bench.mjs
node analyze.mjs main

# The autovacuum comparison
node long-run.mjs --version 17

The results that matter most are the shapes: where each strategy stops scaling, what the sessions are waiting on when it does, and how much throughput your queue keeps after a few minutes without vacuum. If your numbers disagree with ours, the raw output of every run we used is in the repository to compare against.