Sub topic 9
Query conflicts, max_standby_streaming_delay and hot_standby_feedback
This chapter assumes you have a working primary and hot standby from the earlier chapters. You should be comfortable reading pg_stat_replication, editing postgresql.conf and reloading the server, and running two psql sessions side by side. You should also know that VACUUM removes dead row versions.
Why conflicts happen
A hot standby does two jobs at once. A single process, the startup process, replays WAL from the primary. Meanwhile, client sessions run read-only queries against the same data files.
The primary knows nothing about the queries on the standby. If the primary vacuums away a dead row version, that cleanup arrives in the WAL stream. The standby must apply it to stay identical to the primary. If a standby query still needs that row version, replay and the query conflict.
PostgreSQL has two choices. It can delay replay until the query finishes, or it can cancel the query. The settings in this chapter decide which one happens and how long replay waits.
Kinds of conflict
| Conflict | Typical cause on the primary | What the standby query loses |
|---|---|---|
| Snapshot | VACUUM or HOT pruning removes row versions the query's snapshot can still see | The query, or the transaction |
| Lock | `DROP TABLE`, `ALTER TABLE`, `LOCK`, or VACUUM truncating empty pages at the end of a table. Each takes an ACCESS EXCLUSIVE lock, and that lock is replayed on the standby. | Sessions holding conflicting locks |
| Buffer pin | Cleanup of a page that a standby query has pinned in memory | The query |
| Tablespace | A tablespace is dropped while a session uses it for temporary files | The session |
| Deadlock | The startup process is stuck behind a buffer pin held by a session that is itself blocked | The blocking session |
| Logical slot (PostgreSQL 16 and later) | Removal of rows that a logical slot on the standby still needs | The slot |
Snapshot conflicts are by far the most common. They produce this error on the standby:
ERROR: canceling statement due to conflict with recovery
DETAIL: User query might have needed to see row versions that must be removed.Sessions that are idle in a transaction can also be terminated. Then the message reads terminating connection due to conflict with recovery.
What happens during a conflict
The startup process does not cancel a query the moment a conflict appears. It waits up to a limit, and only then cancels the queries that are in its way.
While the startup process waits, it applies nothing else, so every later WAL record queues behind it. Replay lag grows, and replay_lag in pg_stat_replication on the primary shows it. The standby still receives WAL, so sent_lsn and the standby's receive position keep advancing. Only replay stalls.
max_standby_streaming_delay
max_standby_streaming_delay is the longest the startup process waits before cancelling conflicting queries, for WAL that arrived through streaming. The default is 30s.
- A positive value, such as
5min, gives queries more room before replay cancels them. 0cancels conflicting queries immediately and keeps lag minimal.-1waits forever. Replay can then stall for as long as a query runs.
The delay is not a per-query timeout. It is measured from the moment the standby received the WAL record. If replay has already been waiting behind another query, or if the standby was behind to begin with, a new query may have less time left than the full setting. Occasionally a query is cancelled seconds after it starts.
The companion setting max_standby_archive_delay has the same meaning for WAL read from an archive through restore_command. It also defaults to 30s.
You can change both with a reload, with no restart:
# postgresql.conf on a reporting standby
max_standby_streaming_delay = 15min
max_standby_archive_delay = 15minSELECT pg_reload_conf();Long delays have a cost. The standby falls behind the primary while queries run, so reads can return stale data. Failover also takes longer, because the standby must replay its backlog before it can be promoted.
hot_standby_feedback
The other approach is to stop the conflict from arising. With hot_standby_feedback = on, the standby periodically reports to the primary the oldest transaction ID its queries still need (its xmin). The primary's VACUUM then keeps the row versions that the standby might read.
# postgresql.conf on the standby
hot_standby_feedback = onReload after changing it. The standby sends feedback every wal_receiver_status_interval, which defaults to 10s. Setting that interval to 0 turns feedback off entirely.
Feedback has costs and limits:
- Bloat on the primary. A query that runs for hours on the standby holds back cleanup for the whole primary. Dead rows pile up in tables that have nothing to do with the standby query. An idle-in-transaction session on the standby does the same.
- Not a full fix. It does not prevent lock conflicts. If VACUUM on the primary truncates empty pages at the end of a table, the ACCESS EXCLUSIVE lock it takes still conflicts with standby queries on that table. You can turn truncation off per table with
ALTER TABLE big_table SET (vacuum_truncate = off);. - Gaps in feedback. Feedback only protects while the standby is connected. If the connection drops and the xmin is no longer held, the primary may vacuum rows the standby still needs. Pairing feedback with a physical replication slot keeps the xmin in place across reconnects.
- Older versions. Before PostgreSQL 16,
vacuum_defer_cleanup_ageoffered a fixed delay for cleanup. It was removed in 16. Use feedback instead.
Think of the two settings as a trade. Delay settings move the cost onto the standby, as lag. Feedback moves it onto the primary, as bloat.
Measuring conflicts
On the standby, pg_stat_database_conflicts counts queries cancelled by each type. It only shows cancellations on the standby, and the primary's view is empty.
SELECT datname,
confl_tablespace,
confl_lock,
confl_snapshot,
confl_bufferpin,
confl_deadlock
FROM pg_stat_database_conflicts
WHERE datname = current_database();If confl_snapshot is climbing, you need a longer delay or feedback. If confl_lock climbs, look for DDL or VACUUM truncation on the primary. The standby's server log also records each cancellation. Setting log_recovery_conflict_waits = on (PostgreSQL 14 and later) logs when replay has waited longer than deadlock_timeout for a conflict.
To see what is holding replay back, run this on the standby:
SELECT pid, state, xact_start, backend_xmin, left(query, 60) AS query
FROM pg_stat_activity
WHERE backend_type = 'client backend'
ORDER BY xact_start;The oldest xact_start or backend_xmin is usually the culprit.
Choosing a strategy
Match the setting to what the standby is for.
| Standby purpose | Suggested settings |
|---|---|
| Failover target with occasional reads | Defaults, or `max_standby_streaming_delay = 30s` |
| Short web-application reads | `hot_standby_feedback = on`, default delay |
| Long reports and analytics | A dedicated standby with `max_standby_streaming_delay = -1` or several minutes, and no promotion role |
| Both failover and long reports | Separate standbys. A failover standby should not carry long queries. |
Do not put -1 on the standby you rely on for failover. A single forgotten query can freeze replay indefinitely.
You can also reduce conflicts without any setting. Keep long queries off the standby, shorten them with indexes, and avoid long idle-in-transaction sessions. On the primary, avoid frequent DDL on hot tables.
Common errors
- Setting feedback on, then seeing the same cancellations. The cause is probably lock conflicts or a dropped connection. Check
confl_lockagainstconfl_snapshot. - Raising the delay and seeing huge lag. That is the expected result. Check
replay_lagandpg_last_xact_replay_timestamp(). - Primary tables growing unexpectedly. Look for a long-running or idle-in-transaction session on a standby with feedback enabled. Compare the
backend_xminvalues in the query above. - Cancellations right after a long delay. The delay clock started when the WAL arrived, not when your query began.
Exercise
A reporting standby has maxstandbystreamingdelay = 30s and hotstandbyfeedback = off. Analysts report that queries running longer than about a minute fail with "canceling statement due to conflict with recovery", and pgstatdatabaseconflicts shows confl_snapshot rising. Describe two ways to fix this and the cost of each.
Show answer
Option 1: raise maxstandbystreamingdelay on the standby (for example to 15min, or -1 for a dedicated reporting standby). The cost is replay lag: the standby falls behind the primary while queries run, reads become staler, and failover to that standby takes longer. Option 2: set hotstandby_feedback = on, so the primary's VACUUM keeps the rows the standby queries need. The cost is table bloat on the primary while long queries run, and it does not remove lock conflicts such as VACUUM truncation. Using a physical replication slot as well keeps the protection across reconnects.
Exercise
Why does a query sometimes get cancelled only a few seconds after it starts, even though maxstandbystreaming_delay is 5min?
Show answer
The delay is measured from when the standby received the conflicting WAL record, not from when the query began. If replay was already waiting behind earlier queries, or the standby was already behind, most of the allowed time has passed before the new query starts.