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:

View this diagram in the original post

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

Related posts