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
LISTEN on its connection:LISTEN inventory_updates;
inventory_updates until it either runs UNLISTEN or disconnects.Sending a notification
NOTIFY, optionally including a text payload: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:
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/NOTIFYwithout standing up Kafka, Redis pub/sub, or a similar dedicated message broker.
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_namesubscribes the current connection to a channel.NOTIFY channel_name, 'payload'(orpg_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.