PostgreSQL provides a built-in messaging mechanism called LISTEN and NOTIFY. It allows one database session to send a notification and other sessions to receive it without repeatedly querying a table to check whether something has changed.
This feature is useful in applications that need to react to database events. For example, an order-processing service might notify other application components when an order is created. A background worker might listen for changes to a job queue, or a notification service might react when a new message becomes available.
The implementation is relatively simple. One session executes LISTEN to subscribe to a notification channel, and another session executes NOTIFY to publish a message. PostgreSQL delivers the notification to listening sessions when the transaction that issued NOTIFY commits.
However, applications using LISTEN and NOTIFY need additional planning when PostgreSQL runs with high availability or automatic failover.
A database failover replaces the current primary server with another server. Existing database connections are usually interrupted during this process. Since LISTEN registrations belong to individual database sessions, they do not automatically move to the new primary.
This means an application can reconnect successfully after failover but still stop receiving notifications because its new database connection has not registered its LISTEN subscriptions again.
There is another important concern: notifications are not a durable message queue. If an application is disconnected when a notification is delivered, it should not assume that PostgreSQL will store and replay that notification after reconnecting.
In this article, we will look at how LISTEN and NOTIFY work, why they need special handling during failover, and how to build a more reliable notification mechanism for production applications.
Understanding PostgreSQL LISTEN and NOTIFY
LISTEN and NOTIFY provide a lightweight communication mechanism between PostgreSQL sessions.
The LISTEN command registers the current database session to receive notifications from a particular channel.
For example:
LISTEN order_events;
This tells PostgreSQL that the current session wants to receive notifications sent through the order_events channel.
Another database session can publish a notification:
NOTIFY order_events, 'New order created';
PostgreSQL delivers the notification to sessions that are listening on that channel, provided the transaction issuing NOTIFY commits successfully.
An application can also attach a payload to a notification. This payload is a text value that can contain a small amount of information about the event.
For example:
NOTIFY order_events, '{"orderId": 10501, "status": "Created"}';
A listener receives the channel name, payload, and notification information through its database connection.
In a .NET application using Npgsql, the notification can be handled through the connection's notification event.
The important point is that LISTEN and NOTIFY operate through database connections. A subscription is associated with the session that executed LISTEN, not with the application as a whole.
If that connection disappears, the subscription disappears with it.
Why Failover Interrupts LISTEN Subscriptions
In a typical PostgreSQL high-availability setup, one server acts as the primary database and one or more servers act as standbys.
The primary accepts writes and generates WAL records. Standby servers receive and replay those records to maintain a copy of the database.
If the primary becomes unavailable, a standby may be promoted to become the new primary.
Applications connected to the previous primary will generally lose their existing database connections. They must establish new connections to the promoted server.
This creates a problem for applications using LISTEN and NOTIFY.
Consider the following sequence:
An application connects to the original primary.
The application executes LISTEN order_events.
Another service creates an order and publishes a notification.
The primary becomes unavailable.
A standby is promoted.
The application reconnects to the new primary.
At this point, the application may have a working database connection, but it is no longer listening on order_events.
The new connection is a different PostgreSQL session. PostgreSQL does not automatically restore the LISTEN registration from the old session.
This behavior is expected. LISTEN subscriptions are session-level state, not replicated database objects.
The application must execute LISTEN again after reconnecting.
Build a Reliable Reconnection Strategy
A common mistake is assuming that a connection pool or database driver will automatically restore every session-level setting after a connection failure.
Connection pooling can help applications reuse connections, but it does not guarantee that a newly created connection has the same LISTEN registrations as the previous connection.
Your application should explicitly manage the notification listener.
A reliable listener needs to handle several responsibilities:
Establish a connection to the current primary.
Register all required LISTEN channels.
Wait for incoming notifications.
Detect connection failures.
Dispose of the failed connection.
Reconnect with an appropriate delay.
Register LISTEN channels again.
Resume notification processing.
Recover any events that may have been missed.
The last responsibility is particularly important. Reconnecting and registering LISTEN again restores future notifications, but it does not recover notifications delivered while the application was disconnected.
That requires a separate event recovery mechanism.
Example: Listening for Notifications With Npgsql
Npgsql provides notification support for PostgreSQL applications built with .NET.
The following example shows the basic structure of a listener:
using Npgsql;
public sealed class OrderNotificationListener
{
private readonly string _connectionString;
public OrderNotificationListener(string connectionString)
{
_connectionString = connectionString;
}
public async Task StartAsync(
CancellationToken cancellationToken)
{
await using var connection =
new NpgsqlConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
connection.Notification += (_, notification) =>
{
Console.WriteLine(
$"Channel: {notification.Channel}");
Console.WriteLine(
$"Payload: {notification.Payload}");
};
await using (var command = new NpgsqlCommand(
"LISTEN order_events;", connection))
{
await command.ExecuteNonQueryAsync(
cancellationToken);
}
while (!cancellationToken.IsCancellationRequested)
{
await connection.WaitAsync(cancellationToken);
}
}
}
This example opens a connection, registers the order_events channel, and waits for notifications.
The notification event handler receives the channel and payload when PostgreSQL delivers a notification.
However, this example does not implement reconnection. If the database connection fails during failover, the listener stops working.
For a production application, the listening process should run inside a reconnect loop.
Implement Reconnection After Failover
A more practical listener separates connection management from notification processing.
The following example uses a reconnect loop and registers the LISTEN subscription every time a new connection is established.
using Npgsql;
public sealed class OrderNotificationListener
{
private readonly string _connectionString;
public OrderNotificationListener(string connectionString)
{
_connectionString = connectionString;
}
public async Task RunAsync(
CancellationToken cancellationToken)
{
var retryDelay = TimeSpan.FromSeconds(2);
var maximumDelay = TimeSpan.FromSeconds(30);
while (!cancellationToken.IsCancellationRequested)
{
try
{
await ListenAsync(cancellationToken);
retryDelay = TimeSpan.FromSeconds(2);
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
break;
}
catch (NpgsqlException ex)
{
Console.WriteLine(
$"Database connection failed: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine(
$"Notification listener failed: {ex.Message}");
}
await Task.Delay(retryDelay, cancellationToken);
retryDelay = TimeSpan.FromSeconds(
Math.Min(
retryDelay.TotalSeconds * 2,
maximumDelay.TotalSeconds));
}
}
private async Task ListenAsync(
CancellationToken cancellationToken)
{
await using var connection =
new NpgsqlConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
connection.Notification += (_, notification) =>
{
Console.WriteLine(
$"Received: {notification.Payload}");
};
await using var command = new NpgsqlCommand(
"LISTEN order_events;",
connection);
await command.ExecuteNonQueryAsync(cancellationToken);
Console.WriteLine(
"Listening for PostgreSQL notifications.");
while (!cancellationToken.IsCancellationRequested)
{
await connection.WaitAsync(cancellationToken);
}
}
}
This implementation uses an increasing retry delay so that the application does not continuously attempt to connect while the database is unavailable.
When the connection fails, the method exits, the connection is disposed, and the outer loop attempts to establish a new connection.
Once the connection is restored, the LISTEN command runs again.
For production use, add structured logging, metrics, and monitoring around the reconnect process. You should also review how cancellation and retry delays are handled in your application's hosting environment.
A successful connection is not enough to confirm that the listener is ready. Record when the LISTEN command completes so that operators can distinguish between a connected application and an application that is actively listening.
Why Reconnecting Is Not Enough
Restoring the LISTEN subscription solves only one part of the problem.
PostgreSQL notifications are not stored as durable messages for disconnected consumers. They are intended for lightweight signaling between active database sessions.
Suppose a background service listens for order_events. The primary fails, and the service takes 20 seconds to reconnect.
During those 20 seconds, several orders are created after the new primary becomes available.
If the application relies only on notifications, it may not know that these orders need processing.
The listener can reconnect successfully and receive future notifications, but it cannot automatically recover every event that occurred during the interruption.
This is why applications should not use LISTEN and NOTIFY as the only record of important business events.
A better design stores the actual event in a database table and uses NOTIFY only to tell listeners that new work may be available.
Use an Outbox Table for Reliable Event Processing
The transactional outbox pattern is a useful approach when an application needs reliable event processing.
Instead of relying on a notification payload as the complete event, the application writes an event record to a table in the same transaction as the business operation.
For example, create an outbox table:
CREATE TABLE event_outbox
(
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
processed_at TIMESTAMPTZ
);
When an order is created, insert both the order and its corresponding event inside the same transaction:
BEGIN;
INSERT INTO orders
(
customer_id,
status
)
VALUES
(
1001,
'Created'
);
INSERT INTO event_outbox
(
event_type,
payload
)
VALUES
(
'OrderCreated',
'{"orderId": 10501}'
);
SELECT pg_notify(
'order_events',
'new_event_available'
);
COMMIT;
The business record and outbox record are committed together.
The notification acts as a signal that new events are available. The background worker then reads pending events from the outbox table and processes them.
If the listener disconnects during failover, the outbox records remain available. When the worker reconnects, it can query the table and continue processing events that were not completed.
This changes the responsibility of NOTIFY. Instead of carrying the only copy of an event, it simply tells the application that it should check for pending work.
One important detail is that the notification is delivered only after the transaction commits. If the transaction rolls back, PostgreSQL does not deliver the notification.
That makes it suitable for signaling committed database changes.
Make Event Processing Idempotent
Reliable notification handling also requires protection against duplicate processing.
A background worker might successfully process an event but fail before updating its processed status. When it reconnects, it may attempt to process the same event again.
For example, a payment-processing workflow must not charge a customer twice because a worker retried an event after a database failover.
An idempotent operation produces the same intended result when the same event is processed more than once.
You can use the outbox event ID as a unique identifier and maintain a processing record in the receiving system.
For example:
CREATE TABLE processed_events
(
event_id BIGINT PRIMARY KEY,
processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Before applying an event, the worker should check whether it has already been processed. The business operation and the processing record should be coordinated transactionally wherever possible.
For operations involving external services, use the event ID as an idempotency key when the external system supports it.
This is important because database notifications, network failures, and worker restarts can all lead to repeated processing attempts.
Handle Multiple Listeners and Connection Pools
Another production consideration is how many application instances listen to the same channel.
For example, suppose an application runs five background worker instances, and all five execute:
LISTEN order_events;
When PostgreSQL sends a notification on that channel, every connected listener receives it.
This behavior may be useful when all instances need to refresh local state. However, it may not be appropriate when the notification represents a job that should be processed by only one worker.
LISTEN and NOTIFY do not provide competing-consumer queue semantics.
If every listener receives the same notification and each worker processes the same event, your application can perform duplicate work.
For job processing, use a shared durable queue or an outbox table with a controlled claiming strategy. For example, workers can use SELECT FOR UPDATE SKIP LOCKED to claim different pending records without blocking one another unnecessarily.
Also avoid treating a pooled application connection as a permanent notification listener unless the pool and connection lifecycle are explicitly designed for it.
A dedicated connection is generally easier to manage because it has a clear purpose: maintain LISTEN subscriptions and receive notifications.
Regular application queries can use separate pooled connections.
Monitor Replication and Failover Behavior
If your PostgreSQL environment uses streaming replication and automatic failover, the notification listener should be tested as part of the complete high-availability setup.
A successful failover does not guarantee that every application component has recovered.
Monitor the listener's connection state, last successful LISTEN registration time, reconnect attempts, and time spent disconnected.
It is also useful to monitor replication health and failover status from your database infrastructure.
For a production system, test scenarios such as:
The primary database becomes unavailable.
A standby is promoted.
The application connection is terminated.
The listener reconnects to the new primary.
The LISTEN registration is restored.
New notifications are received.
Events created during the interruption are recovered from the outbox.
Do not perform disruptive failover testing directly on production without an approved procedure. Use a staging environment that closely matches your production topology first.
Common Mistakes to Avoid
One common mistake is assuming that LISTEN subscriptions survive database failover. They are session-level registrations, so applications must recreate them after reconnecting.
Another mistake is assuming that PostgreSQL stores notifications until a disconnected application becomes available. Notifications are not a durable queue, and disconnected listeners can miss them.
Using a notification payload as the only copy of an important business event is also risky. If the listener is disconnected, there may be no reliable way to recover that event. Store important events in a table or another durable messaging system.
Applications should also avoid creating a new connection for every notification. A dedicated long-running listener connection is usually more efficient and easier to manage.
Finally, do not assume that every listener should process every notification. Multiple sessions listening on the same channel all receive the notification. If an event represents a job that should run once, use a proper claiming and processing strategy.
Summary
PostgreSQL LISTEN and NOTIFY provide a simple way for application components to react to database events without repeatedly querying tables. They are useful for lightweight signaling, cache refreshes, background processing triggers, and other event-driven workflows.
However, LISTEN subscriptions belong to individual database sessions. When PostgreSQL fails over to another server, existing connections are interrupted, and applications must reconnect and register their subscriptions again.
Reconnection alone does not recover notifications that were missed while the application was disconnected. For important business events, use a durable mechanism such as a transactional outbox table and treat NOTIFY as a signal that new work may be available.
A reliable implementation should include connection recovery, subscription restoration, event persistence, idempotent processing, and monitoring.
The main principle is simple: use LISTEN and NOTIFY to make applications aware of changes, but do not depend on notifications as the only place where important events exist. This approach makes event-driven PostgreSQL applications much more resilient during failover and temporary database outages.
Join the conversation! Your thoughts help the community grow.