0
0
PostgresqlConceptBeginner · 3 min read

What is LISTEN and NOTIFY in PostgreSQL: Simple Explanation

LISTEN and NOTIFY are PostgreSQL commands that let database sessions send and receive simple messages. NOTIFY sends a notification, and LISTEN waits for those notifications, enabling real-time communication between sessions.
⚙️

How It Works

Imagine you are in a room where people can raise their hands to get attention. NOTIFY is like raising your hand to send a signal, and LISTEN is like watching for hands raised by others. When one session sends a notification with NOTIFY, all sessions that are LISTENing for that notification name get alerted.

This system works inside the database, so different clients or parts of an application can communicate without constantly checking the database for changes. It’s like a simple message board where you post a note (NOTIFY) and others watch for new notes (LISTEN).

💻

Example

This example shows how one session listens for a notification and another sends it.

sql
-- In session 1:
LISTEN my_event;

-- In session 2:
NOTIFY my_event, 'Hello listeners!';
Output
Asynchronous notification "my_event" received with payload "Hello listeners!"
🎯

When to Use

Use LISTEN and NOTIFY when you want different parts of your application to react quickly to changes without repeatedly asking the database. For example:

  • Updating a cache when data changes
  • Triggering background jobs after inserts or updates
  • Real-time alerts in web applications

This avoids slow polling and makes your app more efficient and responsive.

Key Points

  • NOTIFY sends a message with an optional payload.
  • LISTEN waits for notifications by name.
  • Notifications are asynchronous and lightweight.
  • Useful for inter-process communication inside PostgreSQL.

Key Takeaways

LISTEN and NOTIFY enable simple message passing between PostgreSQL sessions.
NOTIFY sends a named notification, and LISTEN waits for it asynchronously.
They help avoid constant database polling for changes.
Ideal for real-time updates and event-driven applications.
Notifications can include a small text payload for extra info.