A Job Queue in Plain Postgres with SKIP LOCKED

I benchmarked a Postgres job queue with up to 16 workers. Naive claiming ran jobs twice; SKIP LOCKED hit 35,000 jobs/s in batches, with zero duplicates.

15 min read
AI-assisted

Author's AI disclosure

The author reports using AI to help with this article.

The author confirms reviewing this article.

A Job Queue in Plain Postgres with SKIP LOCKED

You probably don't need Redis or Kafka for background jobs. One table and one SQL clause will do, as long as you avoid two traps I hit while benchmarking it.


Sending emails, resizing images, calling webhooks: every backend needs background jobs. The usual answer is to add Redis, RabbitMQ, or Kafka.

If you already run Postgres, you already have a job queue. All it takes is one table, one index, and FOR UPDATE SKIP LOCKED. Rails 8's default job backend, Solid Queue, is built on this clause.

I built one, ran it with up to 16 workers, and tried to break it.

TL;DR: With 16 workers, the naive "SELECT, then UPDATE" queue produced 22,690 duplicate job runs in 15 seconds. FOR UPDATE SKIP LOCKED gave zero duplicates and scaled to 2,168 jobs/s, or ~35,500 jobs/s when claiming 100 jobs at a time. Two traps: the common way to write dequeue() scanned the whole table on every call (6–10 jobs/s), and a single long-open transaction cut throughput by more than half within a minute.

Every number here is measured, not estimated. I ran every strategy against a real Postgres server with a million queued jobs. The exact scripts are in the "Run it yourself" section near the end.


The hard part: two workers, one job

A queue is easy with one worker. The hard part is many workers taking jobs from the same table without two of them grabbing the same job, and without them waiting on each other.

sequenceDiagram
  participant A as Worker A
  participant DB as jobs table
  participant B as Worker B
  rect rgba(232, 89, 12, 0.12)
  Note over A,B: Naive: look, then claim
  A->>DB: SELECT next job
  DB-->>A: job 1
  B->>DB: SELECT next job
  DB-->>B: job 1
  A->>DB: UPDATE job 1 to running
  B->>DB: UPDATE job 1 to running
  Note over A,B: Both workers run job 1
  end
  rect rgba(47, 158, 68, 0.12)
  Note over A,B: FOR UPDATE SKIP LOCKED
  A->>DB: lock the next unlocked job
  DB-->>A: job 1 (now locked by A)
  B->>DB: lock the next unlocked job
  DB-->>B: job 2 (job 1 is skipped)
  end
  • Naive (SELECT, then UPDATE): both workers see job 1 before either claims it.

  • Guarded (UPDATE ... WHERE status = 'queued'): only one claim succeeds, but every worker races for the same row and most attempts come back empty.

  • FOR UPDATE: correct, but every worker locks the same first row, so they wait in line.

  • FOR UPDATE SKIP LOCKED: if a row is locked, skip it and take the next one. The Postgres docs describe it as a way "to avoid lock contention with multiple consumers accessing a queue-like table". It's been in Postgres since 9.5 (2016).

The queue: one table, four functions

Here's the whole thing. It handles retries with backoff, gives up after 5 attempts, and recovers jobs from workers that crash:

-- queue.sql: a job queue in plain Postgres (10+; tested on 16).

create table jobs (
  id           bigint generated always as identity primary key,
  queue        text        not null default 'default',
  payload      jsonb       not null default '{}',
  status       text        not null default 'queued'
               check (status in ('queued', 'running', 'done', 'dead')),
  run_at       timestamptz not null default now(),  -- when it may run (used for retries)
  attempts     int         not null default 0,
  max_attempts int         not null default 5,
  locked_until timestamptz,                         -- lease: if passed, the worker is presumed dead
  last_error   text,
  created_at   timestamptz not null default now()
);

-- Only waiting jobs are indexed, so done jobs don't slow down dequeue.
create index jobs_ready_idx on jobs (queue, run_at, id) where status = 'queued';
create index jobs_lease_idx on jobs (locked_until) where status = 'running';

