A job queue in Postgres with SKIP LOCKED
For a small project I was running Redis purely as a job queue. Every other piece of state already lived in Postgres, which meant two systems to back up, two systems to monitor, and no way to enqueue a job in the same transaction as the write that caused it. So I moved the queue into Postgres.
The table
CREATE TABLE jobs (
id bigserial PRIMARY KEY,
kind text NOT NULL,
payload jsonb NOT NULL,
run_at timestamptz NOT NULL DEFAULT now(),
attempts int NOT NULL DEFAULT 0,
locked_at timestamptz
);
CREATE INDEX jobs_ready_idx ON jobs (run_at) WHERE locked_at IS NULL;
The partial index only covers jobs that are waiting, so it stays small even when the table has a long tail of history.
Claiming work
The trick is FOR UPDATE SKIP LOCKED: each worker locks the rows it picks, and other workers simply skip them instead of waiting.
UPDATE jobs SET locked_at = now(), attempts = attempts + 1
WHERE id IN (
SELECT id FROM jobs
WHERE locked_at IS NULL AND run_at <= now()
ORDER BY run_at
LIMIT 10
FOR UPDATE SKIP LOCKED
)
RETURNING id, kind, payload;
Ten workers running this concurrently each get a disjoint batch, with no advisory locks and no retries on conflict.
Things that bit me
- Stuck jobs. A worker that crashes leaves
locked_atset forever. A periodic sweep resets rows locked longer than the job timeout. - Table bloat. Deleting finished jobs creates dead tuples. Autovacuum handles it at my volume, but I watch
n_dead_tupon this table. - Latency. Polling every second is fine for background work. If you need faster pickup, add
LISTEN/NOTIFYas a wake-up signal, not as the queue itself.
When not to do this
If you need tens of thousands of jobs per second, fan-out to many consumers, or replay, use a real log like Kafka. For a few hundred jobs a minute that must be consistent with the rest of your data, one table is hard to beat.