Skip to main content
Postgres LISTEN/NOTIFY in Node.js and NestJS: How We Invalidate Caches Across Replicas Without Losing Notifications on Reconnect

Postgres LISTEN/NOTIFY in Node.js and NestJS: How We Invalidate Caches Across Replicas Without Losing Notifications on Reconnect

November 27, 2026
Backend Engineering
8 min read

Headline: PostgreSQL LISTEN/NOTIFY is a transactional signal, not a message queue: a notification is delivered only if the sending transaction commits, and it is lost for any listener that is disconnected at that moment. At Devya we use it to invalidate in-memory caches across NestJS replicas, with ids-only payloads, one dedicated listener connection per process, and a full cache flush after every reconnect.

LISTEN/NOTIFY is PostgreSQL's built-in publish/subscribe mechanism: a session runs LISTEN on a channel, and any transaction that runs NOTIFY or SELECT pg_notify('channel', 'payload') sends an asynchronous message to every listening session when it commits. It needs no extra infrastructure, which is exactly why teams misuse it. These are our notes on what it guarantees, where it beats Redis Pub/Sub, how we wire a listener into NestJS so it survives connection drops, and the limits that tell us to reach for something else.

Key takeaways

• Commit-gated delivery: PostgreSQL delivers a NOTIFY only when the sending transaction commits, so a rolled-back write never produces a stale invalidation.

• Not durable: PostgreSQL does not store notifications for disconnected listeners, so a Node.js listener must resync, for example by flushing its cache, after every reconnect.

• Small payloads: a NOTIFY payload must be shorter than 8000 bytes in a default PostgreSQL build, so we send ids and table names, never rows.

• Session connection required: LISTEN does not work through PgBouncer in transaction pooling mode; the listener needs a direct or session-mode connection.

• Commits that notify are serialized: PostgreSQL takes a global lock while committing a transaction that issued NOTIFY, which caps throughput on write-heavy paths.

What does Postgres LISTEN/NOTIFY actually guarantee?

PostgreSQL LISTEN/NOTIFY guarantees commit-gated, ordered, at-most-once delivery to sessions that are connected and listening at commit time. The PostgreSQL documentation for NOTIFY spells out the rules we design around:

• Transactional: a notification issued inside a transaction is held until COMMIT and discarded on ROLLBACK.

• Ordered: notifications from one transaction arrive in the order sent, and notifications from different transactions arrive in commit order.

• Deduplicated per transaction: if one transaction sends the same channel and identical payload several times, PostgreSQL delivers it once.

• Deferred for busy listeners: a listening session that is inside a transaction receives its notifications only after that transaction ends.

• No access control: any role that can connect to the database can LISTEN on any channel, so a payload is never the place for personal data or secrets.

What LISTEN/NOTIFY does not guarantee is persistence. A notification is fanned out to the sessions listening at commit time, and nothing replays it for a session that connects a second later.

When should we use LISTEN/NOTIFY instead of Redis Pub/Sub or CDC?

We use LISTEN/NOTIFY when the signal must follow a database commit, the volume is modest, and a missed message can be repaired by a resync. Cross-replica cache invalidation fits all three. How the options compare:

• Postgres LISTEN/NOTIFY: tied to the commit, not durable, no extra infrastructure. Best for cache invalidation, waking a worker, and live UI hints.

• Redis Pub/Sub: a second write after the commit, not durable, needs Redis. Best for high-volume fan-out when Redis already runs.

• Redis Streams or a job queue: durable, but tied to the commit only when fed by an outbox. Best for work that must happen once per event.

• Logical replication or CDC (Debezium, pgoutput): tied to the commit and durable through a replication slot, but needs a connector and slot monitoring. Best for streaming every change, in order, to another system.

• Polling a table: tied to the commit, durable, no extra infrastructure. Best for low-urgency sync where seconds of latency are fine.

The deciding question is what happens if one message is lost. If the answer is that a cache entry stays stale until its TTL, LISTEN/NOTIFY is enough. If the answer is that a customer is never charged, the event needs a durable channel, which usually means a transactional outbox.

How do we send notifications from a trigger or from Node.js?

We send notifications from an AFTER row trigger, so every write path, including migrations and manual SQL, invalidates the cache without application code having to remember. The trigger function calls pg_notify('cache_invalidation', ...) with a JSON object built by json_build_object that holds TG_TABLE_NAME and the row's primary key (OLD.id on DELETE, NEW.id otherwise), and it is attached with AFTER INSERT OR UPDATE OR DELETE ... FOR EACH ROW EXECUTE FUNCTION.

