Sub topic 6
Running read-only queries on the standby
This chapter assumes you have a working standby from the earlier chapters: a primary with a replication role, a base backup, standby.signal, and primary_conninfo. You should be comfortable with psql and with the idea of a read-only transaction.
What "hot" means
A standby that replays WAL but refuses client connections is a warm standby. A hot standby also accepts connections and answers queries while it replays. The setting that enables this is hot_standby. It defaults to on in current releases, so you usually get it without editing anything.
The standby serves queries from a consistent snapshot of the data. Replay continues in the background, and each query sees the database as of the last WAL position it was able to apply. Two consequences follow:
- Results are never newer than the primary, and are usually slightly older.
- Replay and queries compete for the same data pages. Chapter "Query conflicts" covers that. Here we only look at what you can run and what you will see.
Confirming you are on a standby
Connect to the standby and ask it directly.
SELECT pg_is_in_recovery() AS in_recovery,
current_setting('transaction_read_only') AS read_only,
pg_last_wal_replay_lsn() AS replay_lsn,
now() - pg_last_xact_replay_timestamp() AS apparent_delay;pg_is_in_recovery() returns true on a standby and false on a primary. Applications and scripts can use it as a safe check before sending writes.
apparent_delay is a rough staleness figure. It is the time since the last replayed commit. If the primary is idle, this value keeps growing even though nothing is wrong. The monitoring chapter covers better lag measurements.
When connections are accepted
A starting standby refuses connections until it reaches a consistent state, meaning replay has passed the point where the base backup became consistent. Until then, clients see an error like this:
FATAL: the database system is not yet accepting connections
DETAIL: Consistent recovery state has not been reached.This is normal on a fresh standby, or after a standby has been down for a long time and must replay a lot of WAL. If it never clears, check the standby log for replay errors or a failing connection to the primary.
What you can run
A standby is read-only from the client's point of view. Anything that would write WAL, or change the data, is rejected. Table 1 summarizes the common cases.
| Category | Allowed on a hot standby | Rejected |
|---|---|---|
| Queries | `SELECT`, `COPY ... TO`, `EXPLAIN` | `SELECT ... FOR UPDATE` and `FOR SHARE` |
| Data changes | None | `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `TRUNCATE`, `COPY ... FROM` |
| Schema changes | None | `CREATE`, `ALTER`, `DROP`, including temporary tables |
| Cursors and prepared statements | `DECLARE`, `FETCH`, `PREPARE`, `EXECUTE` | `PREPARE TRANSACTION` |
| Session settings | `SET`, `RESET`, `SHOW` | None |
| Transactions | `BEGIN`, `COMMIT`, `ROLLBACK`, savepoints | `SERIALIZABLE` isolation |
| Sequences | `SELECT last_value FROM seq` | `nextval()`, `setval()` |
| Notifications | `UNLISTEN` | `LISTEN`, `NOTIFY` |
Here is what a rejected write looks like:
INSERT INTO orders (customer_id, total) VALUES (42, 19.90);
-- ERROR: cannot execute INSERT in a read-only transaction
CREATE TEMP TABLE scratch (id int);
-- ERROR: cannot execute CREATE TABLE in a read-only transactionThe temporary table case catches many people. Reporting jobs that stage intermediate results in temp tables must use CTEs, subqueries, or a different design on the standby. Alternatively, they must run on the primary.
The standby also does not run autovacuum or any other write-producing maintenance. Vacuuming happens on the primary, and its effects arrive as WAL.
Because SERIALIZABLE is rejected, a session on the standby must use READ COMMITTED or REPEATABLE READ. A long REPEATABLE READ transaction gives you a stable snapshot for a report, but it also holds that snapshot open against replay.
Settings that must match the primary
The standby is a physical copy, so a few capacity parameters must be at least as large on the standby as on the primary. These are max_connections, max_worker_processes, max_wal_senders, max_prepared_transactions, and max_locks_per_transaction. If a standby value is lower, replay pauses when it reaches a WAL record that records the larger primary value. The standby stops accepting the replay until you raise the setting and restart.
This often shows up after someone raises max_connections on the primary and forgets the standbys. Change the standbys first, then the primary.
Things that are not replicated
Streaming replication copies the contents of the database cluster, not the files outside it.
- Roles, grants, tables, indexes, and extensions' catalog entries arrive through WAL. A role created on the primary can log in to the standby after replay reaches it.
pg_hba.confandpostgresql.confare not replicated.pg_basebackupcopies them once. After that, each server has its own. If clients connect to the standby, itspg_hba.confmust allow them.- Per-session settings such as
work_memcan be set on the standby for the session. Server-wide settings such asshared_buffersandmax_standby_streaming_delayare independent. You can tune the standby for reporting without touching the primary.
Freshness and read-your-writes
Asynchronous replication means a client can commit on the primary and then read an older version from a standby. For example:
- The application commits an order on the primary.
- It immediately redirects the user to an "order status" page that reads from a standby.
- Replay has not yet applied the commit, so the page shows no order.
You have three main options:
- Read the data that a user has just written from the primary, and use standbys for everything else.
- Make the commit wait for standby replay with
synchronous_commit = remote_apply, together withsynchronous_standby_names. This costs commit latency. - Record the primary's
pg_current_wal_lsn()after the write and wait on the standby untilpg_last_wal_replay_lsn()reaches it. This is more work in application code.
For a stable view during a long analytic query, you can pause replay on the standby and resume it afterward:
SELECT pg_wal_replay_pause();
-- run your report queries here
SELECT pg_wal_replay_resume();While replay is paused, WAL keeps arriving and accumulates on the standby, and the standby falls further behind. Always resume. A paused standby that is promoted or monitored for lag gives misleading results.
Routing clients to standbys
Standbys are useful only if the application sends reads to them. A simple approach uses libpq's multiple-host connection strings (PostgreSQL 14 and later for standby and prefer-standby):
psql "postgresql://standby1.example.com,primary.example.com/appdb?target_session_attrs=prefer-standby" \
-c "SELECT pg_is_in_recovery();"prefer-standby connects to a standby if one is available and falls back to the primary otherwise. standby fails if no standby is reachable. read-write is the usual value for write connections, because it skips standbys.
Do not add the empty block above. Use the diagram below instead.
Common errors
cannot execute ... in a read-only transaction: the client is connected to a standby. Check the connection string andpg_is_in_recovery().cannot use serializable mode in a hot standby: set the isolation level toREPEATABLE READor lower for that session.terminating connection due to conflict with recoveryorcanceling statement due to conflict with recovery: replay needed to remove data that your query still needed. This is a query conflict, covered in a later chapter.- Stale reads: the standby is behind. Measure lag before blaming the application.
Exercise
A reporting job on a standby creates a temporary table to hold intermediate results and fails with "cannot execute CREATE TABLE in a read-only transaction". It also runs under SERIALIZABLE isolation. Name two changes that let the job run on the standby, and say how you would confirm that the session is on a standby.
Show answer
First, rewrite the intermediate results as CTEs or subqueries instead of a temporary table, since a standby accepts no CREATE statements, including temporary ones. Second, change the transaction isolation to REPEATABLE READ (or READ COMMITTED), because SERIALIZABLE is not available on a hot standby. To confirm that the session is on a standby, run SELECT pgisinrecovery(); it returns true on a standby. SHOW transactionread_only also returns on.
Exercise
Immediately after a user places an order, your application reads it from an asynchronous standby and sometimes finds nothing. Give two ways to fix this and one cost of each.
Show answer
Option one is to read freshly written data from the primary. The cost is more load on the primary. Option two is to use synchronouscommit = remoteapply with synchronousstandbynames so a commit waits until the standby has replayed it. The cost is higher commit latency, and commits stall if the named standby is unavailable. A third option is to wait on the standby until pglastwalreplaylsn() reaches the LSN recorded after the write, which costs extra application logic.