Skip to content

How to Build a Job Queue in Postgres and Python

Build a Postgres job queue in Python with SKIP LOCKED, leases, retries and LISTEN/NOTIFY, tested in Docker, and learn when a library or a broker fits better.

26 min read

Just when you didn't expect to wait in a queue

Almost every web app has work that shouldn't happen while the customer waits, like a receipt email after checkout. The first version is usually a cron job with a hero complex. Every minute, a script looks for orders without a receipt, sends one for each and marks them sent. It works for months. Nobody calls it a Postgres job queue yet, but that's what it is slowly becoming.

Then the shop has a good week. The script takes longer than a minute, so runs overlap, and both read the same list of unsent orders. A customer buys one birthday cake and gets four receipts for it, which is generous with the paperwork if nothing else. Next comes a worker that dies mid-email and leaves its order stuck, then an email provider that times out on a Friday.

The usual advice at this point is to bring in a broker such as Redis, RabbitMQ or Amazon SQS. If you already run PostgreSQL, you often don't need one.

A jobs table with SKIP LOCKED, a lease, a retry policy and a NOTIFY to wake workers is a durable queue that commits in the same transaction as your data: one fewer system to run and pay for, and no receipt for an order that rolled back. The cost is owning the failure handling and upkeep, or adopting a library that does. You need a broker when throughput, fan-out or replay outgrow one table; the numbers are near the end.

In this tutorial, you'll build a Postgres job queue in Python for a small online bakery, starting from that cron job; each step fixes the failure the last one exposed. I broke the lab on my laptop on purpose, so every output here is real. The full lab is in ShahidYousufBlogLabs. Tested with PostgreSQL 18.7, Python 3.14.10 and psycopg 3.3.9. PostgreSQL 19.0 shipped on 2026-11-19; nothing here depends on it.

How a Postgres Job Queue Works#

Step into the bakery's back room, where you'll spend the whole tutorial. On the wall hangs a whiteboard of order tickets. A baker takes a ticket, writes her name and a finish time on it, and crosses it off when the cake is boxed. If the time passes with her name still there, the shift lead wipes it and puts the ticket back up. A cake that keeps failing goes to the manager's pile instead.

A Postgres job queue is that whiteboard as a table, one row per ticket. A worker claims a row by writing its name and a deadline, the lease, in one short transaction, works with no transaction open, then marks the row done:

flowchart TB E[Order commits] -->|enqueue| Q[queued] Q -->|claim with lease| R[running] R -->|finish| D[done] R -->|fail, or lease expires| Q R -->|out of attempts| X[dead]

The life of a job. After the enqueue, every arrow is one short UPDATE.

Prerequisites#

Step 1: Set Up the Bakery Lab#

The lab is a PostgreSQL container and an app container with Python and psycopg. Clone it:

git clone https://github.com/ShahidYousuf/ShahidYousufBlogLabs.git
cd ShahidYousufBlogLabs/postgres-job-queue-python
docker-compose.yml
services:
  db:
    image: postgres:18.7
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: app
      POSTGRES_DB: shop
    volumes:
      - ./schema.sql:/docker-entrypoint-initdb.d/schema.sql:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -h localhost -U app -d shop"]
      interval: 1s
      timeout: 3s
      retries: 30

  app:
    build: .
    environment:
      DATABASE_URL: postgresql://app:app@db:5432/shop
    volumes:
      - .:/lab
    working_dir: /lab
    depends_on:
      db:
        condition: service_healthy

orders is the shop counter, jobs is the whiteboard, and emails_sent is every customer's inbox in one place, so you can count what each customer received:

