Sub topic 1
WAL and Log Sequence Numbers: What Gets Replicated
This chapter explains what streaming replication sends from a primary server to a standby, and how to prepare the primary and clone it. It assumes you can run psql as a superuser, edit postgresql.conf and pg_hba.conf, and restart PostgreSQL. It also assumes you know what a transaction commit is.
Prerequisites
- PostgreSQL 13 or later on two Linux hosts,
primaryandstandby1, with network access between them. - A superuser role on the primary.
- An empty data directory on the standby.
Write-Ahead Log and LSNs
The write-ahead log (WAL) is an append-only sequence of records describing every change to the data files. PostgreSQL writes a WAL record before it changes a data page, so a crash can be recovered by replaying the log.
A log sequence number (LSN) is a byte position in the WAL stream, written as two hexadecimal numbers such as 0/3000060. Replication compares LSNs to measure how far a standby has fallen behind.
SELECT pg_current_wal_lsn();How Streaming Replication Works
Streaming replication moves WAL over a normal TCP connection. Two processes cooperate:
- The walsender runs on the primary. It reads WAL and sends it to each connected standby.
- The walreceiver runs on the standby. It writes incoming WAL to the standby's
pg_waldirectory.
The standby's startup process then replays those records into its data files. The standby is therefore always a byte-for-byte copy of the primary, delayed by however much WAL is in transit.
Preparing the Primary
Set these parameters in postgresql.conf on the primary:
listen_addresses = '*'
wal_level = replica
max_wal_senders = 10wal_level = replicawrites enough detail in WAL for standbys.max_wal_senderssets how many standbys can stream at once.
Allow the standby in pg_hba.conf. Replication connections use the pseudo-database name replication:
host replication replicator 10.0.0.0/24 scram-sha-256Create the role that standbys use to connect:
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'change-me';Restart PostgreSQL after changing wal_level, listen_addresses, or max_wal_senders.
Cloning the Primary with pg_basebackup
pg_basebackup copies the primary's data directory while it runs. Run this on the standby:
pg_basebackup -h primary -U replicator \
-D /var/lib/postgresql/data -X stream -R -P-X stream fetches the WAL needed to make the copy consistent. -R writes standby.signal and primary_conninfo, so the copy starts as a standby.
Exercise
Why does the replication role need the REPLICATION attribute, and what happens if pg_hba.conf does not list the pseudo-database "replication"?
Show answer
The REPLICATION attribute lets the role open a walsender connection. Without a pg_hba.conf line for the "replication" pseudo-database, the primary rejects the standby's replication connection, even if the role and password are correct.