Postgres LISTEN/NOTIFY in Node.js: the notifications you miss, and how to catch up

LISTEN/NOTIFY has no backlog: a notification sent while your listener isn't listening is gone. We restarted Postgres, took it down for 20 seconds and redeployed the listener while 20 events a second were being written. A quick restart lost nothing. The outage lost up to 46 events and the redeploy lost 99. A catch-up query brought both to zero, with nothing handled twice. Here is where the gaps come from and the recipe that closes them.

Postgres can tell your Node.js service the moment something changes. A row is written, the same transaction calls pg_notify, and every connection that ran LISTEN on that channel hears about it. There's no broker to run and no polling to tune, and it is fast.

There's one catch, and the Postgres documentation is honest about it: a notification goes only to the connections listening at that moment. Nothing is stored. If your listener is reconnecting, restarting, or being redeployed, the notifications sent in the meantime never reach it, and nothing tells you they existed.

This post measures how big that gap is in practice, and shows the recipe that closes it: keep the events in a table, and run a catch-up query whenever the listener comes back.

Everything below was measured with @imqueue/pg-pubsub 3.0.11 and pg 8.23.1 on Node.js 26, against PostgreSQL 17.11. A writer inserted one event row every 50 ms, 20 a second, and sent its notification in the same statement. One process listened on the channel and recorded every event it handled in the database. Each scenario ran three times.

The short version

  • A notification is delivered only to connections listening when it is committed. Postgres keeps no backlog for a listener that is away.
  • A quick database restart lost nothing. While the database is down, nobody can commit, so there are no notifications to miss. In three restarts, 0 events were lost.
  • A longer outage did lose events. The listener retries with a growing pause, up to 10 seconds by default, so it came back about 2.4 seconds after the database. The writer was already committing again: 28–46 events were lost per run.
  • A redeploy of the listener lost the most. While the listener was down for 5 seconds, the writer kept going: 98–99 events lost, every one of them silently.
  • A catch-up query fixed all of it. Listen first, then read the events this consumer hasn't handled: 0 lost, 0 handled twice, in every run.

Why a notification can disappear

NOTIFY is a broadcast to whoever is connected and listening right now. When a transaction that called pg_notify commits, Postgres hands the message to each listening connection and forgets it. A connection that runs LISTEN a second later gets only what is sent after that second.

So the question isn't "was the database up?" but "was my listener listening while someone was writing?" That gives three very different outcomes.

A database restart: nothing lost

We restarted Postgres in the middle of a run. It was back in about 0.3 seconds, the listener reconnected right after it, and every event that was committed was handled. In three restarts, 0 were lost.

That surprised us less once we looked at the writer: 4–6 of its inserts failed during the restart. A notification belongs to a transaction, and no transaction can commit while the database is down. No commit means no notification to miss.

A longer outage: lost in the gap after it

Then we stopped Postgres for 20 seconds. @imqueue/pg-pubsub reconnects on its own and listens to its channels again, but it waits between attempts: 100 ms first, doubling after each failure, up to retryDelayMax, 10 seconds by default. That protects the database from a crowd of clients retrying ten times a second while it is trying to start.

In our runs the attempts came 0.1, 0.2, 0.4, 0.8, 1.6, 3.2 and 6.4 seconds apart, and then the next one was 10 seconds away. The database came back during that last wait. The writer, which retried every 50 ms, was committing again at once; the listener reconnected about 2.4 seconds later. Everything written in between was lost: 28, 28 and 46 events in three runs.

Lowering retryDelayMax to 1 second shrinks the gap but doesn't close it: 4 events lost in each of three runs, and the listener made 23 attempts instead of 8 while the database was down. No setting can close it completely, because there is always some time between "the database is up" and "the listener is listening".

A redeploy: lost for as long as you're away

The most common gap has nothing to do with the database. We killed the listener process and started a new one 5 seconds later, which is what a deploy or a crash and restart looks like. The database was fine the whole time, and the writer kept committing.