schema.sql
CREATE TABLE orders (
    id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer   text        NOT NULL,
    total      int         NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

-- Stands in for the email provider: one row per email "sent".
CREATE TABLE emails_sent (
    id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    order_id bigint      NOT NULL,
    worker   text        NOT NULL,
    sent_at  timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE jobs (
    id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    kind         text        NOT NULL,
    payload      jsonb       NOT NULL DEFAULT '{}',
    status       text        NOT NULL DEFAULT 'queued'
        CHECK (status IN ('queued', 'running', 'done', 'dead')),
    attempts     int         NOT NULL DEFAULT 0,
    max_attempts int         NOT NULL DEFAULT 5,
    run_at       timestamptz NOT NULL DEFAULT now(),
    locked_by    text,
    locked_until timestamptz,
    last_error   text,
    created_at   timestamptz NOT NULL DEFAULT now(),
    finished_at  timestamptz
);

-- Workers only ever look for ready jobs, and the reaper for
-- expired leases, so each gets a small partial index.
CREATE INDEX jobs_ready ON jobs (run_at, id) WHERE status = 'queued';
CREATE INDEX jobs_leased ON jobs (locked_until)
    WHERE status = 'running';

Look at the two indexes first; the columns come one step at a time. They're partial indexes, covering only rows that match their WHERE: jobs_ready is a short list pinned beside the board with only the open tickets on it, so nobody reads months of crossed-out ones to find the next cake.

The list has a catch for Python code. PostgreSQL matches a query to a partial index when it plans the query, and the partial index docs put it bluntly:

As a result, parameterized query clauses do not work with a partial index.

psycopg 3 prepares a query on the server after five runs. If the claim said status = %s, then once PostgreSQL switches that prepared statement to a generic plan, the planner can't prove the parameter matches the index's WHERE, and the claim falls back to scanning the table. So every query here writes status = 'queued' as a literal.

Start the database, build the app image and place the first 200 orders:

docker compose up -d --wait db
docker compose build app
docker compose run --rm app python seed.py 200
Output
placed 200 orders, queued 200 receipt jobs

Each order and its ticket went in one transaction, which pays off in Step 7. You have 200 tickets up and nobody baking.

Step 2: Send Every Receipt Four Times#

Start with the cron job: look at the board, take the top ticket, bake, cross it off. Now put four bakers on it at once, as happens once cron runs start piling on top of each other:

naive.py
"""The cron-job queue: find a pending job, do it, mark it done."""

import os
import sys
import threading
import time

import psycopg

DSN = os.environ["DATABASE_URL"]


def send_receipt(conn, order_id, worker):
    time.sleep(0.05)  # talking to the email provider
    conn.execute(
        "INSERT INTO emails_sent (order_id, worker) VALUES (%s, %s)",
        (order_id, worker),
    )


def work(name):
    with psycopg.connect(DSN, autocommit=True) as conn:
        while True:
            job = conn.execute(
                "SELECT id, payload FROM jobs WHERE status = 'queued'"
                " ORDER BY id LIMIT 1"
            ).fetchone()
            if job is None:
                return
            job_id, payload = job
            send_receipt(conn, payload["order_id"], name)
            conn.execute(
                "UPDATE jobs SET status = 'done' WHERE id = %s",
                (job_id,),
            )


workers = int(sys.argv[1]) if len(sys.argv) > 1 else 4
threads = [
    threading.Thread(target=work, args=(f"w{i}",))
    for i in range(1, workers + 1)
]
start = time.monotonic()
for t in threads:
    t.start()
for t in threads:
    t.join()
print(f"{workers} workers done in {time.monotonic() - start:.1f}s")

Watch the SELECT: it reads the top ticket without marking it taken. (time.sleep(0.05) is 50 ms of talking to the email provider.)

Before you run it, guess: 200 orders, four workers. How many emails go out?

docker compose run --rm app python naive.py 4
docker compose exec -T db psql -U app -d shop < report.sql
report.sql
SELECT count(DISTINCT order_id) AS orders_emailed,
       count(*) AS emails_sent,
       count(*) - count(DISTINCT order_id) AS duplicates
FROM emails_sent;
Output
4 workers done in 11.1s
 orders_emailed | emails_sent | duplicates
----------------+-------------+------------
            200 |         800 |        600

All four bakers baked the same top ticket before anyone crossed it off. Every customer got four receipts for one cake, in the time one worker would take, so the extra staff bought nothing except embarrassment. The real flaw: reading a job doesn't claim it.

Step 3: Lock the Row, Then Skip Locked Rows#

The first fix most of us reach for is a good instinct: let the first baker keep a hand on his ticket, so nobody else can take it until he lets go.

In SQL, the hand on the ticket is a row lock, and FOR NO KEY UPDATE asks for one. A row lock lasts until the transaction ends, so with conn.transaction(): keeps the hand on the ticket until the receipt is recorded:

locked.py (excerpt)
DSN = os.environ["DATABASE_URL"]
SKIP = "--skip-locked" in sys.argv
CLAIM = (
    "SELECT id, payload FROM jobs WHERE status = 'queued'"
    " ORDER BY id LIMIT 1 FOR NO KEY UPDATE"
    + (" SKIP LOCKED" if SKIP else "")
)


def work(name):
    with psycopg.connect(DSN) as conn:
        while True:
            with conn.transaction():
                job = conn.execute(CLAIM).fetchone()
                if job is None:
                    return
                job_id, payload = job
                time.sleep(0.05)  # talking to the email provider
                conn.execute(
                    "INSERT INTO emails_sent (order_id, worker)"
                    " VALUES (%s, %s)",
                    (payload["order_id"], name),
                )
                conn.execute(
                    "UPDATE jobs SET status = 'done' WHERE id = %s",
                    (job_id,),
                )

You might think locking the row is enough. For correctness, it is. Now guess the speed: one worker (python locked.py 1) needs 11.2 seconds for 200 receipts, so four should need about three, right?

docker compose exec -T db psql -U app -d shop < reset.sql
docker compose run --rm app python seed.py 200
docker compose run --rm app python locked.py 4
docker compose exec db psql -U app -d shop -c "SELECT worker, count(*) FROM emails_sent GROUP BY worker ORDER BY worker"
Output
4 workers done in 11.1s
 worker | count
--------+-------
 w1     |    48
 w2     |    80
 w4     |    72

No duplicates, and the speed of one baker. All four reach for the top ticket; one gets it, and three stand with their hands out until he's done. You've built a very expensive single worker.

And where is w3? It never got past its first SELECT. It waited on a held ticket, and under READ COMMITTED a waiting statement rechecks the row once the holder commits, per the transaction isolation docs:

The search condition of the command (the WHERE clause) is re-evaluated to see if the updated version of the row still matches the search condition.

The ticket was crossed off by then, so w3 moved to the next, found another hand on it, waited, lost again, and kept chasing tickets until the board was empty: eleven seconds queueing for the queue. Waiting statements get no fair turn; in my runs the unluckiest worker sent between 0 and 34 receipts.

The bakers need permission to ignore a held ticket and take the next free one. That's SKIP LOCKED, and --skip-locked adds it to the claim:

docker compose exec -T db psql -U app -d shop < reset.sql
docker compose run --rm app python seed.py 200
docker compose run --rm app python locked.py 4 --skip-locked
Output
4 workers done in 2.7s

Now the bakers spread across the board, 50 cakes each. The SELECT reference names this use, with a warning worth reading twice:

Skipping locked rows provides an inconsistent view of the data, so this is not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue-like table.

Fine for a board of independent tickets; wrong for a report that has to add up.

Why FOR NO KEY UPDATE and not FOR UPDATE?

FOR UPDATE also blocks FOR KEY SHARE, the lock a foreign key check takes, so an insert into a child table referencing jobs.id (a job_logs table, say) would wait for the job to finish. FOR NO KEY UPDATE is the lock a plain UPDATE takes anyway and still stops two workers claiming one row: the weakest lock that does the job.

The claim is correct and fast. The problem left is the transaction around the baking: a provider that hangs for 30 seconds pins a connection and an open transaction per job, and Step 8 shows what that does to cleanup. The baker needs to let go of the board while he bakes.

Step 4: Claim with a Lease, Then Let Go of the Database#

A real baker doesn't hold a ticket for an hour. They write their name and a finish time on it and walk off to bake; anyone glancing at the board sees it's taken, and until when. That note is the lease, and it turns one long transaction into two short ones with the work in between: claim, work with nothing open, record the result.

The claim writes that note: Step 3's SKIP LOCKED select sits in a WITH query that PostgreSQL runs once, and the UPDATE writes the name (locked_by), the finish time (locked_until) and one more tick on attempts:

pgqueue.py (excerpt)
CLAIM = """
WITH next AS (
    SELECT id
    FROM jobs
    WHERE status = 'queued' AND run_at <= now()
    ORDER BY run_at, id
    LIMIT 1
    FOR NO KEY UPDATE SKIP LOCKED
)
UPDATE jobs
SET status = 'running',
    attempts = jobs.attempts + 1,
    locked_by = %(worker)s,
    locked_until = now() + %(lease)s
FROM next
WHERE jobs.id = next.id
RETURNING jobs.id, jobs.kind, jobs.payload, jobs.attempts,
          jobs.max_attempts
"""

# The attempts check is a fence: if this worker's lease expired and
# someone else claimed the job, attempts has moved on and we change
# nothing.
FINISH = """
UPDATE jobs
SET status = 'done', finished_at = now(),
    locked_by = NULL, locked_until = NULL
WHERE id = %(id)s AND status = 'running' AND attempts = %(attempts)s
"""

The worker's connection runs in autocommit, so the claim commits at once and Step 3's row lock now lasts one statement.

Now the last line of FINISH: a baker crossing off a ticket must show the attempt number they claimed it with. Every claim bumps attempts, so that number is a fencing token: if their lease ran out and someone else took the ticket, their FINISH changes nothing. In the worker, a job is a claim, a handler call, then a finish or a fail:

worker.py (excerpt)
def run_one(conn, worker, args):
    job = claim(conn, worker, timedelta(seconds=args.lease))
    if job is None:
        return False
    job_id, kind, payload, attempts, max_attempts = job
    if args.crash:
        print(f"{worker}: claimed job {job_id}, crashing now")
        os._exit(1)
    try:
        HANDLERS[kind](conn, job_id, payload, attempts, worker)
    except Exception as exc:
        delay = timedelta(seconds=backoff(attempts, base=args.base))
        status = fail(conn, job_id, attempts, repr(exc), delay)
        print(
            f"{worker}: job {job_id} attempt {attempts}/{max_attempts}"
            f" failed ({exc}), now {status}"
        )
        if args.trace:
            traceback.print_exc()
    else:
        if not finish(conn, job_id, attempts):
            print(f"{worker}: lost the lease on job {job_id}")
    return True

Run four workers on fresh orders and check the receipts in one go:

docker compose exec -T db psql -U app -d shop < reset.sql
docker compose run --rm app python seed.py 200
docker compose run --rm app python worker.py --workers 4 --drain --poll 0.5
docker compose exec -T db psql -U app -d shop < report.sql
docker compose exec db psql -U app -d shop -c "SELECT worker, count(*) FROM emails_sent GROUP BY worker ORDER BY worker"
Output
workers: 4, stopped after 3.8s
 orders_emailed | emails_sent | duplicates
----------------+-------------+------------
            200 |         200 |          0

 worker | count
--------+-------
 w1     |    50
 w2     |    50
 w3     |    50
 w4     |    50

Step 3's result, 200 receipts and no duplicates, now without holding a transaction open: 2.9 to 3.8 seconds across my runs, against about 11.4 for one worker. Now try 8 workers and 1,000 orders, with fresh statistics to see which indexes the claim used:

docker compose exec -T db psql -U app -d shop < reset.sql
docker compose run --rm app python seed.py 1000
docker compose exec db psql -U app -d shop -c "SELECT pg_stat_reset()"
docker compose run --rm app python worker.py --workers 8 --drain --poll 0.5
docker compose exec db psql -U app -d shop -c "SELECT indexrelname, idx_scan FROM pg_stat_user_indexes WHERE relname = 'jobs'"
Output
workers: 8, stopped after 8.2s
 indexrelname | idx_scan
--------------+----------
 jobs_pkey    |     1176
 jobs_ready   |     1012
 jobs_leased  |     1016

The jobs_ready scans show the prepared claim kept using the short list, which is what writing 'queued' as a literal protects. The run takes 7.2 to 8.2 seconds across my runs.

I ran a control: same claim, no SKIP LOCKED. In Step 3, adding it turned 11 seconds into under three; here, removing it, two runs took 3.8 and 2.8 seconds, no duplicates, 50 jobs per worker. No measurable difference, because nobody holds a ticket long enough to wait on. It earns its keep when locks are held longer or contention is heavy, and I keep it anyway: it costs nothing.

But the bakers now hold nothing a crash would release. What happens when one walks out mid-cake?

Step 5: Crash a Worker Mid-Job#

In Step 3, a crash would have rolled back and freed the ticket. Now nothing is open to roll back. Picture the board after a baker leaves halfway through a cake: what does her ticket say? --crash claims a job and exits on the spot, like a kill -9; a 10-second lease keeps the wait short:

docker compose exec -T db psql -U app -d shop < reset.sql
docker compose run --rm app python seed.py 5
docker compose run --rm app python worker.py --crash --lease 10
docker compose exec db psql -U app -d shop -c "SELECT id, status, attempts, locked_by, locked_until > now() AS lease_active FROM jobs WHERE id = 1"
Output
w1: claimed job 1, crashing now
 id | status  | attempts | locked_by | lease_active
----+---------+----------+-----------+--------------
  1 | running |        1 | w1        | t

Job 1 is now the most dedicated employee on the payroll: officially running, with nobody doing the work. The finish time is what lets the shift lead notice. His round: any running ticket whose time has passed goes back on the board, or to the manager's pile if it's out of attempts:

pgqueue.py (excerpt)
# Jobs whose worker vanished: the lease ran out without a finish or
# a fail. Back in the queue they go, or to the dead pile if they
# have used up their attempts.
REAP = """
UPDATE jobs
SET status = CASE WHEN attempts >= max_attempts
                  THEN 'dead' ELSE 'queued' END,
    last_error = 'lease expired',
    locked_by = NULL, locked_until = NULL
WHERE status = 'running' AND locked_until < now()
RETURNING id, status
"""

Every worker does that round on a timer (--reap-every, five seconds by default) before it claims:

worker.py (excerpt)
def work(worker, args):
    with (
        psycopg.connect(DSN, autocommit=True) as conn,
        psycopg.connect(DSN, autocommit=True) as listener,
    ):
        listener.execute("LISTEN jobs")
        last_reap = 0.0
        while not stop.is_set():
            # Reap on a timer: a busy queue never goes idle.
            if time.monotonic() - last_reap >= args.reap_every:
                for job_id, status in reap(conn):
                    print(f"{worker}: lease expired on job {job_id}, {status}")
                last_reap = time.monotonic()
            if run_one(conn, worker, args):
                continue
            if args.drain and outstanding(conn) == 0:
                return
            wait_for_work(listener, args.poll)

The timer matters because a busy queue never goes idle: a shift lead who only checked the board when there was nothing to bake would leave a dead worker's job stuck until the rush ended.

Start a healthy worker:

docker compose run --rm app python worker.py --drain --lease 10
docker compose exec db psql -U app -d shop -c "SELECT id, status, attempts, last_error FROM jobs WHERE id = 1"
Output
w1: lease expired on job 1, queued
workers: 1, stopped after 10.3s
 id | status | attempts |  last_error
----+--------+----------+---------------
  1 | done   |        2 | lease expired

Job 1 waited out its lease, got requeued and finished on its second attempt. Five customers, five receipts.

Now the awkward question: what if the first baker was only slow, and walks back in with a cake? check_fence.py stages that with an already expired lease:

check_fence.py
"""A worker whose lease ran out must not mark the job done."""

import os
from datetime import timedelta

import psycopg

from pgqueue import claim, enqueue, finish, reap

with psycopg.connect(os.environ["DATABASE_URL"], autocommit=True) as c:
    enqueue(c, "send_receipt", {"order_id": 0})
    slow = claim(c, "slow", timedelta(seconds=-1))  # already expired
    print("reaped:", reap(c))
    fast = claim(c, "fast")
    print("slow finishes:", finish(c, slow[0], slow[3]))
    print("fast finishes:", finish(c, fast[0], fast[3]))
Output
reaped: [(1, 'queued')]
slow finishes: False
fast finishes: True

The late baker's attempt number no longer matches, so her FINISH changes nothing. Notice what the fence protects: the ticket, not the customer. If the slow worker had already sent its email, the customer still gets two. A lease can't prove the old owner stopped, the same lesson as in the Redis distributed locks tutorial.

Plan for every job to run twice

A lease makes the queue at-least-once: a worker can do the work and die before FINISH, and the job runs again. Make every handler idempotent, for example with a unique key per receipt checked before sending. The idempotency keys tutorial shows the pattern in full. Set the lease well above your slowest job too, or healthy jobs get reaped mid-flight.

For cakes longer than any sensible lease, let the baker say "still on it" with a heartbeat that pushes locked_until forward every few seconds, under the same attempts check. Procrastinate's workers update heartbeats every 10 seconds by default; jobs of a worker that stops count as stalled and can be retried.

Want your own queue checked?

Duplicate and stuck jobs rarely show up in a test with one worker. I offer a focused review of background job systems, on PostgreSQL or a broker: how jobs are claimed and leased, what happens when a worker dies mid-job, retries and dead jobs, and whether handlers are idempotent, with a crash test like this step's and written findings. Ask for a job queue review or book a free 20-minute intro call.

Step 6: Retry a Flaky Email Provider with Backoff#

Some cakes fail through no fault of the baker: email providers time out. Retrying at once backfires, since a struggling provider fails again and a hundred workers retrying in step make it worse. The baker puts a failed ticket back herself, with a note saying "not before 3:15". Each time she picks that time at random from a window that doubles, until the ticket goes to the manager.

FAIL writes that note. The job returns to queued with a later run_at, or goes to dead once attempts reaches max_attempts:

pgqueue.py (excerpt)
FAIL = """
UPDATE jobs
SET status = CASE WHEN attempts >= max_attempts
                  THEN 'dead' ELSE 'queued' END,
    run_at = now() + %(delay)s,
    last_error = %(error)s,
    locked_by = NULL, locked_until = NULL
WHERE id = %(id)s AND status = 'running' AND attempts = %(attempts)s
RETURNING status
"""

The wait is exponential backoff with full jitter: a random time between zero and a ceiling that doubles with each attempt. The randomness keeps failed jobs from retrying in lockstep, as the AWS Builders' Library on retries and jitter explains:

pgqueue.py (excerpt)
def backoff(attempts, base=2.0, cap=300.0):
    """Exponential backoff with full jitter, in seconds."""
    return random.uniform(0, min(cap, base * 2 ** (attempts - 1)))

flaky.py queues two receipts for a provider having a bad day: gita's fails twice, then works; hamza's never works. A small --base keeps the wait short:

docker compose exec -T db psql -U app -d shop < reset.sql
docker compose run --rm app python flaky.py
docker compose run --rm app python worker.py --drain --base 0.5 --poll 0.5
Output
w1: job 1 attempt 1/5 failed (email provider timed out), now queued
w1: job 2 attempt 1/5 failed (email provider timed out), now queued
w1: job 1 attempt 2/5 failed (email provider timed out), now queued
w1: job 2 attempt 2/5 failed (email provider timed out), now queued
w1: job 2 attempt 3/5 failed (email provider timed out), now queued
w1: job 2 attempt 4/5 failed (email provider timed out), now queued
w1: job 2 attempt 5/5 failed (email provider timed out), now dead
workers: 1, stopped after 6.1s

gita's receipt went out on its third attempt (successes don't print). hamza's gave up after five tries, which is more patience than most of us show an email provider, and sits on the manager's pile with its last error for a person to look at. Alert on any dead job: a dead receipt is a customer who never heard from you.

Step 7: Enqueue with the Order and Wake Workers with NOTIFY#

In a real shop, tickets go up during checkout. What if the order fails after its ticket goes up? And how do bakers hear about a new ticket without staring at the board?

First, pin the ticket to the order slip, so both go up together or neither does. enqueue takes the caller's connection, so the job joins whatever transaction the order is in:

pgqueue.py (excerpt)
def enqueue(conn, kind, payload, delay=timedelta(0)):
    """Add a job inside the caller's transaction."""
    row = conn.execute(
        "INSERT INTO jobs (kind, payload, run_at)"
        " VALUES (%s, %s, now() + %s) RETURNING id",
        (kind, Jsonb(payload), delay),
    ).fetchone()
    conn.execute("SELECT pg_notify('jobs', %s)", (kind,))
    return row[0]

That's the database queue's biggest advantage over a broker, where a crash between committing and publishing loses the receipt, and publishing first can announce an order that later rolls back. Here both commit or neither does; the outbox tutorial covers that dual-write problem in depth.

Second, a bell. pg_notify in enqueue queues a ring on the jobs channel, and PostgreSQL only rings it if the transaction commits, so a torn-up order makes no sound. Each worker's second connection runs LISTEN jobs, and wait_for_work dozes on it in one-second slices:

worker.py (excerpt)
def wait_for_work(listener, seconds):
    """Sleep until a NOTIFY arrives, the timeout passes, or we stop."""
    deadline = time.monotonic() + seconds
    while not stop.is_set() and time.monotonic() < deadline:
        for _ in listener.notifies(timeout=1, stop_after=1):
            return

checkout.py places two orders: ivan's is declined at payment, jaya's goes through:

checkout.py
"""One order that fails at checkout, and one that succeeds."""

import os

import psycopg

from pgqueue import enqueue


def place_order(conn, customer, total):
    with conn.transaction():
        order_id = conn.execute(
            "INSERT INTO orders (customer, total)"
            " VALUES (%s, %s) RETURNING id",
            (customer, total),
        ).fetchone()[0]
        enqueue(conn, "send_receipt", {"order_id": order_id})
        if total <= 0:
            raise ValueError("payment declined")
    return order_id


with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
    try:
        place_order(conn, "ivan", 0)
    except ValueError as exc:
        print(f"ivan's order rolled back: {exc}")
    print(f"jaya's order {place_order(conn, 'jaya', 45)} committed")

Start two workers that look at the board on their own only every 30 seconds, so a fast receipt means the bell did it. Give them a few seconds, then check out:

docker compose exec -T db psql -U app -d shop < reset.sql
docker compose run -d --name pgq-worker app python worker.py --workers 2 --poll 30
docker compose run --rm app python checkout.py
docker compose exec -T db psql -U app -d shop < latency.sql
Output
ivan's order rolled back: payment declined
jaya's order 2 committed
 customer | seconds_to_receipt
----------+--------------------
 jaya     |               0.05

ivan's declined order left no ticket behind, so no receipt for a cake he never bought. jaya's receipt landed 0.05 seconds after her order, with the workers up to 30 seconds from their next look. The handler spends 50 ms faking the email call, so the wake-up and claim took only a few milliseconds.

The bell is a hint, never delivery; a baker in the walk-in freezer doesn't hear it. Keep polling as the source of truth:

Limit What it means for a queue
Not durable A worker that is disconnected or restarting misses notifications. Polling catches what it missed.
Delivered only between transactions A listener stuck inside a long transaction hears nothing until it ends.
Commits take turns A transaction that ran NOTIFY takes a cluster-wide lock at commit, so these commits run one at a time. Under heavy write load, that lock becomes the bottleneck. PostgreSQL 19 wakes only backends that are listening, but the commit lock remains.
The queue can fill Unread notifications wait in a queue of about 8GB. A listener stuck in a long transaction stops its cleanup, and once it's full, NOTIFY fails at commit, which here would fail the checkout itself.
No PgBouncer transaction mode PgBouncer can't forward LISTEN in transaction pooling, so the listener needs a direct connection.

The one-second slices pay off again at closing time. On SIGTERM the worker sets a flag, finishes the cake in hand, and stops claiming:

time docker stop pgq-worker
docker logs pgq-worker
docker rm pgq-worker
Output
real    0m0.912s
workers: 2, stopped after 5.2s

Under a second. In my first version the worker sat in a single 30-second notifies() call, never saw the flag, and Docker had to kill it. A worker killed mid-job is what the lease is for. What's left is the board itself, and what it quietly fills up with.

Step 8: Keep the Jobs Table Healthy#

PostgreSQL never edits a ticket in place. Every UPDATE writes a fresh copy of the row and leaves the old copy behind, greyed out, until VACUUM, the cleaner, throws it away. Guess how many dead versions 1,000 jobs leave, then measure:

docker compose exec -T db psql -U app -d shop < reset.sql
docker compose run --rm app python seed.py 1000
docker compose exec db psql -U app -d shop -c "SELECT pg_stat_reset()"
docker compose run --rm app python worker.py --workers 8 --drain --poll 0.5
docker compose exec db psql -U app -d shop -c "SELECT n_tup_upd, n_tup_hot_upd, n_dead_tup FROM pg_stat_user_tables WHERE relname = 'jobs'"
Output
 n_tup_upd | n_tup_hot_upd | n_dead_tup
-----------+---------------+------------
      2000 |             0 |       2000

Two per job, from the claim and the finish. None were HOT updates, the cheaper kind that skips index maintenance, because both change status, which both partial indexes filter on, and locked_until, a key of jobs_leased. Autovacuum cleans up this churn on its own, as long as nothing holds it back.

The cleaner has one rule: she can't throw away an old copy while someone might still need it. That someone is usually an open transaction. Picture a colleague who runs a quick data fix and goes to lunch without committing:

forgotten.py
"""A one-off data fix that never got its commit."""

import os
import time

import psycopg

conn = psycopg.connect(os.environ["DATABASE_URL"])  # not autocommit
conn.execute("UPDATE orders SET customer = 'ayesha' WHERE id = 1")
print("fixed a typo, back after lunch")
time.sleep(600)  # no commit: the transaction stays open

Start the lunch break, run 1,000 orders, and check health.sql:

docker compose exec -T db psql -U app -d shop < reset.sql
docker compose run --rm app python seed.py 1000
docker compose run -d --name lunch app python forgotten.py
docker compose run --rm app python worker.py --workers 8 --drain --poll 0.5
docker compose exec -T db psql -U app -d shop < health.sql
health.sql
SELECT n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'jobs';

SELECT pid, state, now() - xact_start AS open_for
FROM pg_stat_activity
WHERE xact_start < now() - interval '10 seconds'  -- minutes in production
ORDER BY xact_start;
Output
 n_live_tup | n_dead_tup |        last_autovacuum
------------+------------+-------------------------------
       1000 |       2048 | 2026-12-01 05:24:05.947376+00

 pid  |        state        |    open_for
------+---------------------+-----------------
 1085 | idle in transaction | 00:00:11.566384

Autovacuum has been through, and the dead rows are still there; the second result shows who's in the way. (If it's empty, your drain was quicker than mine; run health.sql again in a few seconds.) Ask docker compose exec db psql -U app -d shop -c "VACUUM (VERBOSE) jobs" and it says so outright:

