LISTEN NOTIFY Session Messaging

Deliver session-to-session signals with NOTIFY, which queues messages only at commit and drops them silently when nobody is listening.

SqlResilience

Code

snippet
-- LISTEN/NOTIFY 是会话间异步通道:消息不落表,无人监听即丢弃
LISTEN order_events;

NOTIFY order_events, 'order 42 shipped';

-- payload 是字符串字面量,上限 8000 字节;通道名是不加引号就转小写的标识符
SELECT pg_listening_channels() AS my_channels;

-- 事务语义:NOTIFY 只在提交时送达,回滚的通知永远不会发出
BEGIN;
NOTIFY order_events, 'will be rolled back';
ROLLBACK;

-- 清理:不再监听时显式取消
UNLISTEN order_events;

How it works

The file walks one LISTEN/NOTIFY round trip plus its transaction semantics. LISTEN order_events; registers the current session on the channel; NOTIFY order_events, 'order 42 shipped'; publishes a string payload to every session listening on it. SELECT pg_listening_channels() AS my_channels; reports which channels this session is subscribed to, confirming the registration.

The transaction block demonstrates the delivery rule stated in the file’s comment: notifications are queued only at commit. BEGIN; opens a transaction, NOTIFY order_events, 'will be rolled back'; queues a payload, and ROLLBACK; discards it — a notification inside a rolled-back transaction is never delivered. UNLISTEN order_events; then removes the subscription explicitly.

What to watch for

  • Per the comments: messages never land in a table and are dropped silently when nobody is listening — this is a lossy signal channel, suitable for events like cache invalidation where a missed message is tolerable.
  • The payload is a string literal capped at 8000 bytes, and channel names are identifiers lowercased when unquoted.

Using it

The statements run in order: subscribe (LISTEN), publish (NOTIFY), inspect (pg_listening_channels()), show rollback discards queued notifications, then unsubscribe (UNLISTEN). Each is a session-level command, so the whole sequence works in any client session without setup.

Key statements

SELECT pg_listening_channels() AS my_channels;
NOTIFY order_events, 'will be rolled back';
NOTIFY order_events, 'order 42 shipped';

Interactive Tools for This Topic