AI Hints
Home›PostgreSQL Tutorial›NOTIFY, Extensions and pgvector
PostgreSQL · Lesson 97 of 120

LISTEN and NOTIFY

Messages from the database.

⏱ 2 min read▶ Video at 1:27:31🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

When a new order arrives, the warehouse screen should update right away, without asking the database every second. Postgres can send messages to listening apps, with listen and notify.

  • New order
  • Tell the warehouse
  • No polling

A simple message

Bob listens on the orders channel. Alice sends a notify with a small payload, and commits. Bob receives it right away. Run it. Bob gets the message about the new order.

listen.pypython
import psycopg

URL = "postgresql://postgres:postgres@localhost:5432/riverside"
alice = psycopg.connect(URL)   # first session
bob = psycopg.connect(URL)     # second session
bob.autocommit = True
bob.execute("LISTEN new_orders")

alice.execute("SELECT pg_notify('new_orders', 'order 1599 placed')")
alice.commit()

for note in bob.notifies(timeout=2, stop_after=1):
    print("Bob got:", note.channel, "->", note.payload)
Output
Bob got: new_orders -> order 1599 placed

When to use it

Use notify for small signals, like something changed, go look. Messages are sent only when the transaction commits. Listeners must be connected to receive them. For durable queues, use a jobs table instead.

keyvalue
Payloadsmall signals
On commitonly
Offline?messages lost
Durablejobs table

Summary

Listen and notify send instant messages from the database to connected apps. Next, extensions.

Key takeaways
  • LISTEN
  • NOTIFY
  • Instant
Next up: Extensions — add-on powers