Output
tuples: 0 removed, 3000 remain, 2000 are dead but not yet removable

The data fix touched orders, not jobs, and still froze cleanup of the queue. PostgreSQL can't remove a row version an open transaction might still need, and a transaction that has written something holds that line for every table in the database. End the lunch break with docker rm -f lunch and run VACUUM again:

Output
tuples: 2000 removed, 1000 remain, 0 are dead but not yet removable

Left open for a day on a busy queue, it grows the table and its indexes, and every claim scans past more dead rows.

You might expect any open transaction to block the cleaner. I did. My first forgotten transaction had only run a SELECT, and VACUUM removed everything anyway: at READ COMMITTED, an idle transaction that hasn't written anything holds no snapshot between statements. The ones that hurt have written a row, run at REPEATABLE READ, or are one long query.

Guardrails for the jobs table

  • Set idle_in_transaction_session_timeout for application and human roles, so a forgotten BEGIN ends itself. It's off by default.
  • If jobs keeps history, lower its autovacuum_vacuum_scale_factor with ALTER TABLE ... SET (...); the default waits for 20% of the table to be dead.
  • On replicas, hot_standby_feedback lets long replica queries cause bloat on the primary.

Crossed-out tickets are history, not queue; remove them on a schedule:

cleanup.sql
-- Finished jobs are history, not queue. Keep a week of it.
DELETE FROM jobs
WHERE status = 'done' AND finished_at < now() - interval '7 days';