98, 98 and 99 events were lost in three runs: everything written in those 5 seconds. Nothing logged an error, because from Postgres's side nothing went wrong.

The recipe: an events table and a catch-up query

The fix is to stop treating the notification as the event. Make the row the event, and the notification only a fast way of saying "there's something new". When the listener comes back, it asks the table what it missed.

1. Write the event and the notification together

The event goes into a table, and the notification is sent in the same statement, so both commit or neither does:

CREATE TABLE events (
    id         bigserial PRIMARY KEY,
    kind       text        NOT NULL,
    payload    jsonb       NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now()
);

-- one statement: the row and its notification share a transaction
WITH e AS (
    INSERT INTO events (kind, payload)
    VALUES ('order.paid', '{"orderId": "A-1001"}')
    RETURNING id
)
SELECT pg_notify('orders', json_build_object('id', id)::text) FROM e;

If you write the event as part of a larger transaction, call pg_notify inside that transaction. Postgres sends notifications only when the transaction commits, and drops them if it rolls back, so a listener never hears about a row that doesn't exist.

Send it from SQL rather than with pubSub.notify(). notify() runs on the listener's own connection, outside your transaction, so the row could roll back after the notification was already sent.

2. Record what each consumer has handled

A second table remembers which events a consumer has handled. Its primary key is what makes a second delivery harmless:

CREATE TABLE handled (
    consumer   text        NOT NULL,
    event_id   bigint      NOT NULL REFERENCES events (id),
    handled_at timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (consumer, event_id)
);

Handling an event starts by claiming it. If the insert adds no row, someone already handled it, so skip it:

import pg from 'pg';

const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const CONSUMER = 'billing';

async function handle(eventId: number): Promise<void> {
    const client = await db.connect();

    try {
        await client.query('BEGIN');

        const { rowCount } = await client.query(
            `INSERT INTO handled (consumer, event_id) VALUES ($1, $2)
             ON CONFLICT DO NOTHING`,
            [CONSUMER, eventId],
        );

        if (rowCount) {
            await doTheWork(client, eventId); // same transaction as the claim
        }

        await client.query('COMMIT');
    } catch (err) {
        await client.query('ROLLBACK');
        throw err;
    } finally {
        client.release();
    }
}

When the work is a database change, keep it in the same transaction as the claim: either both happen or neither does. When it is something outside the database, such as an email or an HTTP call, do the work first and record the claim after it succeeds. A crash in between then repeats the work instead of skipping it, so make that work safe to repeat.

3. Catch up when the listener starts and every time it reconnects

The catch-up query reads every event this consumer hasn't handled yet:

import { PgPubSub } from '@imqueue/pg-pubsub';

async function catchUp(): Promise<void> {
    const { rows } = await db.query(
        `SELECT e.id FROM events e
          WHERE NOT EXISTS (
                SELECT 1 FROM handled h
                 WHERE h.consumer = $1 AND h.event_id = e.id)
          ORDER BY e.id`,
        [CONSUMER],
    );

    for (const { id } of rows) {
        await handle(Number(id));
    }
}

const pubSub = new PgPubSub({
    connectionString: process.env.DATABASE_URL,
});

pubSub.on('error', err => console.error('pg-pubsub', err.message));
pubSub.on('reconnect', () => void catchUp()); // channels are listened to again first
pubSub.channels.on('orders', ({ id }) => void handle(id));

await pubSub.connect();
await pubSub.listen('orders');
await catchUp();                                  // what happened while we were away

The order matters, and it is the same both times: listen first, then catch up. At start-up the code listens before it queries. On a reconnect, @imqueue/pg-pubsub listens to all its channels again before it emits 'reconnect'. Either way there is no moment when an event can fall between the query and the listening. The two may overlap, so the same event can arrive both ways, and the claim in step 2 turns the second arrival into a no-op.

Always attach the 'error' handler. Every failed reconnect attempt is reported there, and with no handler they go to the logger instead.

What it measured

