Postgres LISTEN/NOTIFY lets any database session push a short text message to every connection that is listening on a channel, and the message is delivered only when the sending transaction commits. It is a good fit for "something changed, go and look" signals; it is a poor fit for carrying data, because payloads must be under 8,000 bytes and nothing is stored for a listener that is offline. WoWSQL Realtime is built on pg_notify and handles the WebSocket side for you, and this guide shows the patterns that keep a self-built LISTEN worker correct: send the key not the row, catch up from a change cursor, and reconnect on failure.
How we tested: every behaviour claimed below was reproduced on PostgreSQL 17.12 with node-postgres 8.x on 2 December 2026, using the SQL and Node.js files in this article. Limits and guarantees we did not test ourselves are linked to the PostgreSQL 19 documentation (the current version on postgresql.org on 2 December 2026).
Key facts
- Payload limit: in the default configuration a payload "must be shorter than 8000 bytes" (NOTIFY docs, checked 2 Dec 2026). That is bytes, not characters: in our test, 7,999 ASCII characters worked, 8,000 failed with
payload string too long, and 4,000écharacters (8,000 bytes) also failed.- Commit only: notifications sent inside a transaction are delivered when it commits and dropped if it rolls back. Messages from different transactions arrive in commit order.
- Not stored: a session that is not listening when the transaction commits never gets the message. There is no replay.
- Duplicates fold: identical channel and payload pairs sent in one transaction are delivered once.
- Queue: undelivered notifications wait in a queue of up to
max_notify_queue_pages(default 1,048,576 pages, about 8 GB). If it fills, transactions that call NOTIFY fail at commit (runtime config, checked 2 Dec 2026).- Poolers: PgBouncer lists LISTEN as "Never" supported in transaction pooling mode (PgBouncer features, checked 2 Dec 2026). Use a direct or session-pooled connection.
- WoWSQL: Realtime APIs are on every plan, Free $0, Pro $25/month and Scale $99/month (pricing), in Mumbai, US East and Frankfurt. Change events go through
pg_notify, so the 8,000-byte limit applies to realtime-enabled tables too.
How LISTEN/NOTIFY works
-- Session A
LISTEN order_changes;
-- Session B
NOTIFY order_changes, 'order 42 changed';
-- or, from a function or trigger, where the channel can be a variable:
SELECT pg_notify('order_changes', 'order 42 changed');
Session A's client receives the channel name, the payload and the process ID of the sender. In node-postgres that arrives as a notification event on the client. Three details trip people up:
LISTENfolds case,pg_notifydoes not.LISTEN OrderChangeslistens onorderchanges. In our test,pg_notify('OrderChanges', ...)was never received andpg_notify('orderchanges', ...)was. Use lowercase channel names everywhere.- A listener inside a transaction waits. If the listening session is in the middle of a transaction, notifications are held until that transaction ends. In our test the listener got 0 messages while its transaction was open and 1 straight after
COMMIT. - Start-up race. The LISTEN docs give the rule: run and commit
LISTENfirst, then read the current state, then rely on notifications. The first few may repeat what you already read, which is harmless if your handler is idempotent.
What we reproduced
| Experiment (PostgreSQL 17.12) | Result |
|---|---|
| Insert inside a transaction, wait 300 ms, then commit | 0 notifications before commit, 1 after; sender PID matched the writer |
Insert, then ROLLBACK |
0 notifications |
pg_notify('demo','same') three times plus 'a' and 'b' in one transaction |
Delivered same, a, b (duplicates folded) |
| Listener inside an open transaction | 0 while open, 1 after its COMMIT |
LISTEN OrderChanges, then notify OrderChanges and orderchanges |
Only orderchanges received |
Insert before a second client ran LISTEN |
0 received by that client |
| 5,000-row insert with a per-row trigger | 5,000 notifications |
| 5,000-row insert with a per-statement trigger | 1 notification: {"op":"INSERT","rows":5000,"max_seq":10003} |
| 10,000-row update with a per-statement trigger | 1 notification |
Trigger that sends row_to_json(NEW), insert with an 8,000-character text column |
Insert failed with payload string too long and rolled back |
The last row is the one that bites in production: a trigger that ships the whole row works in testing, then a user pastes a long comment and their write fails.
Step 1: Send the key, not the row
Keep the payload tiny and fixed-size, and give the table a change cursor so a listener can find everything it missed. This schema adds a change_seq column that a sequence bumps on every insert and update:
-- 1. A table with a change cursor, so listeners can catch up after missing a notification
create sequence public.orders_change_seq;
create table public.orders (
id bigint generated always as identity primary key,
customer text not null,
status text not null default 'new',
notes text,
change_seq bigint not null default nextval('public.orders_change_seq')
);
create index orders_change_seq_idx on public.orders (change_seq);
-- Bump the cursor on every update
create or replace function public.orders_bump_seq()
returns trigger language plpgsql as $$
begin
new.change_seq := nextval('public.orders_change_seq');
return new;
end $$;
create trigger orders_bump_seq
before update on public.orders
for each row execute function public.orders_bump_seq();
-- 2. Send the key, not the row: a tiny payload that can never hit the 8,000-byte limit
create or replace function public.orders_notify()
returns trigger language plpgsql as $$
begin
perform pg_notify('order_changes', json_build_object(
'op', tg_op,
'id', coalesce(new.id, old.id),
'seq', coalesce(new.change_seq, 0)
)::text);
return null; -- AFTER trigger: the return value is ignored
end $$;
create trigger orders_notify
after insert or update or delete on public.orders
for each row execute function public.orders_notify();
The payload is a few dozen bytes whatever the row contains, so it cannot hit the limit. The listener reads the row itself, which also means it reads the committed version rather than a snapshot that might be stale by the time it is processed.
Step 2: One notification per statement for bulk writes
A per-row trigger sends one notification per row. For imports and batch updates, a statement-level trigger with a transition table sends one message per statement, which kept our 5,000-row insert to a single notification:
-- One notification per statement instead of per row (for bulk imports)
create or replace function public.orders_notify_bulk()
returns trigger language plpgsql as $$
begin
perform pg_notify('order_changes', json_build_object(
'op', tg_op,
'rows', (select count(*) from changed),
'max_seq', (select max(change_seq) from changed)
)::text);
return null;
end $$;
drop trigger orders_notify on public.orders;
create trigger orders_notify_ins after insert on public.orders
referencing new table as changed
for each statement execute function public.orders_notify_bulk();
create trigger orders_notify_upd after update on public.orders
referencing new table as changed
for each statement execute function public.orders_notify_bulk();
Statement-level triggers with transition tables can't cover INSERT, UPDATE and DELETE in one trigger, hence one trigger per event. Deletes don't bump change_seq; if listeners need to see them, use soft deletes (deleted_at) or a small tombstone table.
Step 3: A listener that reconnects and catches up
Because notifications are not stored, a correct listener treats each one as a hint and always reads from the table, starting after the last change_seq it processed. After any reconnect it catches up before waiting for new hints:
// listener.mjs: a LISTEN worker that survives disconnects (node-postgres 8.x)
import pg from 'pg'
const DATABASE_URL = process.env.DATABASE_URL // a direct or session-pooled connection, not transaction pooling
let lastSeq = 0n // persist this somewhere durable in a real worker
let running = false
let again = false
// The notification is only a hint: always read what changed from the table
async function catchUp(db) {
if (running) { again = true; return } // a notification arrived mid-scan: scan once more afterwards
running = true
try {
do {
again = false
for (;;) {
const { rows } = await db.query(
'select id, customer, status, change_seq from public.orders where change_seq > $1 order by change_seq limit 500',
[lastSeq.toString()],
)
for (const row of rows) handle(row)
if (rows.length) lastSeq = BigInt(rows.at(-1).change_seq)
if (rows.length < 500) break
}
} while (again)
} finally {
running = false
}
}
function handle(row) {
console.error('changed', row.id, row.status) // your work here: push to clients, bust a cache, enqueue a job
}
async function run(attempt = 0) {
const db = new pg.Client({ connectionString: DATABASE_URL })
let retrying = false
const retry = () => {
if (retrying) return // 'end' and a failed connect can both fire: reconnect once
retrying = true
const delay = Math.min(1000 * 2 ** attempt, 30000)
console.error(`connection lost, reconnecting in ${delay} ms`)
setTimeout(() => run(attempt + 1), delay)
}
db.on('notification', () => { catchUp(db).catch((err) => console.error('catch-up failed', err.message)) })
db.on('error', (err) => console.error('listener error', err.message))
db.on('end', retry)
try {
await db.connect()
await db.query('LISTEN order_changes')
attempt = 0
await catchUp(db) // pick up anything that changed while we were away
} catch (err) {
console.error('connect failed:', err.message)
retry()
db.end().catch(() => {})
}
}
await run()
What we checked: a live insert was handled within one notification. We then killed the listener's backend with pg_terminate_backend, inserted two rows and updated a third while it was down; the worker logged reconnecting in 1000 ms, reconnected and handled all three changes from the catch-up query. Pointed at a closed port, it retried at 1, 2, 4 and 8 seconds with a single retry per failure.
Two honest limits of a sequence cursor:
- Commit order is not sequence order. A long transaction can take
change_seq100, commit after another transaction that took 101, and be skipped if the listener already moved past 101. If that matters, re-read with an overlap window (for example the last few hundred sequence values) and keephandle()idempotent, or move to logical decoding. - Persist
lastSeq. The example keeps it in memory; a real worker stores it after each batch so a restart doesn't replay everything or skip anything.
Step 4: Watch the queue
-- Fraction (0 to 1) of the notification queue in use
SELECT pg_notification_queue_usage();
-- Sessions sitting in a transaction for a long time hold back cleanup
SELECT pid, usename, state, now() - xact_start AS in_transaction_for
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start
LIMIT 5;
The NOTIFY docs say the queue can't be cleaned up while a listening session sits in a long transaction, and Postgres logs warnings that point at that session once the queue is half full. Alert well before that.
Does LISTEN/NOTIFY scale?
For a modest number of writers, yes. Under heavy concurrency there was a known bottleneck: Recall.ai reported in July 2025 that a transaction which has issued NOTIFY takes a global lock during commit, serialising commits across the database, and that it caused major downtime with tens of thousands of concurrent writers (Recall.ai, checked 2 Dec 2026). Their post was updated in May 2026 to say a January 2026 Postgres commit eliminated the bottleneck (commit 282b1cde); the commit message describes a shared channel map so NOTIFY stops waking backends that aren't listening, with "integer multiples" more throughput. That change is in PostgreSQL 19. On older versions, keep NOTIFY out of your hottest write paths: use statement-level triggers, or notify from a periodic job instead of every transaction. Run SELECT version(); to see what you're on.
Doing this on WoWSQL
You have two options on a WoWSQL project:
- Use WoWSQL Realtime and skip the worker. Enable a table and subscribe over a WebSocket with
@wowsql/sdk; the platform runs the LISTEN connection and fan-out. The same payload rule applies, so for tables with large text columns enable a small events table (IDs only) instead of the big table. Tables with Row Level Security can only be enabled and subscribed with the service key, and change events can't be filtered per subscriber, so relay them through your server or use the content-free events pattern from our chat app guide. See the Realtime docs.
// Server side: enable once, then subscribe (@wowsql/sdk 3.10.0)
// POST https://<project>.wowsqlconnect.com/realtime/v1/enable {"schema_name":"public","table_name":"order_events"}
import { WowSQLClient } from '@wowsql/sdk'
const db = new WowSQLClient({ projectUrl: process.env.WOWSQL_URL, apiKey: process.env.WOWSQL_SERVICE_KEY })
const sub = db.realtime.subscribe(
{ schema: 'public', table: 'order_events', event: 'INSERT' },
(change) => console.log(change.event, change.new), // then read the order itself through REST
)
- Run your own LISTEN worker. The dashboard shows a direct connection string in the form
postgresql://USER:[YOUR-PASSWORD]@db.<project>.wowsqlconnect.com:5432/postgres(dashboard docs). Set it asDATABASE_URLforlistener.mjs. We have not tested LISTEN against a live WoWSQL project, so confirm notifications arrive before you rely on it.
LISTEN/NOTIFY vs the alternatives
Checked 2 December 2026. Sources: PostgreSQL NOTIFY, logical decoding concepts, Supabase Postgres Changes, WoWSQL Realtime docs.
| LISTEN/NOTIFY | Polling a change cursor | Logical decoding | WoWSQL Realtime | Supabase Postgres Changes | |
|---|---|---|---|---|---|
| Latency | At commit | Your poll interval | Near commit | At commit, over WebSocket | Near commit, over WebSocket |
| Missed while offline | Lost | Never (re-query) | Kept by the replication slot | Lost; re-fetch on reconnect | No replay documented; re-fetch on reconnect |
| Payload | Under 8,000 bytes | Any (you query rows) | Full change | New and old row in one NOTIFY, so under 8,000 bytes combined | Full row |
| Setup | Trigger plus a listening connection | A column and a loop | Replication slot, plugin, consumer, slot-lag monitoring | Enable table, subscribe | Add table to a publication, subscribe |
| Risk | Queue growth, pooler incompatibility | Load from frequent polls | An idle slot keeps WAL and fills disk | RLS tables need the service key | Throughput limited by per-subscriber auth checks |
| Per-subscriber filtering | Your code | Your code | Your code | No server-side filters | Yes, server-side filters and RLS |
Where others are better: logical decoding is the only option here that doesn't lose changes while the consumer is away, because slots "persist independently of the connection" (at the cost of retaining WAL until consumed). Supabase Postgres Changes applies RLS and server-side filters per subscriber, which WoWSQL Realtime does not do today; Supabase's own docs note that this authorises every event for each subscriber and runs on a single thread, so throughput depends on subscriber count. Plain polling is the simplest thing that never loses data, and is often enough.
Related guides
- Postgres realtime updates without polling
- Build a realtime chat app with Postgres
- What is a realtime database?
- Also published today: Typing indicators and online presence, Razorpay webhooks into Postgres, Astro backend with Postgres and Nuxt 4 backend with Postgres
FAQ
What is the payload size limit for Postgres NOTIFY?
In the default configuration the payload must be shorter than 8,000 bytes. It is a byte limit, so multibyte characters count more than once. Send a row ID and read the row instead of sending the row.
Does Postgres NOTIFY work inside a transaction?
Yes, but delivery waits for the commit. If the transaction rolls back, listeners get nothing, and identical notifications sent in the same transaction are delivered once.
What happens to notifications when my listener is disconnected?
They are lost. Postgres does not store notifications for sessions that weren't listening at commit time, so reconnect, run LISTEN, then query for anything that changed since your last processed change.
Can I use LISTEN/NOTIFY with PgBouncer or a connection pooler?
Not in transaction pooling mode; PgBouncer lists LISTEN as never supported there. Use a direct connection or session pooling for the listening process, and pool everything else as usual.
Is LISTEN/NOTIFY good enough for realtime updates in my app?
For signals to a backend service, yes. For browsers you also need a WebSocket server that holds the LISTEN connection and fans out messages, which is what WoWSQL Realtime and similar services run for you.
LISTEN/NOTIFY vs logical replication: which should I use?
Use LISTEN/NOTIFY for lightweight signals where you can re-query after a gap. Use logical decoding when you need every change delivered even after downtime, and you can run and monitor a replication slot.
Create a free WoWSQL project · Realtime docs · TypeScript SDK docs