ArticleAdvanced2 min read

Postgres as a Job Queue with SKIP LOCKED

An honest PostgreSQL job queue design: atomic claims, leases, fencing, retries, dead letters, and the limits of SKIP LOCKED.

Author
Pradeep Gajendra
Published
Updated

Scope of this article

Versions
PostgreSQL 16
Environment
Working SQL patterns with intentionally abbreviated worker runtime.

If your application already operates PostgreSQL, a jobs table can be a sensible first queue. It avoids an additional broker and keeps scheduling, leasing and business state close together. The hard part is not selecting work; it is recovering when a worker dies after performing some—but not all—of it.

The failure model#

  • Multiple workers must claim distinct jobs without serializing the whole queue.

  • A worker can crash before acknowledging completion; the job must become eligible again.

  • Network calls can succeed before the worker commits its outcome, so jobs must be idempotent.

  • Poison jobs must stop cycling, retaining their error for review.

PostgreSQL documents SKIP LOCKED as useful for queue-like workloads while warning it provides an inconsistent view of rows. That trade-off is appropriate for claiming work, not general reporting queries [1].

Schema and the hot index#

jobs.sqlsql
create table jobs (
  id uuid primary key,
  kind text not null,
  payload jsonb not null,
  status text not null default 'QUEUED'
    check (status in ('QUEUED','RUNNING','SUCCEEDED','DEAD')),
  attempts int not null default 0,
  max_attempts int not null default 8,
  run_at timestamptz not null default now(),
  lease_until timestamptz,
  locked_by text,
  last_error text,
  created_at timestamptz not null default now()
);
create index jobs_ready_idx on jobs (run_at, created_at, id)
  where status = 'QUEUED';

Atomic claim, not SELECT then UPDATE#

claim.sqlsql
with candidates as (
  select id from jobs
  where status = 'QUEUED' and run_at <= now()
  order by run_at, created_at, id
  for update skip locked
  limit 20
)
update jobs as j
set status = 'RUNNING',
    attempts = attempts + 1,
    locked_by = $1,
    lease_until = now() + interval '5 minutes'
from candidates
where j.id = candidates.id
returning j.*;

Claiming holds locks only during the SQL transaction. Commit immediately, then execute work outside it. Note that a queue has neither hard FIFO ordering nor guaranteed fair scheduling when workers race or skip locked rows.

A durable job transitions through claiming, retry and terminal states, with an independent lease-recovery path.

Diagram

Recover an expired lease#

Run a separate reaper that selects RUNNING jobs with expired leases and either reschedules them or moves them to DEAD once attempts are exhausted. Make completion conditional on job ID, worker ID and current lease token. Otherwise a slow old worker may overwrite the result of a new worker after its lease expires.

finish.sqlsql
update jobs
set status = 'SUCCEEDED', lease_until = null, locked_by = null
where id = $1 and status = 'RUNNING' and locked_by = $2
returning id;

Retry and observability policy#

  • Use bounded exponential backoff with jitter for transient failures; never retry invalid payloads indefinitely.

  • Expose ready queue depth, oldest ready age, claim duration, lease expiry rate and dead-letter count.

  • Make side effects deduplicated by domain key, not merely by job ID.

  • Batch claims but cap per-worker concurrency, since a 20-row lease does not imply capacity to process 20 slow jobs.

  • Vacuum and archive successful jobs; high churn grows indexes and tables.

When to leave PostgreSQL#

Move to a dedicated broker when independently scaling consumers, cross-region messaging, strict throughput needs, ordering semantics or integration ecosystems become dominant requirements. The crossover point must be measured. PostgreSQL is not automatically inferior, and a broker does not magically provide exactly-once side effects.

This example intentionally omits heartbeats, partitioning, maintenance scheduling and the full worker runtime. Those are implementation requirements, not optional production extras.

Known limitations

Not a complete drop-in queue library; add lease heartbeats, fencing, reaper, metrics and load tests.

Sources

  1. [1]
    PostgreSQL 16 SELECT — SKIP LOCKED

    PostgreSQL Global Development Group · publication date unknown · PostgreSQL 16 · retrieved 2026-11-02

Spotted an error? Use “Suggest a correction” in the discussion, or read our corrections policy.

Discussion

Sign in to join the discussion. Reading is always open.

Loading discussion…

Report comment