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