• Use pg_notify() for dynamic values: NOTIFY is a utility command that does not accept bind parameters, so from node-postgres we call SELECT pg_notify($1, $2) instead of building a NOTIFY string.

• Keep channel names lowercase: LISTEN CacheInvalidation folds the unquoted identifier to cacheinvalidation, while pg_notify('CacheInvalidation', ...) uses the exact string, so a mixed-case channel silently never matches.

• Send ids, not rows: a payload of 8000 bytes or more fails with "payload string too long", and the listener should load fresh data on the next read rather than trust a copy serialized inside the trigger.

How do we listen from NestJS without losing notifications on reconnect?

A NestJS listener needs one dedicated pg.Client per process, never a pooled connection, because a pool hands connections back and forth and a LISTEN belongs to one session. Our provider implements OnModuleInit and OnModuleDestroy: it opens a Client with keepAlive enabled against a direct database URL, registers a notification handler, runs LISTEN cache_invalidation, clears the local cache, and reconnects with capped exponential backoff whenever the client emits end.

• Flush on every reconnect: notifications sent while the listener was down are gone for good, so clearing the local cache after LISTEN succeeds is the only way to guarantee no stale entry survives a reconnect.

• Bypass transaction pooling: PgBouncer in transaction mode does not support LISTEN, so the listener uses a direct database URL or a session-mode pooler, while normal queries keep using the pool.

• Detect half-open connections: an idle listener can sit behind a NAT or load balancer that drops the TCP flow silently. keepAlive: true enables TCP keepalive, and we also run SELECT 1 on the listener every 30 seconds with a timeout, ending the client on failure so the reconnect logic takes over.

• Let replicas process their own notifications: the writing replica also receives the notification. Cache deletion is idempotent, so we do not filter by msg.processId, which is the PID of the sending backend and rarely maps cleanly to a pooled write connection.

With postgres.js instead of node-postgres, sql.listen(channel, onNotify, onListen) reconnects and re-runs LISTEN automatically, and the onListen callback is the place for the same cache flush.

What breaks LISTEN/NOTIFY at scale?

LISTEN/NOTIFY breaks down on write-heavy paths, on stuck listeners, and on designs that open one database connection per browser. The limits we check before adopting it:

• Commit serialization: PostgreSQL takes a global lock during the commit of any transaction that issued NOTIFY, so those commits run one at a time across the cluster. At modest write rates this is invisible; on a hot ingest path that notifies per row, it becomes the bottleneck. Check the release notes of your PostgreSQL major version before assuming otherwise.

• The notification queue: pending notifications live in a shared queue, 8 GB in a standard installation. A listening session that stays inside a long transaction stops the queue from being cleaned up, and once the queue fills, every transaction that calls NOTIFY fails at commit. We alert when SELECT pg_notification_queue_usage() rises above a small fraction.

• Bulk writes: a row-level trigger turns one UPDATE of 50,000 rows into 50,000 notifications. For tables that receive bulk writes, we use a statement-level trigger (FOR EACH STATEMENT) that sends one table-changed notification, and the listener flushes that table's cache prefix.

• Connections per subscriber: every LISTEN holds a full PostgreSQL backend. We run one listener per Node.js process and fan out in memory, for example to Server-Sent Events clients through an EventEmitter, instead of one database connection per browser tab.

• Short-lived runtimes: a listener needs a long-lived process, so it lives in NestJS replicas or a worker, not in request-scoped serverless functions that are frozen between invocations.

FAQ

Q: Is Postgres NOTIFY delivered if the transaction rolls back?

A: No. PostgreSQL delivers a notification only when the transaction that issued NOTIFY or pg_notify() commits; a rollback discards it.

Q: What is the maximum payload size for Postgres NOTIFY?

A: In a default PostgreSQL build, the payload must be shorter than 8000 bytes. Larger payloads fail with "payload string too long", so send an id and re-read the row.

Q: Does LISTEN/NOTIFY work with PgBouncer?

A: Not in transaction pooling mode, because LISTEN is session state and PgBouncer in that mode reassigns server connections between transactions. Use a direct connection or a session-mode pool for the listener.

Q: Can LISTEN/NOTIFY be used as a job queue?

A: Not on its own, because notifications are not stored for disconnected listeners. Store jobs in a table and use NOTIFY only to wake workers, which then claim rows with SELECT ... FOR UPDATE SKIP LOCKED.

Q: How do you receive Postgres notifications in Node.js?

A: With node-postgres, open a dedicated pg.Client, register client.on('notification', handler), and run LISTEN channel_name. With postgres.js, call sql.listen(channel, handler).