Chapter 8 — The 3 AM Task Board#
A transactional work queue with no broker: PostgreSQL does the locking and the messaging.
savepoint()advisory_xact_lock()retry_transaction()SKIP LOCKEDLISTEN/NOTIFYexamples/146_transactions_locks_queue.pyWeek 2, Sunday 03:00. Three sleepy housekeepers stare at the same clipboard.
Maya: If Oskar and Sofia both ask for the next unclaimed task at the same second, they both grab Room 101!
Panda: Just spin up a message broker cluster! And a separate cache for distributed locks! And a cron job to keep them in sync with PostgreSQL!
Ferris: Or use the database you already have. PostgreSQL has savepoints, advisory locks, SKIP LOCKED, and LISTEN/NOTIFY built right in.
The mission#
Concurrency is where toy apps break. Before sunrise, Maya has to make two workflows rock-solid under parallel traffic:
- Safe loyalty adjustments: serialize per-guest updates with a transaction-scoped advisory lock, recover cleanly from a failed nested step with a
SAVEPOINT, and retrySERIALIZABLEconflicts automatically. - A brokerless work queue: enqueue tasks and wake idle housekeepers via
LISTEN/NOTIFY(only if the transaction commits!), then let multiple workers claim distinct jobs concurrently withFOR UPDATE SKIP LOCKED.
The Panda's plan
Poll SELECT * FROM task WHERE claimed_by IS NULL LIMIT 1 every 200 ms from every worker, then run UPDATE task SET claimed_by = .... Without FOR UPDATE SKIP LOCKED, two workers select the exact same row and do the same chore twice — or block in a queue behind a slow worker holding a row lock.
1. Advisory locks, savepoints and serializable retries#
Sometimes a business operation touches several statements, one optional sub-step might fail, and you still want the rest of the transaction to commit cleanly:
async def savepoints_and_advisory_lock(pool: pg.Pool, guest: Guest) -> None:
# Serialize loyalty adjustments per guest with a transaction-scoped advisory lock,
# and recover from a nested error using a PostgreSQL SAVEPOINT.
async with pool.transaction() as tx:
await tx.advisory_xact_lock(f"guest:{guest.guest_id}:loyalty")
await tx.execute(
pg.update(Guest)
.set(peanut_points=Guest.peanut_points + 200)
.where(Guest.guest_id == guest.guest_id)
)
try:
async with tx.savepoint():
await tx.execute(
pg.update(Guest)
.set(peanut_points=Guest.peanut_points + 9_999)
.where(Guest.guest_id == guest.guest_id)
)
raise ValueError("bonus voucher expired")
except ValueError:
pass
refreshed = await pool.one(pg.select(Guest).where(Guest.guest_id == guest.guest_id))
print(f"after savepoint rollback: {refreshed.first_name} has {refreshed.peanut_points} pts")
# => after savepoint rollback: Jumbo has 200 pts
# retry_transaction transparently retries serialization failures (40001) and deadlocks (40P01).
async def award_bonus(tx: pg.Transaction) -> int:
updated = await tx.one(
pg.update(Guest)
.set(peanut_points=Guest.peanut_points + 50)
.where(Guest.guest_id == guest.guest_id)
.returning(Guest.peanut_points)
)
return updated[0]
total_pts = await pool.retry_transaction(
award_bonus, isolation=pg.enums.IsolationLevel.SERIALIZABLE
)
print(f"after serializable retry_transaction: {total_pts} pts")
# => after serializable retry_transaction: 250 pts
What just happened
tx.advisory_xact_lock("guest:1:loyalty")hashes the string key into a PostgreSQL advisory lock that releases automatically when the transaction commits or rolls back — no leaked locks on crash.- Inside
async with tx.savepoint():, the bogus+9,999bonus raisesValueError. PostgreSQL rolls back only to the savepoint, leaving Jumbo's earlier+200points intact. pool.retry_transaction(award_bonus, isolation=pg.enums.IsolationLevel.SERIALIZABLE)runs the callback underSERIALIZABLEisolation and transparently retries PostgreSQL serialization failures (40001) and deadlocks (40P01) with backoff.
2. A transactional work queue with SKIP LOCKED and LISTEN/NOTIFY#
First, a tiny reusable claim helper that grabs the oldest unclaimed task without ever waiting on another worker's lock:
async def claim_next_task(tx: pg.Transaction, keeper: str) -> Task | None:
# FOR UPDATE SKIP LOCKED lets multiple housekeepers grab distinct tasks with zero blocking.
nxt = await tx.one_or_none(
pg.select(Task)
.where(Task.claimed_by.is_null() & Task.done.is_false())
.order_by(Task.task_id.asc())
.limit(1)
.for_update(skip_locked=True)
)
if nxt is None:
return None
return await tx.one(
pg.update(Task).set(claimed_by=keeper).where(Task.task_id == nxt.task_id).returning(Task)
)
Now pair it with pool.listen(channel) and transactional tx.notify(...):
async def housekeeping_queue_and_notify(pool: pg.Pool, rooms: list[Room]) -> None:
channel = f"dorm_tasks_{uuid.uuid4().hex[:8]}"
async with pool.listen(channel) as listener:
# Enqueue two cleaning tasks and notify listeners atomically on COMMIT.
async with pool.transaction() as tx:
t1 = await tx.one(
pg.insert(CleaningTask)
.values(
CleaningTask(
room_id=rooms[0].room_id,
summary="Sweep peanut shells in 101",
peanut_refill_kg=3,
)
)
.returning(CleaningTask)
)
t2 = await tx.one(
pg.insert(CleaningTask)
.values(
CleaningTask(
room_id=rooms[3].room_id,
summary="Refill mud tub in 104",
extra_towels=6,
)
)
.returning(CleaningTask)
)
await tx.notify(channel, f"queued:{t1.task_id},{t2.task_id}")
# Rolled-back transactions never deliver their NOTIFY payload.
try:
async with pool.transaction() as aborted:
await aborted.notify(channel, "ghost:never-sent")
raise RuntimeError("cancelled")
except RuntimeError:
pass
note = await listener.recv(timeout=2.0)
assert note is not None
print(f"listener received committed alert: {note.payload}")
# => listener received committed alert: queued:1,2
# Two keepers hold open transactions simultaneously: keeper B skips keeper A's locked row.
async with pool.transaction() as tx_a, pool.transaction() as tx_b:
claimed_a = await claim_next_task(tx_a, "maya")
claimed_b = await claim_next_task(tx_b, "oskar")
claimed_c = await claim_next_task(tx_b, "sofia")
assert claimed_a is not None and claimed_b is not None
print(f"maya claimed: {claimed_a.summary}")
# => maya claimed: Sweep peanut shells in 101
print(f"oskar skipped locked row and claimed: {claimed_b.summary}")
# => oskar skipped locked row and claimed: Refill mud tub in 104
print(f"sofia saw remaining unclaimed task: {claimed_c}")
# => sofia saw remaining unclaimed task: None
What just happened
tx.notify(channel, payload)is transactional: PostgreSQL only delivers the notification iftxcommits. Notice the second transaction raisesRuntimeError("cancelled"), so"ghost:never-sent"vanishes completely — your workers never wake up for phantom jobs!- When
tx_a(Maya) claims task #1, PostgreSQL locks that row untiltx_acommits. Whiletx_ais still open,tx_b(Oskar) runs the exact same query with.for_update(skip_locked=True)— PostgreSQL skips the locked row and immediately hands Oskar task #2 with zero waiting. - When Sofia asks next, no unlocked rows remain, so
claim_next_taskreturnsNone.
Ferris' basement: why NOTIFY + SKIP LOCKED beats a sidecar broker for small-to-medium queues
With a separate broker, writing a row to PostgreSQL and publishing a message are two different systems — if the process crashes between them, you lose a job or publish a ghost (the dual-write problem). Inside PostgreSQL, the INSERT and the NOTIFY commit atomically in the same WAL record, and FOR UPDATE SKIP LOCKED turns the table itself into a durable, crash-safe queue.
What PostgreSQL actually received#
🔭 What PostgreSQL received: 33 statements in 25 round trips (captured live on PostgreSQL)
-- ⚙ schema setup (create_all): 54 statements omitted · full transcript in examples/__wire__/transactions_locks_queue.sql
-- ── round trip 1 · 2 statements pipelined ──
BEGIN;
INSERT INTO "dormitory" ("region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING "dormitory_id", "region_id", "code", "name", "city", "country", "timezone", "check_in", "check_out", "city_tax", "opened_on";
-- → 1 row
-- ── round trip 2 ──
INSERT INTO "room" ("dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service")
VALUES
($1, $2, $3, $4, $5, $6, $7, $8),
($9, $10, $11, $12, $13, $14, $15, $16),
($17, $18, $19, $20, $21, $22, $23, $24),
($25, $26, $27, $28, $29, $30, $31, $32),
($33, $34, $35, $36, $37, $38, $39, $40),
($41, $42, $43, $44, $45, $46, $47, $48),
($49, $50, $51, $52, $53, $54, $55, $56),
($57, $58, $59, $60, $61, $62, $63, $64),
($65, $66, $67, $68, $69, $70, $71, $72),
($73, $74, $75, $76, $77, $78, $79, $80),
($81, $82, $83, $84, $85, $86, $87, $88),
($89, $90, $91, $92, $93, $94, $95, $96)
RETURNING "room_id", "dormitory_id", "number", "floor", "category", "max_weight_kg", "max_guests", "amenities", "out_of_service";
-- → 12 rows
-- ── round trip 3 ──
INSERT INTO "guest" ("email", "first_name", "last_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in")
SELECT u.c0, u.c1, u.c2, u.c3, u.c4, u.c5, u.c6, u.c7, u.c8, u.c9, u.c10
FROM unnest($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) WITH ORDINALITY AS u(c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, ord)
ORDER BY u.ord
RETURNING "guest_id", "public_id", "email", "first_name", "last_name", "full_name", "species", "phone", "country", "birth_date", "loyalty_tier", "peanut_points", "preferences", "marketing_opt_in", "created_at";
-- → 3 rows
-- ── round trip 4 ──
COMMIT;
-- ── round trip 5 · 2 statements pipelined ──
BEGIN;
SELECT pg_advisory_xact_lock(hashtext($1));
-- → 1 row
-- ── round trip 6 ──
UPDATE "guest"
SET "peanut_points" = "peanut_points" + $1
WHERE "guest_id" = $2;
-- → 1 affected
-- ── round trip 7 ──
SAVEPOINT sp_1;
-- ── round trip 8 ──
UPDATE "guest"
SET "peanut_points" = "peanut_points" + $1
WHERE "guest_id" = $2;
-- → 1 affected
-- ── round trip 9 · 2 statements pipelined ──
ROLLBACK TO SAVEPOINT sp_1;
RELEASE SAVEPOINT sp_1;
-- ── round trip 10 ──
COMMIT;
-- ── round trip 11 ──
SELECT
"guest_id",
"public_id",
"email",
"first_name",
"last_name",
"full_name",
"species",
"phone",
"country",
"birth_date",
"loyalty_tier",
"peanut_points",
"preferences",
"marketing_opt_in",
"created_at"
FROM "guest"
WHERE "guest_id" = $1;
-- → 1 row
-- ── round trip 12 · 2 statements pipelined ──
BEGIN ISOLATION LEVEL SERIALIZABLE;
UPDATE "guest"
SET "peanut_points" = "peanut_points" + $1
WHERE "guest_id" = $2
RETURNING "peanut_points";
-- → 1 row
-- ── round trip 13 ──
COMMIT;
-- ── round trip 14 · 2 statements pipelined ──
BEGIN;
WITH "_pgdorm_cti_0" AS (
INSERT INTO "task" ("task_kind_id", "room_id", "summary", "claimed_by", "done")
VALUES ($1, $2, $3, $4, $5)
RETURNING "task_id", "task_kind_id", "room_id", "summary", "claimed_by", "done"
), "_pgdorm_cti_1" AS (
INSERT INTO "cleaning_task" ("task_id", "task_kind_id", "extra_towels", "peanut_refill_kg")
SELECT "task_id", "task_kind_id", $6, $7
FROM "_pgdorm_cti_0"
RETURNING "task_id", "task_kind_id", "extra_towels", "peanut_refill_kg"
)
SELECT
"_pgdorm_cti_1"."task_id",
"_pgdorm_cti_1"."task_kind_id",
"_pgdorm_cti_0"."room_id",
"_pgdorm_cti_0"."summary",
"_pgdorm_cti_0"."claimed_by",
"_pgdorm_cti_0"."done",
"_pgdorm_cti_1"."extra_towels",
"_pgdorm_cti_1"."peanut_refill_kg"
FROM "_pgdorm_cti_0"
INNER JOIN "_pgdorm_cti_1" USING ("task_id");
-- → 1 row
-- ── round trip 15 ──
WITH "_pgdorm_cti_0" AS (
INSERT INTO "task" ("task_kind_id", "room_id", "summary", "claimed_by", "done")
VALUES ($1, $2, $3, $4, $5)
RETURNING "task_id", "task_kind_id", "room_id", "summary", "claimed_by", "done"
), "_pgdorm_cti_1" AS (
INSERT INTO "cleaning_task" ("task_id", "task_kind_id", "extra_towels", "peanut_refill_kg")
SELECT "task_id", "task_kind_id", $6, $7
FROM "_pgdorm_cti_0"
RETURNING "task_id", "task_kind_id", "extra_towels", "peanut_refill_kg"
)
SELECT
"_pgdorm_cti_1"."task_id",
"_pgdorm_cti_1"."task_kind_id",
"_pgdorm_cti_0"."room_id",
"_pgdorm_cti_0"."summary",
"_pgdorm_cti_0"."claimed_by",
"_pgdorm_cti_0"."done",
"_pgdorm_cti_1"."extra_towels",
"_pgdorm_cti_1"."peanut_refill_kg"
FROM "_pgdorm_cti_0"
INNER JOIN "_pgdorm_cti_1" USING ("task_id");
-- → 1 row
-- ── round trip 16 ──
SELECT pg_notify($1, $2);
-- → 1 row
-- ── round trip 17 ──
COMMIT;
-- ── round trip 18 · 2 statements pipelined ──
BEGIN;
SELECT pg_notify($1, $2);
-- → 1 row
-- ── round trip 19 · 2 statements pipelined ──
BEGIN;
SELECT
"task_id",
"task_kind_id",
"room_id",
"summary",
"claimed_by",
"done"
FROM "task"
WHERE "claimed_by" IS NULL AND "done" IS FALSE
ORDER BY "task_id" ASC
LIMIT $1
FOR UPDATE SKIP LOCKED;
-- → 1 row
-- ── round trip 20 ──
UPDATE "task"
SET "claimed_by" = $1
WHERE "task_id" = $2
RETURNING "task_id", "task_kind_id", "room_id", "summary", "claimed_by", "done";
-- → 1 row
-- ── round trip 21 · 2 statements pipelined ──
BEGIN;
SELECT
"task_id",
"task_kind_id",
"room_id",
"summary",
"claimed_by",
"done"
FROM "task"
WHERE "claimed_by" IS NULL AND "done" IS FALSE
ORDER BY "task_id" ASC
LIMIT $1
FOR UPDATE SKIP LOCKED;
-- → 1 row
-- ── round trip 22 ──
UPDATE "task"
SET "claimed_by" = $1
WHERE "task_id" = $2
RETURNING "task_id", "task_kind_id", "room_id", "summary", "claimed_by", "done";
-- → 1 row
-- ── round trip 23 ──
SELECT
"task_id",
"task_kind_id",
"room_id",
"summary",
"claimed_by",
"done"
FROM "task"
WHERE "claimed_by" IS NULL AND "done" IS FALSE
ORDER BY "task_id" ASC
LIMIT $1
FOR UPDATE SKIP LOCKED;
-- ── round trip 24 ──
COMMIT;
-- ── round trip 25 ──
COMMIT;
Shift report
- Serialized per-entity work with transaction-scoped
advisory_xact_lock() - Rolled back a failed sub-step cleanly with
tx.savepoint() - Handled
SERIALIZABLEcontention automatically withretry_transaction() - Woke workers atomically on commit with
pool.listen()andtx.notify() - Claimed distinct jobs concurrently with
.for_update(skip_locked=True)
Try it yourself
Remove skip_locked=True from claim_next_task (leaving .for_update()) and think through what happens when tx_a and tx_b run inside the same coroutine: why would tx_b deadlock waiting for tx_a?
Go deeper: tests/integration/runtime/listen/test_listen.py (live PostgreSQL test suites & snapshots)
Note
Also in pgdorm: Collapse SELECT ... FOR UPDATE SKIP LOCKED + UPDATE into a single statement using WriteCte (pg.write_cte) and Update.from_ — see Field Note 6 · Search, JSON & Advanced DML.
Sticky note from Management
"Month 2! We have THOUSANDS of guests now, the directory page takes four seconds on page 200, and I'm trying to check the dashboard from the harbour café on 15 ms Wi-Fi. SPEED IT UP."
← PreviousChapter 7 · Payments & ChoresChapter 7 · STI & CTI Polymorphism
Next →Act III · The Wi-Fi EraAct III · Keyset, Pipelines & Stats