With history in the table, this and monitor.sql scan all of it, so index finished_at if you keep months; beyond that, partition by time and drop old partitions, which per the partitioning docs avoids the VACUUM work of a bulk DELETE. Last, a view of the board from your desk:

monitor.sql
SELECT status,
       count(*) AS jobs,
       max(now() - run_at) FILTER (WHERE status = 'queued')
           AS oldest_waiting
FROM jobs
GROUP BY status
ORDER BY status;

Alert when oldest_waiting keeps growing (workers down or too few), when anything lands on the manager's pile, and when health.sql shows a transaction open for minutes. When you're done, remove the lab and its data with docker compose down -v.

Extending the queue#

The lab keeps the queue small on purpose. The usual next needs, and where each goes:

Need Change
Production connections Each worker thread here holds two connections, one for LISTEN; in a real service, share one listener per process and take job connections from a psycopg_pool pool
Several jobs per claim LIMIT n in the claim's CTE, with a lease long enough for the whole batch
Priorities A priority column, ORDER BY priority DESC, run_at, id, and the same columns in jobs_ready
Several queues A queue column as the first key column of jobs_ready; it's a key, not the predicate, so it can be a parameter
No duplicate jobs A partial unique index, for example ON jobs ((payload->>'order_id')) WHERE kind = 'send_receipt' AND status IN ('queued', 'running'), plus ON CONFLICT ... DO NOTHING. The conflict target must repeat the index's WHERE, or PostgreSQL finds no matching constraint
Recurring jobs pg_cron enqueues on a schedule, or use a library's periodic tasks
Django or SQLAlchemy Django's select_for_update(skip_locked=True, no_key=True); SQLAlchemy's with_for_update(skip_locked=True, key_share=True) renders FOR NO KEY UPDATE SKIP LOCKED
asyncio psycopg's AsyncConnection has an async notifies(); PgQueuer is async-first and Procrastinate supports async

