How Postgres wakes a worker with LISTEN and NOTIFY
Too long, didn’t read
Two boxes are ready for pickup. The app saves both jobs and runs NOTIFY once. Both workers get that message when the app commits. You can try it in three Postgres sessions, then see why a worker should commit LISTEN before its first read when it reconnects.
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.
SQL files
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.
Try it with the transaction open
Back in App, run these first four lines of publish.sql. You’ll insert both rows and call NOTIFY once. The call passes a channel name and leaves the message body, called the payload, empty. The box numbers are in the table.
BEGIN;
INSERT INTO pickup_jobs (id)
VALUES (101), (102);
NOTIFY pickup_ready; Leave App’s transaction open. Run pending.sql in each drone terminal. Both still see zero rows, and neither gets a notification. App’s changes are still inside its transaction.
Now run COMMIT; in App and repeat pending.sql in both drone terminals. Look for two rows in the query output and an asynchronous notification for pickup_ready. The query tells you what work is pending. The other line tells you the connection received a message.
| App’s transaction | What each drone can observe |
|---|---|
Open after NOTIFY | Zero rows and no notification |
| Committed | Jobs 101 and 102, plus one pickup_ready notification |
In the recorded run on PostgreSQL 18.7, Drone A saw rows 101 and 102 after the commit. Both connections received one message with an empty payload.
What if App changes its mind? Try it with box 104 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.
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
Both workers saw box 101 on the list. If they both dispatch a drone for the first row they read, we have two drones heading for the same box. A worker needs to claim the job before it sends a drone. The first post builds that job claim
What happens inside Postgres
When App runs NOTIFY, the Postgres process handling that connection puts the notification on a private list for the current transaction. App can still roll back, in which case the process discards the entry. During commit, it adds the notification to a queue shared by the Postgres processes. Once the transaction has committed, it signals the listener processes so they can check that queue.
The process handling Drone A keeps its own read position in that queue. The process handling Drone B has its own position, too. Both can read the same entry. Each checks whether the entry is for its database and a channel it listens to, then passes the matching message to its client. That’s how one queue entry reached both terminals. The pickup jobs are in the table we created earlier. PostgreSQL 18.7 notification implementation
What if a drone was offline?
Now send Drone B home for the night. A box arrives just as Drone A loses its connection. The operator still scans the box, and App commits job 103. The worker has to subscribe again because Postgres removes a subscription when its session ends. In a separate run with an empty table at the start, the new connection received no notification for that commit. Its first query still found job 103. PostgreSQL documentation on session subscriptions
The first read can pick up work that arrived during the outage. What happens if a new box arrives during startup itself, between the first read and the subscription? You can make that happen on purpose by choosing when to run App’s transaction.
Close both drone sessions with \q and keep App open. Before each of the next two runs, clear the scratch table with TRUNCATE pickup_jobs; in App and open a fresh Drone A session with psql -X listen_notify_lab. The new connection starts without a subscription. In both runs, App uses this file to save box 103.
BEGIN;
INSERT INTO pickup_jobs (id) VALUES (103);
NOTIFY pickup_ready;
COMMIT; Read first
Run pending.sql in Drone A. It sees an empty table. Run publish-job-103.sql in App, then run subscribe.sql in Drone A.
Run SELECT 1; in Drone A to give psql a chance to show a notification. The query returns 1 and there’s no notification for 103. Check with pending.sql in App and you’ll find the box. Drone A checked too early and subscribed too late. Left waiting for another notification, it could miss this job until the next box comes in.
Subscribe first
Close Drone A, clear the scratch table in App, and open a fresh Drone A session again. This time run subscribe.sql in Drone A first and let its COMMIT finish. Run the same publish-job-103.sql in App, then run pending.sql in Drone A. It receives pickup_ready and finds box 103 on its first read.
This time the worker has two reasons to look at box 103. Its first read finds the row, and a notification also tells it to check the table. That’s fine when each check uses the same job claim. The order PostgreSQL recommends is to commit LISTEN, then inspect the database in a new transaction. PostgreSQL documentation on LISTEN startup order
Put that order in the worker
On startup and after a disconnect, the worker connects, commits LISTEN, and checks for pending work. In reconnect.sql, the COMMIT ends the subscription transaction. The query after it runs in a new transaction when you’re in psql with its default autocommit setting.
BEGIN;
LISTEN pickup_ready;
COMMIT;
SELECT id
FROM pickup_jobs
WHERE status = 'pending'
ORDER BY id; In the worker, that check is a loop. Try to claim a job, do the work, and try again until the claim returns no row. Then wait for the next notification and run the same loop. Think back to boxes 101 and 102. App sent one message when it saved both. A worker that takes one job and goes straight back to sleep can leave the second box on the bench.