-- Claim up to n ready jobs. Workers never block each other: rows another worker
-- has locked are skipped. Each claimed job gets a lease.
-- id = any(array(...)) matters: written as a join, the planner can't see that n is
-- small and may scan the whole table on every call (see the post).
create function dequeue(q text, n int default 1, lease interval default '5 minutes')
returns setof jobs language sql as $$
  update jobs
  set status = 'running', attempts = attempts + 1, locked_until = now() + lease
  where id = any (array(
    select id from jobs
    where queue = q and status = 'queued' and run_at <= now()
    order by run_at, id
    limit n
    for update skip locked))
  returning *;
$$;

-- Mark a job done. Pass the attempts value you got from dequeue: if the lease
-- expired and someone else re-claimed the job, this returns false and changes nothing.
create function complete(job_id bigint, attempt int) returns boolean language sql as $$
  with u as (
    update jobs set status = 'done', locked_until = null
    where id = job_id and attempts = attempt and status = 'running'
    returning 1)
  select count(*) > 0 from u;
$$;

-- Record a failure. Retries with exponential backoff (2^attempts seconds, max 1 hour,
-- with jitter), or moves the job to 'dead' after max_attempts.
create function fail(job_id bigint, attempt int, err text) returns boolean language sql as $$
  with u as (
    update jobs set
      status       = case when attempts >= max_attempts then 'dead' else 'queued' end,
      run_at       = now() + least(interval '1 hour', interval '1 second' * 2 ^ attempts)
                             * (0.5 + random() / 2),
      locked_until = null,
      last_error   = err
    where id = job_id and attempts = attempt and status = 'running'
    returning 1)
  select count(*) > 0 from u;
$$;

-- Requeue jobs whose worker died (lease expired). Run it every minute or so.
create function reap() returns int language sql as $$
  with u as (
    update jobs set
      status       = case when attempts >= max_attempts then 'dead' else 'queued' end,
      locked_until = null,
      last_error   = 'lease expired'
    where status = 'running' and locked_until < now()
    returning 1)
  select count(*)::int from u;
$$;

A job moves through these states:

stateDiagram-v2
  [*] --> queued: INSERT
  queued --> running: dequeue()
  running --> done: complete()
  running --> queued: fail(), retry after backoff
  running --> queued: reap(), lease expired
  running --> dead: fail() or reap() after max_attempts
  done --> [*]
  dead --> [*]
  classDef ok fill:#2f9e44,color:#fff,stroke:#2b8a3e
  classDef bad fill:#e8590c,color:#fff,stroke:#c2410c
  classDef work fill:#1c7ed6,color:#fff,stroke:#1864ab
  class done ok
  class dead bad
  class running work

Three design choices are worth explaining:

  1. Leases, not long transactions. dequeue() commits right away and stamps locked_until. The worker does the job outside any transaction. If it crashes, reap() puts the job back once the lease expires.

  2. attempts doubles as a fencing token. If a slow worker's lease expires and another worker re-claims the job, the slow one's complete(id, attempt) no longer matches and changes nothing.

  3. A partial index on waiting jobs only. Done jobs can pile up without slowing down dequeue().

I tested every path: claiming, completing, retrying with backoff, dead-lettering, and lease expiry, including the slow worker that can't complete a job it lost. All 17 checks pass.

One rule for your job code: make it safe to run twice. If a worker finishes the work but crashes before complete(), the job runs again after the lease expires. This is called at-least-once delivery, and it's how most job queues behave.

The worker

"""A minimal worker for queue.sql. Run as many copies as you like; they never block each other.

`db` is a connection in autocommit mode that returns rows as dicts
(for example psycopg 3 with row_factory=dict_row).
"""
import time


def run_worker(db, handle, queue="default", batch=10, idle_sleep=1.0, stop=lambda: False):
    last_reap = 0.0
    while not stop():
        if time.monotonic() - last_reap > 60:            # requeue jobs from crashed workers
            db.execute("select reap()")
            last_reap = time.monotonic()

        jobs = db.execute("select * from dequeue(%s, %s)", (queue, batch)).fetchall()
        if not jobs:
            time.sleep(idle_sleep)                       # nothing to do; poll again soon
            continue

        for job in jobs:
            try:
                handle(job)
                db.execute("select complete(%s, %s)", (job["id"], job["attempts"]))
            except Exception as e:                       # retried later with backoff
                db.execute("select fail(%s, %s, %s)", (job["id"], job["attempts"], repr(e)))

