Video in progress
When is using PostgreSQL as a queue with `FOR UPDATE SKIP LOCKED` the right call, and when should you move to Kafka or RabbitMQ?
If the tasks run at hundreds to thousands per second, you need a transactional guarantee, and not adding infrastructure matters, a Postgres queue is good. If traffic is very large, or you need many consumer groups, replay or long retention, use a broker.
📖 Answer
The strong side of a Postgres queue is that the task is created in the same transaction as the business data. The order was saved, so the "send email" task was saved too, or neither of them was. With a broker you need an outbox for that.
WITH next AS (
SELECT id FROM jobs
WHERE status = 'READY' AND run_at <= now()
ORDER BY run_at
LIMIT 10
FOR UPDATE SKIP LOCKED
)
UPDATE jobs j SET status = 'RUNNING', locked_at = now()
FROM next WHERE j.id = next.id
RETURNING j.*;
SKIP LOCKED skips rows taken by another worker without waiting, so workers don't block each other.
The limitations I've run into in practice:
- Each task is at least one insert and two updates, which are dead rows. At 5-10 thousand tasks per second, VACUUM and index bloat become a serious problem. Cleaning finished tasks with partitions helps.
- If a worker crashes, you need a job that returns tasks left in
RUNNINGusing a timeout onlocked_at. - There's no fan-out: if five independent services have to read one event, that's Kafka's job.
- There's no replay: "make the new service re-read yesterday's events" is easy with an offset in Kafka and manual work in Postgres.
My rule: a monolith or a few services with internal background tasks, Postgres (libraries like JobRunr and db-scheduler work this way). An event stream between services, and analytics, a broker. Often the two live together.
Sign up to mark studied questions and save your progress.