Real life use case of Postgres' LISTEN/NOTIFY

A Postgres noob asked me: what's the real time (sic) use of LISTEN and NOTIFY? And here's how the conversation went:

noob:  what's the real time use of LISTEN and NOTIFY?
in postgresql
me:  Well, that is a very useful facility.
Say you have two applications, one inserts some data and the other reads and acts on that data..
In a normal setup you would have the reading application querying the DB every few seconds to see if new data has come in..
This incurs overhead on the dataabase.
In Postgres you can use LISTEN/NOTIFY to achieve the same thing without having to 'poll' the database every few seconds.
The reading application can register its interest in new data by saying 'LISTEN newdata'
And the writing application, whenever it inserts new data, can send  anotification, saying 'NOTIFY newdata'
At this point, Postgres will send a message to the reading application that 'newdata' has arrived, and now the reading application query the database to process newly inserted data.
I hope that explains it.

noob:  thank you Gurjeet, that's really good
Happy Weekend

1 comment:

  1. Also, see Ryan Smith from Heroku's Queue Classic:

    It uses listen/notify to inform workers when a job is ready without polling.