I ran three of these in parallel against the real queue, with every 10th job failing on its first try. All 40 jobs finished, each was handled exactly once, and the 4 failures succeeded on retry after backing off.

The benchmark: five ways to claim a job

The setup: Postgres 16.15 with stock config on a 2 vCPU / 7 GB cloud VM. 1 million jobs queued, workers simulated with pgbench, 15 seconds per run. Each job is claimed, logged, and marked done, each in its own commit, with no real work in between. So this measures the queue itself. I ran everything twice and report the average: most numbers agreed within 7%, the noisiest (naive with 1 worker) differed by 32%, and the patterns were the same in both runs.

Jobs completed per second (each job counted once, average of two runs):

How workers claim jobs

1 worker

4 workers

16 workers

Problem at 16 workers

Naive: SELECT, then UPDATE

888

810

539

22,690 duplicate runs

Guarded: UPDATE ... WHERE status = 'queued'

829

794

533

2,830 empty claims/s

FOR UPDATE

614

1,356

854

workers wait in line

SKIP LOCKED, join-style dequeue()

6

10

9

full table scan per call

SKIP LOCKED, dequeue() above

750

1,796

2,168

none

SKIP LOCKED, 100 jobs per call

18,016

35,504

31,850

none

What stands out:

  • Among the one-job-at-a-time approaches, naive is fastest with one worker, because there's nothing to coordinate. With more workers it gets slower and runs jobs over and over.

  • SKIP LOCKED was the only one-at-a-time approach that kept getting faster as workers were added.

  • Claiming in batches of 100 was 15–24x faster than one at a time. Commits are the bottleneck here, and batching shares each commit across 100 jobs.

  • On this small VM, the workers and Postgres shared 2 CPUs, which is why the batched run peaked at 4 workers.

When jobs hold the lock while they work

Some queues skip the lease and simply hold the row lock in a transaction while the job runs. Here each job took 10 ms:

%%{init: {"themeVariables": {"xyChart": {"plotColorPalette": "#e8590c, #2f9e44"}}}}%%
xychart-beta
  title "Jobs/s when each job holds its lock for 10 ms"
  x-axis "Workers" ["1", "4", "16"]
  y-axis "jobs/s" 0 --> 1400
  line [78, 82, 82]
  line [80, 322, 1258]

Orange: FOR UPDATE · Green: FOR UPDATE SKIP LOCKED

With plain FOR UPDATE, adding workers changed nothing: 82 jobs/s with 16 workers, about the same as with one. They all queued behind one locked row. SKIP LOCKED went from 80 to 1,258 jobs/s.

Trap 1: the usual way to write dequeue()

This is a common way to write it, and the version I wrote first:

update jobs j set status = 'running', ...
from (
  select id from jobs
  where status = 'queued' ...
  order by run_at, id
  limit n
  for update skip locked
) next
where j.id = next.id
returning j.*;

Inside a SQL function, Postgres plans this without knowing n, so it assumes LIMIT n returns 10% of the waiting jobs (19,891 rows in my test). For that many rows, joining them back with a hash join looks cheapest, which means a full scan of the jobs table on every call:

dequeue() version

One call, 200k jobs queued

Throughput, 1M jobs queued

UPDATE ... FROM (subquery)

31 ms

6–10 jobs/s

WHERE id = ANY(ARRAY(subquery))

0.2 ms

750–2,168 jobs/s

With id = any(array(...)), the subquery runs first and the update looks up each id by primary key. The planner's bad guess no longer matters.

To see the plan of a query inside a function, use auto_explain with log_nested_statements = on. That's how I found this one.

Trap 2: one long-open transaction

Every update leaves behind a dead row version, and every claim also leaves a dead entry at the front of the index dequeue() scans. Postgres cleans these up only once no open transaction could still need them. A single long transaction blocks that cleanup: a slow report, a REPEATABLE READ session left open, or a transaction that wrote something and was never committed.

I ran 4 workers for 60 seconds: once normally, and once with one idle transaction (REPEATABLE READ, after one query) open in another session. I repeated both, and the chart shows the average.

