Implement a Postgres job queue with SKIP LOCKED
Allow N concurrent workers to claim pending jobs from a jobs table without double-claiming or blocking each other.
Model Answer & Explanation
WITH next_job AS (
SELECT id FROM jobs
WHERE status = 'pending' AND run_at <= now()
ORDER BY run_at ASC
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE jobs
SET status = 'running', locked_at = now()
FROM next_job
WHERE jobs.id = next_job.id
RETURNING jobs.*; Select the next pending job inside a transaction with FOR UPDATE SKIP LOCKED and immediately UPDATE its status to 'running' in a single CTE statement. Workers skip rows locked by other workers instead of waiting, and a partial index on (run_at) WHERE status = 'pending' keeps claims O(log N).