skip to content

streaming replication

a standby replaying WAL as it arrives. lag, hot standby conflicts, and synchronous replicas.

address
everything.wal.streaming_replication
part
part 16, WAL and recovery
chapter
chapter 10 of 11
reading time
8 min

a standby is a server stuck in recovery on purpose. the primary's walsender streams WAL to the standby's walreceiver as it's written, and the standby replays it, the same redo as after a crash, forever. it can serve reads meanwhile (hot standby). pg_stat_replication shows how far it has written, flushed and replayed. a replication slot makes the primary keep WAL until the standby has it, and synchronous_standby_names makes COMMIT wait for the standby too.

the picture

you know how crash recovery replays WAL until it runs out, then opens for business? a standby is the same thing, except it never runs out: whenever it reaches the end of the WAL, more arrives over the network.

think of a court stenographer's transcript (the WAL) being faxed, page by page, to a second courtroom that acts out every line as it arrives (replay). people can sit in the second courtroom and watch (read-only queries). they can't speak (no writes). and the second courtroom is always a little behind, by however long the fax and the acting take (lag).

hover a stage.

one change, from a primary backend to a read on the standby. hover a stage. write, flush and replay are the three positions the primary can see.

making one

the browser has one server, so it can't stream to anyone. it is a primary, though, with nobody connected:

sqldb=lab
SELECT pg_is_in_recovery() AS standby, (SELECT count(*) FROM pg_stat_replication) AS standbys;
SELECT name, setting FROM pg_settings
WHERE name IN ('wal_level', 'max_wal_senders', 'max_replication_slots', 'hot_standby')
ORDER BY name;
output, from postgres 18.6
#1 · SELECT 1
standbyboolstandbysint8
f0
(1 row)
#2 · SELECT 4
nametextsettingtext
hot_standbyon
max_replication_slots10
max_wal_senders10
wal_levelreplica
(4 rows)

wal_level = replica (the default) is enough for streaming. everything else is a throwaway primary and standby on this mac. pg_basebackup -R copies the primary and writes the standby's config; -C -S standby1 creates a replication slot for it on the primary:

terminal
$ pg_basebackup -h /tmp/w17prim2 -D $STANDBY -R -C -S standby1 --checkpoint=fast
$ cat $STANDBY/postgresql.auto.conf
primary_conninfo = 'user=postgres … host=''/tmp/w17prim2'' port=5495 …'
primary_slot_name = 'standby1'
$ ls $STANDBY/standby.signal
$STANDBY/standby.signal
$ pg_ctl -D $STANDBY start
recorded: pg_basebackup 18.6 and the shell on this mac; the connection string is cut where it lists libpq defaults

standby.signal is what makes it a standby: on start it enters recovery and stays there.

standby log
  1. LOG: entering standby mode
  2. LOG: redo starts at 0/2000028
  3. LOG: consistent recovery state reached at 0/2000120
  4. LOG: database system is ready to accept read-only connections
  5. LOG: started streaming WAL from primary at 0/3000000 on timeline 1
recorded: the standby's server log, same run, lines about the base backup left out
the standby's log as it starts: crash-recovery-style replay from the backup's redo pointer, then "ready to accept read-only connections", then streaming. it never says "redo done".

an insert on the primary shows up on the standby almost at once, and the standby refuses to write:

psql
-- on the standby
SELECT pg_is_in_recovery();
 pg_is_in_recovery
-------------------
 t
(1 row)
 
SELECT id, owner, balance FROM accounts ORDER BY id;
 id | owner | balance
----+-------+---------
  1 | alice |  100.00
  2 | bob   |  100.00
  3 | carol |   50.00
(3 rows)
 
INSERT INTO accounts VALUES (4, 'dave', 10.00);
ERROR:  cannot execute INSERT in a read-only transaction
recorded: psql 18.6 on the standby, same run (the -- line is mine)

lag

replication is asynchronous by default: the primary commits, returns, and the WAL reaches the standby a moment later. to make the moment visible, this run paused replay on the standby (pg_wal_replay_pause()), then took 25.00 from alice on the primary:

application_namenamesent_lsnpg_lsnflush_lsnpg_lsnreplay_lsnpg_lsnreplay_behind_bytesnumeric
standby10/30002380/30002380/30001C8112
(1 row)
recorded: psql 18.6 on the primary, same run
pg_stat_replication on the primary while the standby's replay is paused. the WAL has arrived and been flushed there; it just hasn't been applied.

sent_lsn and flush_lsn are equal: the standby has the update on disk. replay_lsn is 112 bytes behind, and a query on the standby still says alice has 100.00. after pg_wal_replay_resume(), it says 75.00. on a live system the three positions are usually within milliseconds of each other, and write_lag, flush_lag and replay_lag in the same view give it in time instead of bytes. a read sent to a standby right after a write on the primary can come back stale: read replicas is about living with that.

