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.
making one
the browser has one server, so it can't stream to anyone. it is a primary, though, with nobody connected:
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;| standbybool | standbysint8 |
|---|---|
| f | 0 |
| nametext | settingtext |
|---|---|
| hot_standby | on |
| max_replication_slots | 10 |
| max_wal_senders | 10 |
| wal_level | replica |
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:
$ 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 startstandby.signal is what makes it a standby: on start it enters recovery and stays there.
- LOG: entering standby mode
- LOG: redo starts at 0/2000028
- LOG: consistent recovery state reached at 0/2000120
- LOG: database system is ready to accept read-only connections
- LOG: started streaming WAL from primary at 0/3000000 on timeline 1
an insert on the primary shows up on the standby almost at once, and the standby refuses to write:
-- 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 transactionlag
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_namename | sent_lsnpg_lsn | flush_lsnpg_lsn | replay_lsnpg_lsn | replay_behind_bytesnumeric |
|---|---|---|---|---|
| standby1 | 0/3000238 | 0/3000238 | 0/30001C8 | 112 |
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.
-- 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):
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');| slot_namename |
|---|
| standby1 |
| slot_namename | activebool | wal_statustext | holding_walbool |
|---|---|---|---|
| standby1 | f | reserved | t |
| pg_drop_replication_slotvoid |
|---|
| '' |
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:
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.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_commit | COMMIT waits until the standby has | pg_stat_replication column |
|---|---|---|
remote_write | written it (in the OS cache) | write_lsn |
on | flushed it to disk | flush_lsn |
remote_apply | replayed 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:
-- 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 1read 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.