What is LISTEN and NOTIFY?
Users can listen in on database activity using the LISTEN/NOTIFY capability. It is still one of PostgreSQL’s most used features despite being one of the older ones. What does the asynchronous query interface (LISTEN/NOTIFY) do, and why is it useful? The main query is To avoid polling is the essential tenet.
The code frequently functions like this:
while true SELECT * FROM todo_list; sleep; end
Numerous loads are put on the database for no reason if thousands of users poll it continuously. There must be a better way because the majority of polling requests are fruitless. The purpose of LISTEN/NOTIFY is to provide a better alternative to repeatedly polling the database. We instead connect to the database and wait for a pertinent event to rouse us up.
Set up PostgreSQL notifications
Two commands are relevant for using PostgreSQL notifications: Listen and be alert:
test=# \h LISTEN Command: LISTEN Description: listen for a notification Syntax: LISTEN channel URL: https://www.postgresql.org/docs/15/sql-listen.html
Your database connection will listen on a “channel” thanks to LISTEN. A channel is essentially just a name. It is unnecessary to make one or to make sure that one already exists. We will keep an eye on this name while waiting for a notification to arrive.
Notify any active database connections that are waiting: Using the NOTIFY command
test=# \h NOTIFY Command: NOTIFY Description: generate a notification Syntax: NOTIFY channel [ , payload ] URL: https://www.postgresql.org/docs/15/sql-notify.html
A channel and an optional payload—a regular string that is transmitted to the receiver—are all that are required to send a notice.
Let’s put it to the test and see how it performs:
test=# LISTEN x; LISTEN
LISTEN notifies the backend that we wish to be informed of messages arriving via channel “x” An application typically only listens to one channel. Nothing prevents us, however, from sending several LISTEN requests to listen to more than one channel at once. This is entirely possible and, occasionally, even quite desirable.
What happens when a notification is issued?
test=# NOTIFY x, 'some message'; NOTIFY Asynchronous notification "x" with payload "some message" received from server process with PID 62451.
The notification will be sent to all connections that used the LISTEN command to connect to the same channel.
Use triggers with LISTEN / NOTIFY
When a row is added to a table, we frequently want to let the client know. Use a table trigger installed for that purpose. Here is an illustration to illustrate how this operates:
CREATE TABLE t_message ( id serial, t timestamptz DEFAULT now(), message text ); CREATE FUNCTION capture_func() RETURNS trigger AS $$ DECLARE v_txt text; BEGIN v_txt := format('sending message for %s, %s', TG_OP, NEW); RAISE NOTICE '%', v_txt; EXECUTE FORMAT('NOTIFY mychannel, ''%s''', v_txt); RETURN NEW; END; $$ LANGUAGE 'plpgsql'; CREATE TRIGGER mytrigger BEFORE INSERT OR UPDATE ON t_message FOR EACH ROW EXECUTE PROCEDURE capture_func();
Another way: pg_notify()
The source code demonstrates how to establish a table and the trigger that will deliver notifications. EXECUTE was used in my example to execute dynamic SQL. But there is an additional approach as well:
SELECT pg_notify('mychannel', v_txt);
The pg_notify() function is a more tasteful method of communicating.
We use the INSERT statement to test the function.
INSERT INTO t_message (message) VALUES ('sample text');
The message will be sent:
NOTICE: sending message for INSERT, (1,"2022-07-13 16:18:24.709008+02","sample text")
When the transaction is actually committed, only then is the notification truly sent out. Why is this information significant? The modifications would not be apparent to other transactions if the transaction was sent out right after. Keep in mind that, unless you commit, updates are only visible to your own transaction. As soon as the first transaction is completed correctly, the message is sent to the second transaction. Recall that notifications are also a type of transaction because they can only be sent after a commit and not in the event of a rollback.
About Enteros
Enteros offers a patented database performance management SaaS platform. It proactively identifies root causes of complex business-impacting database scalability and performance issues across a growing number of clouds, RDBMS, NoSQL, and machine learning database platforms.
The views expressed on this blog are those of the author and do not necessarily reflect the opinions of Enteros Inc. This blog may contain links to the content of third-party sites. By providing such links, Enteros Inc. does not adopt, guarantee, approve, or endorse the information, views, or products available on such sites.
Are you interested in writing for Enteros’ Blog? Please send us a pitch!
RELATED POSTS
How to Enable Data-Driven Media Growth with Enteros Cost Attribution and Software Management
- 22 June 2026
- Software Engineering
Introduction The media industry is experiencing one of the most significant transformations in its history. Streaming services, digital publishing platforms, online advertising ecosystems, video-on-demand applications, and content distribution networks have fundamentally changed how audiences consume content. Modern media organizations now operate highly complex digital ecosystems that support: Streaming platforms Digital publishing systems Video content delivery … Continue reading “How to Enable Data-Driven Media Growth with Enteros Cost Attribution and Software Management”
How to Enable Intelligent Wealth Management Operations with Enteros Database Software, AIOps Platform, and Gen AI
Introduction The wealth management industry is undergoing a major transformation. As investors demand personalized financial services, real-time portfolio visibility, and digital-first experiences, wealth management firms are increasingly relying on technology to drive operational efficiency, improve client engagement, and accelerate business growth. Modern wealth management organizations now support: Portfolio management platforms Wealth advisory applications Digital client … Continue reading “How to Enable Intelligent Wealth Management Operations with Enteros Database Software, AIOps Platform, and Gen AI”
The Future of Database Observability in Hybrid Cloud Environments
As enterprises accelerate digital transformation, hybrid cloud infrastructure has become the preferred operating model for many organizations. Instead of relying solely on on-premises data centers or fully public cloud deployments, businesses increasingly combine both environments to achieve greater flexibility, scalability, performance, and cost efficiency. Hybrid cloud enables organizations to distribute workloads strategically across private infrastructure … Continue reading “The Future of Database Observability in Hybrid Cloud Environments”
How AI-Powered Database Analytics Improves Digital Customer Experience
In today’s digital-first economy, customer experience has become one of the strongest differentiators for businesses. Whether customers are shopping online, using banking apps, booking travel, streaming media, or accessing SaaS platforms, they expect fast, seamless, and reliable digital interactions at every touchpoint. Modern users have little tolerance for delays. A slow-loading webpage, failed transaction, delayed … Continue reading “How AI-Powered Database Analytics Improves Digital Customer Experience”