PostgreSQLLISTEN / NOTIFY

LISTEN / NOTIFY

LISTEN and NOTIFY are PostgreSQL's built-in, lightweight publish/subscribe mechanism: one client can broadcast a message on a named channel, and any other client connections currently listening on that channel receive it immediately — no separate message queue system required.
Listening on a channel
A client subscribes to a channel by running LISTEN on its connection:

SQL
LISTEN inventory_updates;
That connection is now subscribed. It will keep receiving notifications on inventory_updates until it either runs UNLISTEN or disconnects.
Sending a notification
Any other connection can broadcast a message to that channel with NOTIFY, optionally including a text payload:

SQL
NOTIFY inventory_updates, 'sku:WM-2201 restocked';

Equivalently, using the function form — handy when the payload is built dynamically inside a PL/pgSQL function or trigger:

SQL
SELECT pg_notify('inventory_updates', 'sku:' || sku || ' restocked');

Listening connections receive it as an event, for example via psql:

Asynchronous notification "inventory_updates" with payload
"sku:WM-2201 restocked" received from server process with PID 4821.
Use cases
  • Cache invalidation. When a row changes, a trigger fires NOTIFY, and an application process listening on that channel evicts the relevant cache entry — without polling the database.

  • Simple real-time notifications. Chat presence, live dashboard updates, or "someone else is editing this record" indicators can be built directly on LISTEN/NOTIFY without standing up Kafka, Redis pub/sub, or a similar dedicated message broker.

Note
This is a genuinely distinctive PostgreSQL feature — few other relational databases ship anything quite like a built-in publish/subscribe channel. But it comes with real limitations: payloads are capped in size (a few thousand bytes), and there is no persistence or delivery guarantee — if no client is listening at the moment NOTIFY runs, the message is simply gone. It is best suited to "nice to have" notifications, not critical message delivery that must never be missed.
  • LISTEN channel_name subscribes the current connection to a channel.

  • NOTIFY channel_name, 'payload' (or pg_notify()) broadcasts a message to all current listeners.

  • Great for cache invalidation and lightweight real-time updates.

  • No persistence and no delivery guarantee — a message sent while nobody is listening is lost.