AI Hints
Home›PostgreSQL Tutorial›Job Queues, Mistakes and Alternatives
PostgreSQL · Lesson 103 of 120

Postgres as a Job Queue

No extra software.

⏱ 2 min read▶ Video at 1:33:26🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Many teams add a separate queue system for background jobs. With skip locked, Postgres itself can be a reliable queue. Fewer moving parts, and jobs live in the same transaction as your data.

  • Background jobs
  • No extra system
  • SKIP LOCKED

Grab and finish a job in one step

Delete returning removes the oldest waiting job and returns it, in one statement. Skip locked means two workers never take the same job. If the worker fails, roll back, and the job comes back. Run it. Two calls, two different jobs, oldest first.

query.sqlsql
CREATE TABLE jobs (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
                   task text NOT NULL, run_at timestamptz DEFAULT now());
INSERT INTO jobs (task) VALUES ('send receipt 1001'), ('send receipt 1002'), ('resize cover 9');

DELETE FROM jobs
WHERE id = (SELECT id FROM jobs WHERE run_at <= now()
            ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING id, task;
DELETE FROM jobs
WHERE id = (SELECT id FROM jobs WHERE run_at <= now()
            ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING id, task;
Output
CREATE TABLE
INSERT 0 3
 id |       task
----+-------------------
  1 | send receipt 1001
(1 row)

DELETE 1
 id |       task
----+-------------------
  2 | send receipt 1002
(1 row)

DELETE 1

Queue tips

Run at lets you schedule jobs for later. Add an attempts counter for retries. Notify can wake workers instantly. And libraries like pg boss, River and Procrastinate build all this for you.

keyvalue
run_atschedule later
attemptsretries
NOTIFYwake workers
Librariespg-boss, River…

Summary

With skip locked, a table becomes a safe job queue, no extra system needed. Next, common mistakes.

Key takeaways
  • SKIP LOCKED
  • DELETE RETURNING
  • run_at
Next up: Common Mistakes — learn from others