Source: https://gres.monicz.dev/guide/notifications/

# LISTEN and NOTIFY

`listen()` on a `Connection` or `Pool` subscribes to one or more PostgreSQL channels and yields immutable [`Notification`](https://gres.monicz.dev/api/queries/#gres.Notification) values.

```python
import asyncio
from gres import Notification, Pool


async def main() -> None:
    async with Pool() as pool:
        async with pool.listen('jobs') as events:
            await pool.execute("SELECT pg_notify('jobs', '42')")
            match await anext(events):
                case Notification(channel='jobs', payload=job):
                    print('job', job)  # job 42


asyncio.run(main())
```

## Receive notifications

`async with pool.listen('jobs') as events` reserves a dedicated session until exit and waits for `LISTEN` to commit before yielding, so notifications committed after entry are delivered. Each `Notification` carries `channel`, `payload`, and the sending backend `pid`, supports pattern matching, and is picklable.

- Publish notifications with ordinary SQL: `await tx.execute('SELECT pg_notify($1, $2)', ('jobs', job_id))` (delivered when the sending transaction commits).
- Listening requires `pool_mode='session'` (not [transaction pooling](https://gres.monicz.dev/guide/pools/#pgbouncer-transaction-pooling)).
- `buffer_bytes` (default 1 MiB) bounds unread buffered notifications; overflow raises `NotificationOverflowError`.
- `timeout` (default `None`) limits total subscription lifetime and does not inherit `operation_timeout` (which bounds only initial registration).

## Keep a worker consistent

Because PostgreSQL drops notifications sent while no session is listening, subscribe first and then drain pending database state. Socket loss or `NotificationOverflowError` closes the listener session without reconnecting; catch both, re-subscribe, and re-scan:

```python
# Partial: pool is an open gres.Pool; process_pending reads and claims
# pending jobs.
import asyncio
from gres import errors


async def worker() -> None:
    while True:
        try:
            async with pool.listen('jobs') as events:
                # Catch up on work committed before subscribing.
                await process_pending(pool)
                async for _ in events:
                    await process_pending(pool)
        except (errors.ConnectionError, errors.NotificationOverflowError):
            await asyncio.sleep(1)
```

Server diagnostics (`RAISE NOTICE`, etc.) go to the [`gres.notice` logger](https://gres.monicz.dev/guide/observability/#log-server-notices), not `listen()`.