Troubleshooting#

Symptom Cause Fix
Duplicate emails Reads without a lock, or a rerun after a lease expired Lock the claim (Step 3); idempotent handlers (Step 5)
One worker does little or no work Its locked claim keeps waiting on rows other workers hold and losing the race (Step 3) Add SKIP LOCKED and keep the lock to one short statement (Step 4)
Jobs stuck in running Nothing reaps expired leases Run REAP on a timer, not only when idle (Step 5)
n_dead_tup keeps climbing A long or idle transaction blocks VACUUM Find it with health.sql, end it, set a timeout (Step 8)
Claims slow down as history grows The claim isn't using the partial index Write status = 'queued' as a literal, not a parameter (Step 1)
New jobs wait for the next poll The listener goes through PgBouncer Give the listener a direct connection

When Postgres Is Not Enough#

A whiteboard has a ceiling too. Published benchmarks put the ceiling in the thousands of jobs per second on modest hardware; read them as orders of magnitude, since each has its own setup:

Source Setup Reported
Stanislav Kozlovski's benchmark One SKIP LOCKED claim per transaction, 1 KiB rows, 4 vCPU (c7i.xlarge) 2,885 messages/s, limited by the readers
Same 96 vCPU 20,144 messages/s
Graphile Worker performance Trivial jobs, one i9 desktop, database on the same machine About 15,600 jobs/s without batching
Graphile Worker scaling Advice on moving to another queue "start thinking about it when you're getting to 5k+ jobs per second"

