← Back to SQL, page 12

sql-0235 · Hard senior

How would several workers take jobs from a PostgreSQL queue table without two workers getting the same job?

Each worker selects one pending job with SELECT ... FOR UPDATE SKIP LOCKED inside a transaction, marks it as running, and commits. FOR UPDATE locks the chosen row, and SKIP LOCKED makes other workers pass over rows that are already locked instead of waiting. A partial index on pending jobs keeps the lookup fast.

Full answer
sql
CREATE TABLE jobs (id int PRIMARY KEY, status text NOT NULL, created int NOT NULL);
CREATE INDEX jobs_pending ON jobs(created) WHERE status = 'pending';
INSERT INTO jobs VALUES (1, 'pending', 1), (2, 'pending', 2), (3, 'done', 0);
SELECT id, status FROM jobs ORDER BY id;
idstatus
1pending
2pending
3done

One worker's claim, as a single statement with a CTE:

sql
WITH next AS (
  SELECT id FROM jobs WHERE status = 'pending'
  ORDER BY created LIMIT 1
  FOR UPDATE SKIP LOCKED
)
UPDATE jobs SET status = 'running' FROM next WHERE jobs.id = next.id
RETURNING jobs.id, jobs.status;
idstatus
1running

Job 1 is claimed and returned. A second worker running the same statement at the same moment would skip job 1, because it is locked, and claim job 2 (the concurrent part is from the documentation; only one session ran here).

Details that matter in production:

  • Order by priority or creation time so old jobs are not starved.
  • Record locked_at and requeue jobs whose worker died, by resetting jobs stuck in 'running' too long.
  • Keep the claim transaction short; do the actual work after committing the status change.

SQLite has no FOR UPDATE; with a single writer, an UPDATE ... WHERE id = (SELECT ... LIMIT 1) RETURNING id in a BEGIN IMMEDIATE transaction gives the same effect.

Key points

  • FOR UPDATE locks the selected rows
  • SKIP LOCKED skips rows other workers hold
  • Claim in a short transaction, work after commit
  • Requeue jobs whose workers die
  • A partial index on pending rows keeps it fast

Common mistakes

  • Selecting a job without locking and marking it later
  • Doing long work inside the claim transaction

Follow-ups

  • How would you add retries with backoff?
  • What changes if jobs have priorities?

Tips

  • Mention crash recovery for claimed jobs