%%{init: {"themeVariables": {"xyChart": {"plotColorPalette": "#2f9e44, #e8590c"}}}}%%
xychart-beta
  title "Jobs/s over one minute, 4 workers"
  x-axis "Seconds" ["10", "20", "30", "40", "50", "60"]
  y-axis "jobs/s" 0 --> 2000
  line [1742, 1590, 1473, 1475, 1317, 1138]
  line [1092, 702, 567, 517, 447, 418]

Green: normal · Orange: one long-open transaction elsewhere

With the open transaction, throughput fell to 418 jobs/s by the end of the minute. Even the normal run slowed over the minute, a sign of how fast a queue table churns. That's why the checklist below matters.

Running it in production

  • Keep transactions short. Set idle_in_transaction_session_timeout, and watch pg_stat_activity for old xact_start values.

  • Vacuum the jobs table often. It churns far more than a normal table; per-table autovacuum settings let you vacuum it sooner than the defaults would.

  • Delete or archive done jobs, say after 7 days, so the table doesn't grow forever.

  • Run reap() every minute. The worker above does it; a cron job works too.

  • Claim in batches when jobs are short. It was the biggest single throughput win.

  • Want lower latency than polling? Add LISTEN/NOTIFY so workers wake as soon as a job arrives.

  • Watch the queue:

select queue,
       count(*) filter (where status = 'queued')                          as waiting,
       max(now() - run_at) filter (where status = 'queued' and run_at <= now()) as oldest_wait,
       count(*) filter (where status = 'dead')                            as dead
from jobs
group by queue;

When you do need a real broker

A Postgres queue is a great default, not a universal answer. Reach for Kafka, RabbitMQ, or a managed queue when:

  • Many independent consumers need the same event (pub/sub fan-out), or you need to replay old events.

  • Volume outgrows your database. Jobs compete with your app for the same CPU, connections, and WAL.

  • Postgres is already your bottleneck. Don't add load to the thing that's struggling.

For most apps sending emails and calling webhooks, none of that applies.

Run it yourself

Needs Postgres 11+ (tested on 16), psql, and pgbench.

psql -f test_queue.sql   # creates the queue and runs the 17 behavior checks
PSQL="psql -d mydb" PGBENCH="pgbench mydb" ./run_bench.sh
PSQL="psql -d mydb" PGBENCH="pgbench mydb" ./long_tx.sh
test_queue.sql
-- test_queue.sql: behavior checks for queue.sql. Every line should print "t".
drop table if exists jobs cascade;
drop function if exists dequeue, complete, fail, reap;
\i queue.sql

insert into jobs (payload) select jsonb_build_object('n', g) from generate_series(1, 5) g;

-- dequeue returns the oldest jobs, marks them running, counts the attempt
create temp table claimed as select * from dequeue('default', 2);
select 'dequeue takes the 2 oldest' as check, array_agg(id order by id) = '{1,2}' as ok from claimed;
select 'claimed jobs are running, attempt 1', bool_and(status = 'running' and attempts = 1 and locked_until > now()) from claimed;

-- complete
select 'complete returns true', complete(1, 1);
select 'job 1 is done', status = 'done' from jobs where id = 1;
select 'completing twice returns false', complete(1, 1) = false;

-- fail -> retry later with backoff
select 'fail returns true', fail(2, 1, 'boom');
select 'job 2 is queued again with backoff 1-2 s',
       status = 'queued' and run_at between now() + interval '0.9 s' and now() + interval '2.1 s' and last_error = 'boom'
from jobs where id = 2;
select 'job 2 is not ready yet', not exists (select 1 from dequeue('default', 10) where id = 2);

-- dead after max_attempts
update jobs set status = 'queued', run_at = now(), attempts = 4, max_attempts = 5 where id = 2;
select 'attempt 5 claimed', (select attempts from dequeue('default', 1)) = 5;
select 'fail on last attempt', fail(2, 5, 'boom again');
select 'job 2 is dead', status = 'dead' from jobs where id = 2;