Reach for a broker when you need what one table can't give you: several thousand jobs per second sustained, one message read by many independent consumers (unless you adopt an event log like PgQ), or replaying history. Queues on Redis or RabbitMQ (RQ, Dramatiq, Celery) suit very high throughput or low latency, at the cost of a second system; RabbitMQ also does routing and fan-out. Amazon SQS is managed, with the same lease idea (a visibility timeout) and dead-letter queues. Kafka is for replayable streams.

Libraries that already do this#

You don't have to maintain all of this yourself. Most languages already have a Postgres-backed queue that does everything above and more. In Python, Procrastinate is the closest to this post's design, and PgQueuer is async-first.

For everything else, I keep a curated list instead of squeezing it into a table here: awesome-job-queues. It has more than 140 libraries, job servers and brokers across nine languages, a section on database-backed queues, and reading on PostgreSQL as a queue, retries and the outbox pattern.

If it saves you an afternoon of searching, a star on GitHub helps the next person find it. And if your favorite queue is missing or an entry has gone stale, open an issue or a pull request. Feedback is how a list like this stays useful.

Conclusion#

You started with four bakers reading one ticket and ended with a board where no two bakers claim the same ticket at once, a walk-out doesn't strand a cake, and no ticket goes up for a torn-up order. You also watched one forgotten transaction stop the cleaner cold, the failure that's easiest to miss.

