~/writing

SKIP LOCKED is enough for most job queues

How far a single Postgres table goes as a job queue, and the three signs you've outgrown it.

1 min readpostgres, queues

Every team I’ve joined has had the same conversation in its first month: should background jobs go through Redis, a hosted queue or the database we already run? For most of them the answer was the database, and the reason fits in one SQL statement.

The claim query

A worker claims the next job by locking a row nobody else holds:

update jobs
set state = 'running', claimed_at = now(), attempts = attempts + 1
where id = (
  select id from jobs
  where state = 'ready' and run_at <= now()
  order by priority desc, run_at
  for update skip locked
  limit 1
)
returning id, kind, payload;

skip locked is the whole trick. Two workers running this at the same moment never wait on each other and never claim the same row.

What it buys you

  • Jobs are written in the same transaction as the data they act on, so an order and its “send receipt” job either both exist or neither does.
  • Backups, monitoring and access control already cover it.
  • You can answer “what’s stuck?” with a select.

When you’ve outgrown it

  1. The jobs table is the hottest table in the database and autovacuum can’t keep up.
  2. You need fan-out to many consumers, not one worker per job.
  3. Jobs need to survive the database being down.

Until one of those is true, I’d keep the queue next to the data.