-- lease expiry: a crashed worker's job is requeued, and the old worker can't complete it
-- (the readiness check above claimed jobs 3-5; reset them)
update jobs set status = 'queued', run_at = now(), locked_until = null, attempts = 0 where id in (3, 4, 5);
update jobs set status = 'done' where id in (4, 5);
create temp table c2 as select * from dequeue('default', 1, '50 milliseconds');
select 'job 3 claimed with a short lease', (select id from c2) = 3;
select pg_sleep(0.1);
select 'reap requeues 1 expired job', reap() = 1;
select 'job 3 queued again', status = 'queued' and last_error = 'lease expired' from jobs where id = 3;
select 'a new worker claims it (attempt 2)', (select attempts from dequeue('default', 1)) = 2;
select 'the old worker cannot complete it', complete(3, 1) = false;
select 'the new worker can', complete(3, 2);
run_bench.sh
#!/usr/bin/env bash
# run_bench.sh: run each dequeue strategy with 1, 4 and 16 workers for 15 s each.
# Usage: PSQL="psql -d bench" PGBENCH="pgbench -d bench" ./run_bench.sh
set -euo pipefail
cd "$(dirname "$0")"
PSQL=${PSQL:-psql}; PGBENCH=${PGBENCH:-pgbench}
SECS=${SECS:-15}; JOBS=${JOBS:-1000000}
q() { $PSQL -X -q -At -v ON_ERROR_STOP=1 "$@"; }