predict the output
the standby crashes and stays down for a day. the primary has a replication slot for it. what happens on the primary?
sql
-- primary: slot standby1, standby offline since yesterday
SELECT slot_name, active, restart_lsn FROM pg_replication_slots;

a slot is just a row in pg_replication_slots with a restart_lsn. one created with immediately_reserve = true starts holding WAL right away, before any standby has connected (a native block: it's cluster-wide state, so it drops the slot again at the end):

sqldb=lab
SELECT slot_name FROM pg_create_physical_replication_slot('standby1', true);
UPDATE notes SET body = 'x' WHERE id <= 200;
SELECT slot_name, active, wal_status,
       pg_wal_lsn_diff(pg_current_wal_insert_lsn(), restart_lsn) > 0 AS holding_wal
FROM pg_replication_slots;
SELECT pg_drop_replication_slot('standby1');
output, from a real postgres 18.6 server
#1 · SELECT 1
slot_namename
standby1
(1 row)
#2 · UPDATE 200
#3 · SELECT 1
slot_namenameactiveboolwal_statustextholding_walbool
standby1freservedt
(1 row)
#4 · SELECT 1
pg_drop_replication_slotvoid
''
(1 row)

checked on a real postgres 18.6 server. the browser engine can't run this one.

hot standby conflicts

a standby's queries see an old snapshot, but replay keeps applying the primary's changes, including VACUUM removing row versions that snapshot might still need. replay can wait for the query (up to max_standby_streaming_delay, 30 s by default; this run set 2 s) or cancel it. this standby session opened a repeatable read transaction and slept while the primary deleted a row and vacuumed:

psql
BEGIN ISOLATION LEVEL REPEATABLE READ;
BEGIN
SELECT count(*) FROM accounts;
 count
-------
     3
(1 row)
 
SELECT pg_sleep(6);
ERROR:  canceling statement due to conflict with recovery
DETAIL:  User query might have needed to see row versions that must be removed.
recorded: psql 18.6 on the standby, max_standby_streaming_delay = 2s, while the primary ran DELETE and VACUUM

the knobs pull in opposite directions: a longer delay lets standby queries finish but lets replay fall behind; hot_standby_feedback = on tells the primary which rows the standby still needs, so VACUUM on the primary leaves them, which avoids the cancel and brings bloat to the primary instead.

synchronous replicas

with synchronous_standby_names naming a standby, COMMIT waits for it too, at the level synchronous_commit asks for (what COMMIT waits for):

synchronous_commitCOMMIT waits until the standby haspg_stat_replication column
remote_writewritten it (in the OS cache)write_lsn
onflushed it to diskflush_lsn
remote_applyreplayed it (visible to its queries)replay_lsn

the catch is what happens when the synchronous standby goes away. this run made standby1 synchronous, stopped it, and inserted a row on the primary. the INSERT didn't return. a second session found it waiting, and cancelled it:

psql
-- another session, 3 s later
SELECT wait_event_type, wait_event, state, query FROM pg_stat_activity WHERE wait_event = 'SyncRep';
 wait_event_type | wait_event | state  |                      query
-----------------+------------+--------+--------------------------------------------------
 IPC             | SyncRep    | active | INSERT INTO accounts VALUES (6, 'frank', 30.00);
(1 row)
 
SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE wait_event = 'SyncRep';
 pg_cancel_backend
-------------------
 t
(1 row)
 
-- the waiting session
INSERT INTO accounts VALUES (6, 'frank', 30.00);
WARNING:  canceling wait for synchronous replication due to user request
DETAIL:  The transaction has already committed locally, but might not have been replicated to the standby.
INSERT 0 1
recorded: psql 18.6 on the primary, two sessions, same run (the -- lines are mine)

read that DETAIL twice. the row is committed on the primary and visible; it just isn't guaranteed on the standby. synchronous replication doesn't mean "never committed unless replicated": it means "COMMIT doesn't return until replicated". listing two standbys (FIRST 1 (a, b) or ANY 1 (a, b)) keeps one dead standby from stopping all writes.

keylines

  • a standby is recovery that never ends: walsender streams WAL, walreceiver writes it, startup replays it.
  • pg_stat_replication: sent, write, flush, replay. the gaps between them are lag.
  • a replication slot keeps WAL until the standby has it. an abandoned slot fills pg_wal.
  • standby queries can be cancelled by replay ("conflict with recovery").
  • synchronous replication makes COMMIT wait for the standby. a dead sync standby blocks commits.
  • a replica copies mistakes too. it isn't a backup.