How Postgres wakes a worker with LISTEN and NOTIFY
Too long, didn’t read
Two workers are already listening when the warehouse app inserts two pickup jobs and runs NOTIFY once. While the transaction is open, the jobs table still looks empty to both workers. After the app commits, each gets one notification and can find both jobs. Try it in three Postgres sessions, then see how a worker can miss a signal during startup.
Two boxes, two drones
It’s the end of a quiet shift. An operator scans two boxes at the dispatch bench, 101 and 102. Both drones are still on their docks. Each has a worker, a small program with its own database connection. The app puts one row in Postgres per box. How do the workers know when to check for those rows?
The workers could run a query every few seconds, even when the bench is empty. With LISTEN, a worker can subscribe to a named channel on its connection. The app can then use NOTIFY to send a short message to that channel. The part worth trying is what happens when you leave the app’s transaction open, right after it runs NOTIFY.
Put the boxes in a table
Open the SQL files to follow the code as you read.
If you have a running PostgreSQL server and permission to create a database, run createdb listen_notify_lab in your shell. We’ll use this scratch database throughout. Open three terminals and run psql -X listen_notify_lab in each. That’s PostgreSQL’s command-line client, with -X to skip your startup settings.
Call the first terminal App, the second Drone A, and the third Drone B. App writes the jobs. The drone terminals stand in for the two workers, each with its own connection. You can follow the query results below if you’re reading without a database.
Run schema.sql once in App. We’ll use the number on a box as the job identifier. Every box that arrives starts as a pending job.
CREATE TABLE pickup_jobs (
id integer PRIMARY KEY,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending', 'done'))
); Switch to Drone A and run pending.sql. It asks for the number of every box waiting for pickup. It should return zero rows. Keep the query handy because you’ll run it again after App adds the boxes.
SELECT id
FROM pickup_jobs
WHERE status = 'pending'
ORDER BY id; Tell both drones where to listen
Run subscribe.sql in Drone A and Drone B. Both connections subscribe to the channel pickup_ready. BEGIN starts a transaction, and COMMIT finishes it. The subscription takes effect at COMMIT, so run all three lines in both terminals.
BEGIN;
LISTEN pickup_ready;
COMMIT; Leave both connections open with no transaction in progress. Later, when you run a query in psql, it can print any waiting notifications alongside the query result. The recorded run used Psycopg, a Python client that can wait for a notification directly.
What changes when the app commits?
Both drone sessions have already committed LISTEN pickup_ready and are idle. In App, run the first four lines of publish.sql and leave the transaction open.
BEGIN;
INSERT INTO pickup_jobs (id)
VALUES (101), (102);
NOTIFY pickup_ready; Before COMMIT. Run pending.sql in both drone terminals. Both queries return zero rows. Neither connection gets a notification.
After COMMIT. Run COMMIT; in App and repeat pending.sql in both drone terminals. The query returns jobs 101 and 102. Each connection also receives one pickup_ready notification. Its payload, the message body, is empty.
In the PostgreSQL 18.7 lab run, the script queried the table from Drone A and checked both connections for notifications.
If the listener is still in a transaction when a notification arrives, Postgres waits for that transaction to end before delivering it to the client. That’s why we leave the drone terminals at their normal prompts between checks. PostgreSQL documentation on NOTIFY delivery
Job 101 is first on both workers’ lists. If both workers act on the first row they see, both drones head for the same box. Each worker can send its drone once its claim commits. The first post builds that job claim
What if App rolls back?
Try it with box 104. Run these lines in App and finish with ROLLBACK to cancel the transaction.
BEGIN;
INSERT INTO pickup_jobs (id) VALUES (104);
NOTIFY pickup_ready;
ROLLBACK; Run pending.sql in both drone terminals again. Boxes 101 and 102 are still waiting. Box 104 never appears, and there is no new pickup_ready message.
What happens inside Postgres
In the lab, App ran NOTIFY pickup_ready once. Each drone connection got one message with an empty payload after App committed. Both deliveries start with the same entry in Postgres’s shared notification queue.
When App runs NOTIFY, the Postgres process handling its connection keeps the notification on a private list for that transaction. If App rolls back, as it did for box 104, the process discards the pending notification.
While App is committing, the same process adds one pickup_ready entry to the shared queue. Once the transaction has committed, the process signals listening Postgres processes to check the queue. PostgreSQL 18.7 source for staging, commit, and signaling
The Postgres processes for Drone A and Drone B each read from their own position in the queue. Each checks that the entry is for its database and a channel it listens to. With both sessions subscribed to pickup_ready in App’s database, each process forwards the notification to its client between transactions. PostgreSQL 18.7 source for queue reads and delivery
When pickup_ready arrives, each worker can query pickup_jobs to find the boxes still waiting at the bench.
What if a drone was offline?
The operator scans box 103 while Drone A’s worker is offline. App inserts the job, runs NOTIFY pickup_ready, and commits before the worker reconnects. Postgres clears the old session’s subscription when it closes, so the worker has to subscribe again. PostgreSQL documentation on session subscriptions
In the lab, Drone A committed LISTEN pickup_ready on a fresh connection. Its first query found job 103. The notification check that followed returned no messages.
Box 103 was already waiting when Drone A reconnected. If App saves it during startup, the worker can check the table before the job arrives.
In both trials, App commits between Drone A’s first query and its LISTEN commit. Swap those two Drone A steps in the second trial.
Leave autocommit on in App and Drone A. Before each trial, reset the scratch database in this order.
- Close any old drone sessions with
\q. - With App still connected to
listen_notify_lab, runTRUNCATE pickup_jobs;. - Open a fresh Drone A session with
psql -X listen_notify_lab.
Use pending.sql to check for pending jobs in either run.
SELECT id
FROM pickup_jobs
WHERE status = 'pending'
ORDER BY id; Use publish-job-103.sql for App’s transaction in both trials.
BEGIN;
INSERT INTO pickup_jobs (id) VALUES (103);
NOTIFY pickup_ready;
COMMIT; Read first
- Drone A reads. Run
pending.sql. Expect zero rows. - App commits box 103. Run
publish-job-103.sql. - Drone A subscribes. Run
BEGIN; LISTEN pickup_ready; COMMIT;. Then runSELECT 1;sopsqlcan display any waiting notifications. Expect1and nopickup_readyfrom App’s commit.
Run pending.sql in App to check for job 103.
In the lab, Drone A’s first query found zero jobs and its notification check after subscribing returned no messages. App’s query found job 103 still pending.
If Drone A waits for a notification before it checks the table again, box 103 can sit on the bench until another signal arrives.
Subscribe first
Repeat the reset above to start with an empty table and a fresh Drone A session.
- Drone A subscribes. Run
BEGIN; LISTEN pickup_ready; COMMIT;. LetCOMMITfinish before you switch terminals. - App commits box 103. Run the same
publish-job-103.sql. - Drone A reads. Run
pending.sql. Look for row 103 and apickup_readynotification inpsql.
In the recorded run, the script waited for pickup_ready before it ran its first query. That query found job 103.
Postgres recommends committing LISTEN and then checking the table in a new transaction. A notification from the same commit can prompt another check for a job the first query already found. PostgreSQL documentation on LISTEN startup order
Put that order in the worker
When the worker starts or reconnects, it commits LISTEN pickup_ready on the new connection. It checks for pending jobs right away in a new transaction. With psql’s default autocommit setting, the SELECT in reconnect.sql runs in that new transaction.
BEGIN;
LISTEN pickup_ready;
COMMIT;
SELECT id
FROM pickup_jobs
WHERE status = 'pending'
ORDER BY id; The query lists pending jobs. To reserve one, follow the claim pattern from the first post. How to claim a job in Postgres
On that first check and on every pickup_ready notification, the worker runs each claim in its own transaction and sends the drone once the claim commits. When the pickup is done, it tries another claim. If a claim returns zero rows, it ends the transaction before waiting again.
A SKIP LOCKED claim can return zero rows while other workers hold locks on the pending jobs. Add a fallback check if those jobs can become claimable without a new NOTIFY.
Suppose only Drone A is available when App saves boxes 101 and 102 and runs NOTIFY once. If the worker goes back to waiting after picking up 101, box 102 can sit on the bench until the next signal. A second claim can find it on the same wake-up.