q -c "create unlogged table if not exists processed (job_id bigint not null)" -f bench/dequeue_join.sql
echo "strategy,workers,jobs_per_sec,duplicates,empty_attempts_per_sec"
for s in ${STRATEGIES:-naive guarded for_update skip_locked_join skip_locked skip_locked_batch hold_for_update hold_skip_locked}; do
  for c in ${WORKERS:-1 4 16}; do
    q -c "truncate jobs, processed restart identity" \
      -c "insert into jobs (payload) select jsonb_build_object('n', g) from generate_series(1, $JOBS) g" \
      -c "vacuum analyze jobs" -c "checkpoint"
    txns=$($PGBENCH -n -c "$c" -j "$(( c < 2 ? c : 2 ))" -T "$SECS" -f "bench/$s.sql" 2>/dev/null \
           | awk '/number of transactions actually processed/ {print $NF}')
    txns=${txns%%/*}
    q -F, -c "select '$s', $c,
                     round(count(distinct job_id) / $SECS.0),
                     count(*) - count(distinct job_id),
                     case when '$s' like '%batch' then null
                          else round(greatest($txns - count(*), 0) / $SECS.0) end
              from processed"
  done
done
bench/*.sql (one pgbench script per strategy)
-- ===== bench/dequeue_join.sql =====
-- The common way to write dequeue: UPDATE ... FROM (subquery). Benchmark only.
create or replace function dequeue_join(q text, n int default 1, lease interval default '5 minutes')
returns setof jobs language sql as $$
  update jobs j
  set status = 'running', attempts = j.attempts + 1, locked_until = now() + lease
  from (
    select id from jobs
    where queue = q and status = 'queued' and run_at <= now()
    order by run_at, id
    limit n
    for update skip locked
  ) next
  where j.id = next.id
  returning j.*;
$$;

-- ===== bench/naive.sql =====
-- Naive: look, then claim. Two workers can see the same job.
select id as claimed from jobs where queue = 'default' and status = 'queued' and run_at <= now()
order by run_at, id limit 1 \gset
update jobs set status = 'running', attempts = attempts + 1 where id = :claimed;
insert into processed (job_id) values (:claimed);
update jobs set status = 'done' where id = :claimed;

-- ===== bench/guarded.sql =====
-- Guarded: look, then claim only if still queued. No duplicates, but workers race for the same row.
select id from jobs where queue = 'default' and status = 'queued' and run_at <= now()
order by run_at, id limit 1 \gset
with c as (update jobs set status = 'running', attempts = attempts + 1
           where id = :id and status = 'queued' returning id)
select coalesce((select id from c), 0) as claimed \gset
\if :claimed > 0
insert into processed (job_id) values (:claimed);
update jobs set status = 'done' where id = :claimed;
\endif

-- ===== bench/for_update.sql =====
-- FOR UPDATE: lock the row while claiming. Correct, but workers queue up behind one row.
with c as (
  update jobs j set status = 'running', attempts = j.attempts + 1
  from (select id from jobs where queue = 'default' and status = 'queued' and run_at <= now()
        order by run_at, id limit 1 for update) next
  where j.id = next.id returning j.id)
select coalesce((select id from c), 0) as claimed \gset
\if :claimed > 0
insert into processed (job_id) values (:claimed);
update jobs set status = 'done' where id = :claimed;
\endif

-- ===== bench/skip_locked_join.sql =====
-- SKIP LOCKED via dequeue_join() (UPDATE ... FROM), one job at a time.
select coalesce(min(id), 0) as claimed from dequeue_join('default', 1) \gset
\if :claimed > 0
insert into processed (job_id) values (:claimed);
update jobs set status = 'done' where id = :claimed;
\endif

-- ===== bench/skip_locked.sql =====
-- SKIP LOCKED: dequeue() from queue.sql, one job at a time.
select coalesce(min(id), 0) as claimed from dequeue('default', 1) \gset
\if :claimed > 0
insert into processed (job_id) values (:claimed);
update jobs set status = 'done' where id = :claimed;
\endif

-- ===== bench/skip_locked_batch.sql =====
-- SKIP LOCKED, 100 jobs per dequeue.
select coalesce(string_agg(id::text, ','), '0') as ids from dequeue('default', 100) \gset
insert into processed (job_id) select id from jobs where id in (:ids);
update jobs set status = 'done' where id in (:ids);

-- ===== bench/hold_for_update.sql =====
-- Lock held for the whole job (10 ms of work), FOR UPDATE.
begin;
select coalesce(min(id), 0) as claimed from (
  select id from jobs where queue = 'default' and status = 'queued' and run_at <= now()
  order by run_at, id limit 1 for update) x \gset
\sleep 10 ms
insert into processed (job_id) select :claimed where :claimed > 0;
update jobs set status = 'done' where id = :claimed;
commit;

-- ===== bench/hold_skip_locked.sql =====
-- Lock held for the whole job (10 ms of work), FOR UPDATE SKIP LOCKED.
begin;
select coalesce(min(id), 0) as claimed from (
  select id from jobs where queue = 'default' and status = 'queued' and run_at <= now()
  order by run_at, id limit 1 for update skip locked) x \gset
\sleep 10 ms
insert into processed (job_id) select :claimed where :claimed > 0;
update jobs set status = 'done' where id = :claimed;
commit;
long_tx.sh
#!/usr/bin/env bash
# long_tx.sh: 4 SKIP LOCKED workers for 60 s, with and without one long-open transaction
# elsewhere in the database. Prints jobs/s every 10 s.
set -euo pipefail
cd "$(dirname "$0")"
PSQL=${PSQL:-psql}; PGBENCH=${PGBENCH:-pgbench}
q() { $PSQL -X -q -At -v ON_ERROR_STOP=1 "$@"; }

for mode in normal long_tx; do
  q -c "truncate jobs, processed restart identity" \
    -c "insert into jobs (payload) select jsonb_build_object('n', g) from generate_series(1, 1000000) g" \
    -c "vacuum analyze jobs" -c "checkpoint"
  if [ "$mode" = long_tx ]; then
    # e.g. a forgotten "BEGIN" in a console, or a slow report: holds a snapshot for 90 s
    $PSQL -X -q -c "begin isolation level repeatable read" -c "select count(*) from processed" \
          -c "select pg_sleep(90)" -c "commit" >/dev/null &
    sleep 1
  fi
  echo "== $mode"
  $PGBENCH -n -c 4 -j 2 -T 60 -P 10 -f bench/skip_locked.sql 2>&1 | grep '^progress' \
    | awk '{print "  " $2 " s: " $4 " jobs/s"}'
  q -c "select '  index size: ' || pg_size_pretty(pg_relation_size('jobs_ready_idx'))"
  wait
done

The bottom line

Adding a message broker means another system to run, monitor, back up, and keep consistent with your database. For most background jobs, Postgres already does the job: one table, one partial index, and FOR UPDATE SKIP LOCKED.

The clause is the easy part. What decides whether your queue works is everything around it: leases so crashed workers don't lose jobs, job code that's safe to run twice, a dequeue() whose plan you've actually checked, and no long transactions blocking cleanup.

Before you add Redis for your next background job, try the table.

Comments0

Log in to join the discussion.

No comments yet.

Emma Clements

Read articles by this author.

Subscribe to Emma Clements's newsletter

Get the articles this author chooses to send by email.