Skip to main content

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.

Official Reference

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).

Follow-up Interview Question · How do you recover jobs stuck in 'running' if a worker crashes mid-execution?

Module Context & References

PostgreSQL & Redis · Practice SQL & schema drills The classic SQL queries, locking patterns and optimization problems tested repeatedly
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.