Video in progress

How do you build a job queue in the database with SELECT ... FOR UPDATE SKIP LOCKED?

Each worker takes a few free tasks with FOR UPDATE SKIP LOCKED: rows locked by another worker are skipped without waiting. As a result, workers don't block each other and no task is picked up twice.

📖 Answer

WITH picked AS (
    SELECT id FROM job
    WHERE status = 'PENDING' AND run_at <= now()
    ORDER BY run_at
    LIMIT 10
    FOR UPDATE SKIP LOCKED
)
UPDATE job j
SET status = 'RUNNING', locked_at = now(), attempts = attempts + 1
FROM picked
WHERE j.id = picked.id
RETURNING j.*;

Without SKIP LOCKED, the second worker gets stuck waiting on the rows the first one locked, then sees they are no longer PENDING and returns empty. With SKIP LOCKED it moves straight on to the next free rows.

Things to watch in practice:

  • put a partial index on status = 'PENDING', otherwise the lookup gets slower as the table grows;
  • if running a task takes long, don't hold the row in a lock. Mark it RUNNING and commit, as above, and when it's done, mark it DONE in a separate transaction;
  • if a worker crashes, RUNNING rows hang. You need a "reaper" that puts rows with a stale locked_at back to PENDING;
  • delete finished tasks periodically, otherwise dead tuples pile up.

For small and medium load, without Kafka or RabbitMQ, this is a reliable solution. A bonus: the task is written in the same transaction as the business data.