Streaming Replication and Failover

Topics Covered

How Streaming Replication Works

WAL is the replication stream

Creating a standby

The walsender and walreceiver

LSNs and positions

Measuring lag

Replication slots

The danger of abandoned slots

WAL archiving as a second path

Cascading replication

Network and bandwidth

What is not replicated

Replication connections and security

wal_level and what it enables

Replay is single threaded

Starting a standby quickly

Replication and checkpoints

Logical versus physical

Physical replication keeps standby servers as byte for byte copies of the primary by shipping and replaying its write ahead log. It is the foundation for high availability, read scaling and many backup setups. This section explains how a standby is created, how WAL flows from the primary to standbys, what replication slots do and how to measure how far behind a standby is.

WAL is the replication stream

Every change to data pages on the primary is first described in the write ahead log. A standby that replays the same WAL records in the same order arrives at the same physical state. Physical replication therefore copies the entire cluster, all databases, tables, indexes and catalogs, and the standby must run the same major version on the same architecture. It cannot replicate a subset of tables, which is what logical replication is for.

Creating a standby

A standby starts from a base backup of the primary, usually taken with pg_basebackup, which copies the data directory while the primary keeps running and records the WAL position where the copy began. The standby is configured with primary_conninfo pointing to the primary and a standby.signal file in its data directory. On start, it replays WAL from the backup start position until it is consistent, then continues streaming new WAL as it arrives.

The walsender and walreceiver

On the primary, each connected standby is served by a walsender process, which reads WAL from disk or memory and sends it over a replication connection. On the standby, a walreceiver process receives the stream, writes it to the local pg_wal directory and flushes it, and the startup process replays it into data pages. The walreceiver reports back the positions it has written, flushed and replayed, which the primary shows in pg_stat_replication.

The standby receives, flushes and replays the same WAL the primary wrote, and reports each position back.

LSNs and positions

WAL positions are log sequence numbers, LSNs, written as two hexadecimal numbers separated by a slash, which increase monotonically as WAL is written. pg_current_wal_lsn on the primary gives the current write position, and on the standby pg_last_wal_receive_lsn and pg_last_wal_replay_lsn give received and replayed positions. pg_wal_lsn_diff subtracts two LSNs to give a byte distance, the most precise measure of how far a standby is behind.

Measuring lag

pg_stat_replication on the primary shows, for each standby, sent_lsn, write_lsn, flush_lsn and replay_lsn, and the time based columns write_lag, flush_lag and replay_lag, which estimate how long recent WAL took to reach each stage. Byte lag shows how much work is queued; time lag shows how stale reads on the standby are. On the standby, now minus pg_last_xact_replay_timestamp gives time since the last replayed transaction, which overstates lag when the primary is idle.

Replication slots

Without a slot, the primary removes old WAL after checkpoints according to its own needs and wal_keep_size. A standby that falls too far behind may find the WAL it needs gone and must be rebuilt from a new base backup. A physical replication slot makes the primary retain WAL until the standby using the slot has received it, so a disconnected standby can always catch up. Slots also carry the standby xmin when hot_standby_feedback is on.

Slots guarantee catch up by retaining WAL, but an abandoned slot can fill the disk unless max_slot_wal_keep_size caps it.

The danger of abandoned slots

A slot whose standby is gone for good keeps retaining WAL forever, and the primary disk fills until the database stops accepting writes. Since version 13, max_slot_wal_keep_size caps how much WAL a slot can retain; beyond it, the slot is invalidated and the standby must be rebuilt, but the primary survives. pg_replication_slots shows each slot with active, restart_lsn and wal_status, and monitoring inactive slots and retained WAL is essential.

WAL archiving as a second path

Besides streaming, standbys can fetch WAL from an archive with restore_command, the same archive used for point in time recovery. If streaming falls behind or breaks, the standby replays from the archive and then resumes streaming. Combining an archive with streaming makes standbys resilient without requiring slots to retain unlimited WAL, since the archive holds everything needed to catch up.

Cascading replication

A standby can itself serve as an upstream for other standbys, forming a tree. Cascading reduces load on the primary when there are many replicas, and lets a remote region have one standby that streams across the long link and feeds local replicas. The cost is additional lag for downstream standbys and the need to repoint them if the intermediate standby fails or is promoted.

Network and bandwidth

The replication stream carries every byte of WAL, so the network must sustain the peak WAL rate of the primary. Bulk loads, index builds and full page writes after checkpoints cause bursts. wal_compression, available with lz4 and zstd since version 15, reduces the size of full page images. Cross region replicas need enough bandwidth for peaks, or lag grows during heavy writes and recovers only afterwards.

What is not replicated

Physical replication copies everything in the data files, but not server configuration in postgresql.conf, pg_hba.conf, or files outside the data directory. Unlogged tables are not replicated: they appear empty on standbys. Temporary tables, which are session local, are not replicated either. Configuration must be managed separately on each server, usually with configuration management, so a promoted standby has the right settings.

Replication connections and security

Standbys connect with a role that has the REPLICATION attribute, authorized by a pg_hba.conf line for the replication pseudo database. The connection should use TLS and SCRAM, especially across zones or regions, since the stream carries every change in the database. max_wal_senders limits the number of concurrent replication connections, including those used by pg_basebackup, so it must leave room for backups while all standbys are connected.

wal_level and what it enables

wal_level must be replica or higher for streaming replication, which is the default; logical adds information needed for logical decoding. minimal produces the least WAL by skipping logging for some bulk operations, but makes replication and point in time recovery impossible. Changing wal_level requires a restart, so production clusters usually set it to logical from the start if there is any chance of needing logical replication later.

Replay is single threaded

The startup process applies WAL records one at a time, so a standby replays with one CPU, while the primary generates WAL from many concurrent sessions. A primary that writes heavily can outpace replay, especially when replay must read pages from disk that are not in the standby cache. Version 15 added recovery_prefetch, which reads ahead in the WAL and prefetches the blocks that upcoming records will touch, reducing replay stalls on I/O bound standbys.

Starting a standby quickly

A large base backup can take hours, during which the primary keeps generating WAL that the standby must later replay. Using a slot during the backup, taking the backup from an existing standby rather than the primary, and using storage snapshots or incremental backups, available natively since version 17, all shorten the time to a working standby. Practicing the rebuild procedure gives a realistic estimate for how long the cluster runs with reduced redundancy after a standby is lost.

Replication and checkpoints

On a standby, restartpoints play the role of checkpoints: they flush replayed pages to disk so that a restarted standby does not have to replay from the beginning. Restartpoints can only happen at checkpoint records received from the primary, so standby restart time depends on the primary checkpoint frequency. Settings such as checkpoint_timeout affect both, and very long checkpoint intervals make standby restarts slower.

Logical versus physical

Physical replication copies the cluster exactly and is the basis of failover, but requires the same major version and copies everything. Logical replication, covered in the next lesson, sends row changes for chosen tables, works across major versions and allows the subscriber to have its own writes and indexes. Most production setups use physical replication for high availability and logical replication for upgrades, integration and selective copies.

WAL in, WAL replayed

A standby starts from a base backup and replays the primary WAL stream. Measure lag in bytes with LSN differences and in time with replay_lag. Use slots to guarantee catch up but cap them with max_slot_wal_keep_size, keep an archive as a second path and remember that configuration is not replicated.