A PostgreSQL Job Queue with SKIP LOCKED and LISTEN/NOTIFY

If PostgreSQL is already your main database, it can also run a background job queue for moderate workloads: sending emails, generating exports, calling webhooks. You avoid running a separate broker, and enqueuing a job can be part of the same transaction as the data change that caused it. If the transaction rolls back, the job disappears with it.
Getting it right depends on a few details that many examples get wrong. This guide builds a queue that:
- claims jobs safely across many workers with
SELECT ... FOR UPDATE SKIP LOCKED, - wakes workers immediately with
LISTEN/NOTIFYinstead of tight polling, - recovers jobs from crashed workers with a lease (visibility timeout),
- retries failures with exponential backoff.
Code examples use Python with psycopg 3, but the SQL works from any language.
The Two PostgreSQL Features Involved
FOR UPDATE SKIP LOCKED locks the rows a query selects and skips rows that another transaction has already locked. Ten workers running the same "give me the next job" query each get a different job, and none of them waits on the others. This is the core of the queue. Advisory locks, which some guides add on top, aren't needed for claiming jobs.
LISTEN/NOTIFY is a lightweight publish/subscribe channel. A session that runs LISTEN jobs receives a notification when another session runs NOTIFY jobs (or pg_notify('jobs', ...)) and commits. Notifications aren't stored. A worker that's disconnected when one is sent never sees it. Treat a notification as a hint ("check the table now"), never as the job itself.
Step 1: The Jobs Table
CREATE TABLE jobs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
queue text NOT NULL DEFAULT 'default',
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'running', 'done', 'dead')),
run_at timestamptz NOT NULL DEFAULT now(), -- when it may next run
attempts int NOT NULL DEFAULT 0,
max_attempts int NOT NULL DEFAULT 5,
locked_until timestamptz, -- lease expiry while running
last_error text,
created_at timestamptz NOT NULL DEFAULT now()
);
-- Only rows a worker might pick up are indexed, so the index stays small.
CREATE INDEX jobs_ready_idx ON jobs (queue, run_at) WHERE status = 'pending';
CREATE INDEX jobs_running_idx ON jobs (locked_until) WHERE status = 'running';Retries reuse the pending status with a future run_at, so the claim query only needs to handle one case.
Step 2: Enqueue and Notify
A trigger sends the notification, so every insert wakes workers no matter which code path created the job:
CREATE OR REPLACE FUNCTION notify_new_job() RETURNS trigger AS $$
BEGIN
PERFORM pg_notify('jobs_' || NEW.queue, '');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER jobs_notify
AFTER INSERT ON jobs
FOR EACH ROW EXECUTE FUNCTION notify_new_job();Enqueue inside the same transaction as the business change:
BEGIN;
INSERT INTO users (email) VALUES ('new@example.com');
INSERT INTO jobs (queue, payload)
VALUES ('email', '{"type": "welcome", "email": "new@example.com"}');
COMMIT; -- the notification is delivered only nowPostgreSQL delivers notifications on commit, and drops duplicate notifications with the same channel and payload within one transaction. A bulk insert of 1,000 jobs wakes workers once, not 1,000 times.
Step 3: Claim a Job
The claim runs in its own short transaction: select the next ready job with SKIP LOCKED, mark it running with a lease, and commit.
UPDATE jobs
SET status = 'running',
attempts = attempts + 1,
locked_until = now() + interval '5 minutes'
WHERE id = (
SELECT id FROM jobs
WHERE queue = %(queue)s
AND status = 'pending'
AND run_at <= now()
ORDER BY run_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id, payload, attempts, max_attempts;The row lock only has to last until this statement commits. After that, the running status and the lease keep other workers away, so the job itself runs outside any open transaction. Holding a transaction open for the whole job (a common shortcut) ties up a connection, and long-running transactions stop vacuum from cleaning up dead rows across the entire database.
⚠️ Common mistake: Running the claim with autocommit turned on and separate
SELECT ... FOR UPDATEandUPDATEstatements. With autocommit, each statement is its own transaction, so the row lock is released the moment theSELECTfinishes, and two workers can claim the same job. Either use a singleUPDATE ... WHERE id = (SELECT ... FOR UPDATE SKIP LOCKED)statement as shown, or wrap both statements in an explicit transaction.
Step 4: The Worker
import json
import os
import traceback
import psycopg
DSN = os.environ["DATABASE_URL"]
QUEUE = "email"
CLAIM_SQL = """...""" # the UPDATE ... RETURNING statement from Step 3
def handle(payload: dict) -> None:
... # send the email, call the webhook, etc. Must be safe to run twice.
def claim(conn):
with conn.transaction():
return conn.execute(CLAIM_SQL, {"queue": QUEUE}).fetchone()
def finish(conn, job_id):
with conn.transaction():
conn.execute("UPDATE jobs SET status = 'done', locked_until = NULL WHERE id = %s", (job_id,))
def fail(conn, job_id, attempts, max_attempts, error):
with conn.transaction():
if attempts >= max_attempts:
conn.execute(
"UPDATE jobs SET status = 'dead', locked_until = NULL, last_error = %s WHERE id = %s",
(error, job_id),
)
else:
# Exponential backoff: 30s, 60s, 120s, ...
conn.execute(
"""UPDATE jobs
SET status = 'pending', locked_until = NULL, last_error = %s,
run_at = now() + make_interval(secs => 30 * power(2, %s - 1))
WHERE id = %s""",
(error, attempts, job_id),
)
def drain(conn):
"""Process jobs until none are ready."""
while (job := claim(conn)) is not None:
job_id, payload, attempts, max_attempts = job
try:
handle(payload)
except Exception:
fail(conn, job_id, attempts, max_attempts, traceback.format_exc(limit=5))
else:
finish(conn, job_id)
def main():
# A separate autocommit connection for LISTEN: notifications only arrive
# while the listening session is not inside a transaction.
listener = psycopg.connect(DSN, autocommit=True)
listener.execute(f"LISTEN jobs_{QUEUE}")
work = psycopg.connect(DSN, autocommit=True) # transactions are explicit above
while True:
drain(work)
# Sleep until notified, or 30s at most. The timeout catches retries
# whose run_at has arrived and any notification we missed.
for _ in listener.notifies(timeout=30, stop_after=1):
pass
if __name__ == "__main__":
main()The worker drains everything that's ready, then blocks on listener.notifies(). A new job wakes it within milliseconds, and the 30-second timeout picks up scheduled retries and anything sent while it was busy or reconnecting. Run as many worker processes as you need. SKIP LOCKED keeps them from colliding.
Step 5: Recover Jobs from Crashed Workers
If a worker dies mid-job, its job stays running. The lease makes that recoverable. Run this periodically (from a cron job, pg_cron, or at the start of each drain):
UPDATE jobs
SET status = 'pending', locked_until = NULL,
last_error = 'lease expired (worker crashed or job exceeded timeout)'
WHERE status = 'running' AND locked_until < now();Two consequences follow:
- Jobs must be idempotent. A worker can finish the work and crash before marking the job
done, and the job will run again. Use idempotency keys for external calls (most payment and email APIs accept one) or check whether the work was already done. - Size the lease to your slowest job. For long jobs, extend
locked_untilperiodically while working (a heartbeat) rather than setting a huge lease that delays recovery.
When to Use a Dedicated Queue Instead
A PostgreSQL queue comfortably handles hundreds of jobs per second on modest hardware, and the transactional enqueue is a real advantage. Consider a dedicated broker or streaming system when you need sustained throughput in the thousands per second, fan-out to many independent consumers, or long retention and replay of events. Also watch table bloat: completed jobs leave dead rows, so delete or archive done jobs regularly and make sure autovacuum keeps up on the jobs table.
Before writing your own, look at existing libraries built on these same techniques: for example Procrastinate for Python, graphile-worker for Node.js, River for Go and Oban for Elixir.
Summary
- Claim jobs with one
UPDATE ... WHERE id = (SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1)statement in a short transaction. Advisory locks aren't needed. - Run the job outside the transaction, protected by a
runningstatus and a lease (locked_until). - Use
LISTEN/NOTIFYonly as a wake-up signal, with a polling timeout as backup. - Make jobs idempotent, retry with backoff, and move jobs to
deadaftermax_attempts. - Clean up finished jobs so the table doesn't bloat.