Scenario Lost, notifications only Lost, with catch-up Recovered by catch-up Handled twice
Database restart 0 0 0 0
Database down 20 s 28–46 0 46–47 0
Listener down 5 s 98–99 0 98–99 0

In one outage run, one event arrived both as a notification and through the catch-up query; the claim skipped it, as it should. A last catch-up at the end of every run found nothing left behind.

Choices worth making on purpose

Run the catch-up on a timer too. Reconnects and start-ups are the gaps you know about. A slow consumer, a handler that threw, or a connection that died quietly are the ones you don't. Running catchUp() every minute or so turns all of those into a short delay rather than a lost event.

Keep the catch-up query cheap. It runs at every start, reconnect and tick, so it shouldn't scan years of history. Delete or archive handled events after a while, or limit the query to recent rows (created_at > now() - interval '1 day', with an index on created_at).

Use retryDelayMax for the database, not for correctness. A shorter pause narrows the gap after an outage (4 lost instead of up to 46 at 1 second) at the cost of more connection attempts against a database that is starting up. The catch-up makes the number irrelevant for losing events, so pick it for how gently you want to treat the database.

Several replicas are fine. With the same consumer name, every replica claims through the same handled table, so each event is handled once, whichever replica got the notification or ran the catch-up. @imqueue/pg-pubsub can also elect a single listener per channel (singleListener, on by default); the catch-up then also covers the moment when the listening replica changes. One notification, every replica explains how that election works.

Keep notifications small. A NOTIFY payload is limited to 8,000 bytes, and notify() throws a RangeError beyond that. Sending only the event's id, as above, keeps every notification tiny and leaves the data in the table where the catch-up can find it.

When LISTEN/NOTIFY is the right tool

With a catch-up query, LISTEN/NOTIFY is a fine way to react quickly to changes that already live in Postgres: invalidating a cache, refreshing a read model, starting work after an order is paid. You get low latency from the notification and completeness from the table.

If what you need is a queue that holds work for consumers that are offline, spreads it across workers and retries it, that's a different tool. An @imqueue service or job queue on Redis keeps messages until they're taken; LISTEN/NOTIFY never will.

FAQ

Does Postgres store notifications for a listener that is disconnected?

No. A notification goes only to connections that are listening when the transaction commits. A listener that reconnects later receives only what is sent after it runs LISTEN again. In our test, a listener that was down for 5 seconds missed all 98–99 events written in that time.

Are notifications lost when Postgres restarts?

A quick restart lost nothing in our test, because no transaction can commit while the database is down. Losses come from the time after the database is back but before the listener is listening again: with the default reconnect settings that was about 2.4 seconds after a 20-second outage, and 28–46 events.

How do I recover missed LISTEN/NOTIFY messages?

Keep each event in a table and send its notification in the same transaction. When the listener starts or reconnects, listen first, then query the events this consumer hasn't handled yet. Record handled events in a table with a primary key on (consumer, event id) so an event that arrives twice is handled once.

Does @imqueue/pg-pubsub reconnect automatically?

Yes. It reconnects after the connection drops, waiting 100 ms first and doubling the wait after each failed attempt up to 10 seconds (retryDelay and retryDelayMax). It listens to its channels again before it emits 'reconnect', which is the right moment to run a catch-up query.

Should I send notifications with pg_notify or with pubSub.notify()?

When the notification announces a row, use pg_notify in the same transaction as the row, so the notification is sent only if the row commits. pubSub.notify() runs on its own connection, outside your transaction.

Reference

PgPubSub · PgPubSub.connect() · PgPubSub.listen() · PgPubSub.notify() · PgPubSub.channels · PgPubSubOptions.retryDelay · PgPubSubOptions.retryDelayMax · PgPubSubOptions.singleListener · One notification, every replica: the LISTEN/NOTIFY duplicate problem · When Redis restarts

Read this page as plain markdown — no HTML, no navigation. For pasting into an LLM, or for an agent to fetch.


Building on @imqueue? The open-source packages live on GitHub and the docs at imqueue.org. Shipping inside a closed-source product? See commercial licensing & support.