Learning center

Wake a PostgreSQL job queue's workers with LISTEN/NOTIFY instead of a faster poll

A worker that polls every second makes each new job wait half a second on average before anyone claims it, and up to a full second. A trigger that calls pg_notify when a job becomes due, and a worker that listens on its own connection, cut that wait to a few milliseconds. Keep the poll as a fallback: notifications arrive only after commit, fold together, and are lost while a listener is disconnected.

Where the wait comes from#

A Postgres-backed queue usually claims work with a statement like this one, run in a loop:

UPDATE jobs SET status = 'RUNNING', claimed_at = clock_timestamp()
WHERE id = (SELECT id FROM jobs WHERE status = 'PENDING'
            ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1)
RETURNING id;

When the claim finds nothing, the worker sleeps for its poll interval. A job enqueued just after a worker went to sleep waits for the rest of that interval, so with a one-second poll the wait is spread evenly between 0 and 1,000 ms. For a background job nobody notices. For a request that enqueues a job and waits for its result, that is half a second added to the median response for no work at all.

Shortening the poll trades that wait for load. Six workers on a 100 ms poll run about 60 claim statements a second, all day, whether or not anything is due.

Notify on the write that makes a job due#

PostgreSQL can tell the workers instead. A trigger sends a notification on a channel, and every session that has run LISTEN on that channel receives it:

CREATE FUNCTION jobs_notify() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
  PERFORM pg_notify('jobs_due', '');
  RETURN NULL;
END $$;
CREATE TRIGGER jobs_notify AFTER INSERT ON jobs
  FOR EACH ROW EXECUTE FUNCTION jobs_notify();

Three rules from the NOTIFY reference shape the design:

  • Delivery happens at commit. A notification sent inside a transaction is not delivered "until and unless the transaction is committed". A worker can never wake for a job it cannot yet see, and a rolled-back insert wakes nobody.
  • Identical notifications fold. The same channel and payload signaled several times in one transaction arrive once. With an empty payload, a batch of 500 inserts is one wake-up, and the worker claims in a loop until the queue is empty.
  • Listeners hear only while connected. Nothing is stored for a session that was not listening. Notifications carry no durability, so the jobs table stays the source of truth and the poll stays as a fallback.

Fire the trigger on every write that makes a job claimable, not only on insert: a retry that sets available_at = now(), or a status change back to pending. Leave it out of claims, lease renewals and completions, which make nothing due.

The lab#

The lab needs Docker. It shows the delivery rules in psql, then measures the claim wait with a small Node.js worker.

docker network create pl-b-notify-net
docker run -d --rm --name pl-b-notify --network pl-b-notify-net -e POSTGRES_PASSWORD=x postgres:18
docker exec -it pl-b-notify psql -U postgres
CREATE TABLE jobs (
  id bigserial PRIMARY KEY,
  status text NOT NULL DEFAULT 'PENDING',
  enqueued_at timestamptz NOT NULL DEFAULT clock_timestamp(),
  claimed_at timestamptz
);

Then create the trigger above. In a second session, run LISTEN jobs_due;. In the first, insert three jobs in one transaction and commit two seconds later; then insert one more and roll back. psql prints notifications after the next command it runs, and the listening session printed exactly one, after the commit:

Asynchronous notification "jobs_due" received from server process with PID 109.

Nothing arrived before the commit and nothing for the rolled-back insert.

At a steady polling interval, a ready job can wait nearly the whole interval before the next claim attempt. If arrivals are spread uniformly through that interval and workers are idle, the median wait is about half the interval. Use that as a baseline for your own measurement. Record the time from the enqueue commit to the claim for both poll-only and notified workers. Keep the same fallback interval in both runs so any difference comes from the earlier wake-up.

A worker can use a separate listener connection to end its idle wait.

const listener = new Client(url);
await listener.connect();
listener.on('notification', () => wake());
await listener.query('LISTEN jobs_due');

Here wake() tells the worker to try another claim. The claim still runs on the worker's regular database connection.

Run the listener in production#

Give it its own connection. The LISTEN reference ties a registration to its session: it ends when the session does. The session also receives notifications only between transactions. Do not take it from the application pool, and do not route it through a transaction pooler: the PgBouncer feature table lists LISTEN as never supported in transaction pooling, because the next transaction may run on a different server connection. NOTIFY itself works through the pooler, so writers need no change.

Wake once on every (re)connect. Jobs can become due while the listener is down. When it starts or reconnects, have the worker claim once before it waits.

Keep the poll for what has no write. A job scheduled for later becomes due when the clock passes available_at, and no write happens at that moment. The fallback poll covers it, and covers any notification a listener missed. One second is still fine; it is no longer on the common path.

Expect every worker to wake. Every listener hears every notification, so all idle workers race for one job. FOR UPDATE SKIP LOCKED makes the losers find nothing and go back to waiting. With many workers, keep that race cheap, or wake only some of them.

Keep transactions short in the listener. The notification queue is shared and is cleaned up only once every listener has read it. The NOTIFY reference warns that a listening session that stays inside a long transaction blocks that cleanup, and that NOTIFY fails at commit once the queue is full.

Because the notification and the job commit together, this is not a dual write. The same property is what an outbox replaces a dual write with when the signal must leave the database.

Where this came from#

Proofline found this in its own workflow queue and shipped notified wake-ups in its production release of 18 November 2026. On the one-second poll, claims of one kind of run waited 409 ms at the median and 865 ms at p90 against 1,814 ms of actual work, and that wait was the reason a route that enqueues the run and waits for it missed its 2.0-second median target. A 100 ms poll on six workers would have run about 60 claim statements a second; the change kept the one-second poll as the fallback for timed runs and missed notifications. Proofline reviews GitHub pull requests; new organizations get one calendar month of hosted code review without a cloud connection. Start a free GitHub review ยท Eligibility and fair-use terms

Questions#

Is pg_notify delivered if the transaction rolls back?

No. Notifications sent inside a transaction are delivered only when it commits. A rolled-back insert wakes no worker, which is the behavior a job queue wants.

Can LISTEN work through PgBouncer?

Only in session pooling mode. In transaction pooling, the session that ran LISTEN is not the one that receives the next notification, so run the listener on a direct connection.

Do I still need polling with LISTEN/NOTIFY?

Yes, at a slower interval. Notifications are lost while a listener is disconnected, and a job that becomes due by the passage of time produces no write to notify on.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading