Video in progress
A long report on a replica is cut off with "canceling statement due to conflict with recovery". Why, and what are the options?
A row version that the master removed with VACUUM may still be read by a query on the replica. To apply the WAL, the replica cancels that query after max_standby_streaming_delay. The options: increase the delay, turn on hot_standby_feedback, or use a separate replica for reports.
📖 Answer
A hot standby does two jobs: it answers queries and applies the WAL coming from the master. They collide: the WAL contains a record saying "clean up these rows", while a 20-minute query on the replica needs to see exactly those rows.
The replica has to choose: either stop applying the WAL and wait (lag grows), or cancel the query. How long it waits is set by these settings:
max_standby_streaming_delay = 30s # default; -1 = wait forever
hot_standby_feedback = off # default
The options and their cost:
hot_standby_feedback = on: the replica tells the master "I have a snapshot older than this xmin", and the master doesn't clean those versions. The conflict goes away, but a long query on the replica now creates bloat on the master. A badly written report can bloat the primary database;- raising
max_standby_streaming_delay: queries survive, but the replica falls behind. That's bad for a replica that serves user reads; - a separate replica for reports: its lag can be large without affecting anyone else. I often choose this;
- shortening the query: split it into batches, or use a pre-aggregated table.
Some conflicts aren't solved even with feedback: an ACCESS EXCLUSIVE lock on the master (for example TRUNCATE, or VACUUM trimming the end of the table) requires a lock on the replica too.
Sign up to mark studied questions and save your progress.