Full answer
Diagnose:
- Lag: on the primary,
pg_stat_replicationshows sent, written, flushed and replayed positions; on the replica,now() - pg_last_xact_replay_timestamp()approximates time lag. - Replay conflicts: queries on the replica can block replay when
max_standby_streaming_delayallows waiting; check for long reporting queries. - Resources: replay is single-threaded for much of the work in PostgreSQL, so a replica with slow disks falls behind under heavy writes.
- Write bursts: a large batch job or index build on the primary generates WAL faster than replay.
Actions:
- Throttle or batch bulk jobs on the primary.
- Move long analytics off the replica or allow them to be cancelled.
- Give the replica comparable disk performance.
- Route lag-sensitive reads to the primary while the replica catches up.
Alert on replication lag so it is noticed in minutes, not hours. Described here, not run.
Key points
- Write bursts outpace replay
- Replica queries can delay replay
- Replay needs fast disks
- Measure lag at both ends
- Route sensitive reads to the primary meanwhile
Common mistakes
- Ignoring lag until users report stale data
- Running heavy reports on a replica configured to wait for them
Follow-ups
- What does hot_standby_feedback trade off?
- How would you detect lag from the application?
Tips
- List causes on both sides