For a team already on PostgreSQL, that's one fewer system to run and pay for, and jobs that commit with their data. The price is ownership: idempotent handlers, a dead-job alert, a transaction timeout and retention. For production Python, I'd try Procrastinate before maintaining my own; it covers this design and more. Hand-rolled is fine for a small internal need, and building it once is how you learn to judge the library. The cron job can retire. It never wanted the hero role anyway.

Next, find the cron job in your codebase that scans for unsent work and run two copies at once, then hunt for transactions that stay open while calling out to the world. If the work has to reach another system reliably, read the transactional outbox tutorial.

Need a job system built? See how I approach distributed systems, or book a free 20-minute intro call.

there are no Dumb Questions

(frequently asked questions, answered without judgement)

Is a SKIP LOCKED queue FIFO?

Roughly, not strictly. Workers take the oldest job nobody else holds, so jobs start in about the order they were queued, but they finish in whatever order the work takes, and a retried job goes to the back. If jobs for the same customer or account must run in order, serialize them per key: one worker per key, an advisory lock per key, or a claim that skips keys with a job already running.

What happens to a job if the worker crashes?

With a lease, the job stays running until its lease expires. Then a reaper puts it back in the queue with its attempt count intact, and another worker runs it again. That means the job can run twice, so the handler must be idempotent: check whether the email or charge already happened before doing it again. A fence on the finish query stops the old worker from marking the new attempt done.

