Listener

PostgREST uses LISTEN to reload its Schema Cache and Configuration via NOTIFY. This is useful in environments where you can’t send SIGUSR1 or SIGUSR2 Unix Signals. Like on cloud managed containers or on Windows systems.

NOTIFY pgrst, 'reload schema'; -- reload schema cache
NOTIFY pgrst, 'reload config'; -- reload config
NOTIFY pgrst;                  -- reload both

By default, the LISTEN channel is enabled (db-channel-enabled) and named pgrst (db-channel).

Listener on Read Replicas

The LISTEN and NOTIFY commands do not work on PostgreSQL read replicas. Thus, if you connect PostgREST to a read replica the Listener will fail to start.

-- check if the instance is a replica
postgres=# select pg_is_in_recovery();
 pg_is_in_recovery
-------------------
 t
(1 row)

postgres=# LISTEN pgrst;
ERROR:  cannot execute LISTEN during recovery

To work around this, you can connect the Listener to the primary while still using the Connection Pool on the replica.

This can be done by using the standard libpq multiple hosts and target_session_attrs in your connection string.

db-uri = "postgres://read_replica.host,primary.host/mydb?target_session_attrs=read-only"

This will cause the Connection Pool to connect to the read replica host and LISTEN on the fallback primary host.

Note

Under the hood, PostgREST forces target_session_attrs=read-write for the LISTEN session.

Automatic Recovery

The listener will retry reconnecting to the database if connection loss happens.

  • It will retry forever with exponential backoff, with a maximum backoff time of 32 seconds between retries. Each of these attempts are logged.

  • Automatic recovery can be disabled by setting db-pool-automatic-recovery to false.

  • To ensure a valid state, the listener reloads the Schema Cache and Configuration when recovering.