← Back to SQL, page 18

sql-0350 · Hard senior

How would you use a database table as a job queue for background workers?

Store jobs with a status, run_at and attempts. Workers claim jobs with SELECT ... FOR UPDATE SKIP LOCKED inside a transaction, so concurrent workers take different rows without blocking each other. Mark jobs done or failed, retry with backoff, and delete or archive finished jobs to keep the table small.

Full answer
text
jobs(id bigserial PK, kind, payload jsonb, status DEFAULT 'queued',
     run_at timestamptz DEFAULT now(), attempts int DEFAULT 0, locked_by, locked_at)
CREATE INDEX ON jobs (run_at) WHERE status = 'queued';

Claiming a job in PostgreSQL:

text
UPDATE jobs SET status = 'running', locked_by = :worker, locked_at = now()
WHERE id = (SELECT id FROM jobs WHERE status = 'queued' AND run_at <= now()
            ORDER BY run_at LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING *;

SKIP LOCKED makes each worker skip rows another worker is claiming, instead of waiting. Then:

  • On success, set status 'done' (or delete the row).
  • On failure, increment attempts and set run_at = now() + backoff; after N attempts mark 'dead'.
  • A reaper resets jobs stuck in 'running' past a timeout.

This suits moderate volumes and gives transactional enqueueing with business data. Very high throughput is better served by a dedicated broker. SQLite has no SKIP LOCKED; a single writer claims jobs with an UPDATE ... RETURNING instead. The PostgreSQL statements here were not run here.

Key points

  • FOR UPDATE SKIP LOCKED lets workers claim different rows
  • Partial index on queued jobs
  • Retries with backoff and a dead state
  • Reap stuck jobs
  • Clean up finished jobs

Common mistakes

  • Polling with plain SELECT then UPDATE, so two workers take one job
  • Letting the jobs table grow forever

Follow-ups

  • Why enqueue in the same transaction as the business change?
  • When should you move to a message broker?

Tips

  • Explain SKIP LOCKED