Does a Postgres job queue work with PgBouncer?

The claim, finish and retry queries do, in transaction pooling mode, because each is one short transaction. LISTEN and session-level advisory locks don't, so give each worker's listener a direct connection to PostgreSQL. With psycopg 3.2 or later, prepared statements work when PgBouncer is 1.22 or later with max_prepared_statements above zero and the client's libpq is version 17 or newer; otherwise set prepare_threshold to None.

Will a jobs table bloat my database?

Every claim and every finish leaves a dead row version, two per job in this lab, and autovacuum cleans them up only if no old transaction still needs them. One forgotten open transaction stopped VACUUM from removing 2,000 dead rows. Set idle_in_transaction_session_timeout, watch n_dead_tup and long transactions, delete or partition old jobs, and keep the partial index small.

Can a Postgres queue run each job exactly once?

No. A worker can finish the work and die before it records that, so the job runs again. Brokers don't change this for side effects: SQS FIFO deduplicates messages and Kafka transactions cover writes back into Kafka, but neither can un-send an email. Celery's PGMQ transport docs say a visibility timeout does not guarantee exactly-once. Aim for at-least-once delivery and idempotent effects, such as a unique key per receipt.

Found this useful? Share it

Distributed SystemsJob QueuesPostgreSQLPython

Did that make sense? If not, tell me. Seriously.

Written by an actual human. Any typos are artisanal.

Written by Shahid Yousuf

Senior Software Engineer for backend, distributed and data-intensive systems, AWS infrastructure and AI applications, from the first conversation to production. Work with me, or connect on X and LinkedIn to get the next in-depth tutorial.

Shahid Yousuf

Senior Software Engineer

I build whole products, specialising in backend, distributed and data-intensive systems, AWS and AI. Have something in mind? Let's talk.

Hire me Book a free intro call see the case studies

Get new posts

I share every new in-depth tutorial on X and LinkedIn. Connect with me there to get the next one.

feed reader person? RSS or Atom, very retro, very respected.

(the kettle's still warm)

A tested Python tutorial: see what each PostgreSQL isolation level lets through, overspend a budget three ways, then stop it with SERIALIZABLE retries, a row lock or one UPDATE.

PostgreSQL 24 min read

Have a project in mind?

Send me the goals, the deadline and whatever is on fire. I'll reply with an approach, a rough scope and next steps.

Hire me

Liked the post? The engineer is available too. Same writing style, more code.