PostgreSQL Read Replicas and Replication Lag: Read Routing, Read-Your-Writes and WAIT FOR
A practical guide to serving reads from replicas without handing anyone the past: how a change actually travels from primary to replica and what each of the four clocks in pg_stat_replication measures (sent, write, flush and replay), why the seconds-based lag metric almost everyone ships first lies on an idle primary and the query that fixes it, Prometheus alerts built on your own postgres_exporter queries instead of metric names that change between versions, the five real causes of lag —single-process replay, replicas with fewer IOPS than the primary, recovery conflicts and the max_standby_streaming_delay that cancels your queries after 30 seconds, huge transactions, and a forgotten recovery_min_apply_delay—, the five levels of synchronous_commit and what each one costs, quorum commit with ANY and FIRST plus the two traps that cause real incidents (remote_apply with ANY 1 does not make every replica current, and an unsatisfiable quorum stops COMMITs with no timeout), the hot_standby_feedback trade-off between query cancellations on the replica and bloat on the primary, and read routing in the application —never by SQL text— with two pools, background health probing and lag-based eviction. It covers all four read-your-writes strategies: primary pinning with a TTL, LSN tokens with the new WAIT FOR command in PostgreSQL 19 and its four modes, the client-side polling fallback for PostgreSQL 18 and earlier (including the exact reason pg_wal_replay_wait was reverted before release), and lag-aware routing per read class. Includes the format validation that prevents SQL injection in a command that takes no bind parameters, the token max() without which concurrent requests move it backwards, why comparing LSNs as strings gives wrong answers, slots that fill pg_wal with max_slot_wal_keep_size and PostgreSQL 18 idle_replication_slot_timeout, what breaks on promotion and PostgreSQL 17 failover slot synchronisation, a complete write/read endpoint pair, eight recurring mistakes, a twelve-point production checklist and an FAQ. With production-ready SQL, Python, TypeScript, YAML and configuration.
Verificando acceso...