Sub topic 2
How streaming replication works: walsender, walreceiver and recovery
This chapter explains the moving parts of physical streaming replication. It assumes you know the basics of PostgreSQL administration, can use psql, and understand what a transaction and a commit are. You also need the idea of the write-ahead log (WAL) and log sequence numbers (LSNs) from the previous chapter. No configuration happens here. The next chapters build a working pair of servers. This chapter gives you the model you need to understand what those steps do and why they fail when they do.
The core idea
A PostgreSQL primary already writes every change to the WAL before it changes data files. WAL is a sequence of records that describe changes to data pages. Crash recovery replays these records after a crash to bring the data files back to a consistent state.
Physical streaming replication reuses that mechanism. A standby is a server that stays in recovery. Instead of reading WAL from its own local crash, it reads WAL that the primary produces and replays it continuously. The standby never generates its own WAL records for user data. It only applies the records it receives.
This has a consequence that shapes everything else: the standby is a byte-for-byte copy at the level of data pages. Replication ships page-level changes, not SQL statements and not row changes. For that reason:
- The standby must run the same major version of PostgreSQL as the primary.
- The standby must have the same CPU architecture and compatible binary layout.
- The whole cluster is replicated. You cannot pick individual tables or databases.
- The standby cannot accept writes, because it would diverge from the primary's pages.
The processes involved
Three kinds of processes cooperate. Two of them handle the network connection. One does the replay.
| Process | Runs on | Job |
|---|---|---|
| walsender | Primary | Reads WAL and sends it over a replication connection. One per connected standby. |
| walreceiver | Standby | Connects to the primary, receives WAL, writes it to local WAL files and reports progress. |
| startup process | Standby | Reads the local WAL and replays it into the data files. |
The walsender is started by the postmaster when a client connects with replication enabled. This is why max_wal_senders limits the number of simultaneous standbys and backup clients. A pg_basebackup run also uses a walsender.
The walreceiver and the startup process are separate on purpose. Receiving and replaying run at independent speeds. A standby can receive WAL quickly and still be behind in replay if replay is slow, for example because the replaying process is waiting on a conflicting query. You will see this difference again in the monitoring chapter, where it appears as separate received and replayed positions.
What happens when a standby starts
When you start a server that has a standby.signal file in its data directory, it enters standby mode instead of finishing recovery and opening for writes. The sequence looks like this:
- The startup process begins recovery from the last checkpoint recorded in the data directory. It replays any WAL it finds locally in
pg_wal. - When it runs out of local WAL, it asks for more. If
primary_conninfois set, it starts a walreceiver. - The walreceiver connects to the primary using that connection string. It sends the LSN where it wants streaming to begin, which is the point right after the WAL it already has.
- On the primary, a walsender starts and begins sending WAL from that LSN.
- The walreceiver writes the incoming WAL into the standby's
pg_waland tells the startup process more WAL is available. - The startup process replays records as they arrive.
Once the standby reaches a consistent state, meaning it has replayed enough WAL that the data files are valid, it can accept read-only connections if hot_standby is on. Until then, connection attempts fail with a message that the system is starting up.
The key point in step 3 is that streaming resumes from a specific LSN. If the primary no longer has the WAL from that point, the walsender cannot send it and the walreceiver cannot continue. The standby then logs an error such as a requested WAL segment having already been removed. Later chapters cover the two ways to prevent this: replication slots and WAL archiving. A third partial measure is wal_keep_size, which you will set when you prepare the primary.
What gets sent, and when
The walsender does not wait for a WAL segment file (16 MB by default) to fill up. It sends records as soon as they are flushed to the primary's WAL. This is the difference between streaming replication and older file-based log shipping, where a standby could only see changes after a whole segment was complete.
The streaming protocol is a variant of the normal PostgreSQL wire protocol. A client opens a connection with the replication parameter set. Such a connection accepts a small set of replication commands in place of ordinary SQL, such as IDENTIFY_SYSTEM and START_REPLICATION. You can see this from psql:
psql "host=primary.example.com user=replicator dbname=postgres replication=true" \
-c "IDENTIFY_SYSTEM"The result shows the system identifier, the current timeline, and the current WAL write position. The system identifier is a unique number given to the cluster at initdb. A standby built from a base backup has the same identifier as its primary, and the walreceiver checks this on connect. That check stops you from attaching a standby to an unrelated cluster by mistake.
Reporting progress back
The data flow is not only one way. The walreceiver sends status messages back to the walsender. These carry three positions:
- The last LSN written to the standby's WAL files.
- The last LSN flushed to disk on the standby.
- The last LSN replayed by the startup process.
The primary shows these values in pg_stat_replication as write_lsn, flush_lsn and replay_lsn. They always satisfy write ≥ flush ≥ replay. The distance between the primary's current WAL position and each of them is the replication lag at that stage.
These messages matter for two reasons. First, they drive monitoring. Second, they are how synchronous replication works. When a commit waits for a standby, it waits until the standby reports that it has reached a given LSN. A later chapter covers this in detail.
The standby also sends a status message at least every wal_receiver_status_interval, which defaults to 10 seconds. Primary and standby detect a dead peer with timeouts: wal_sender_timeout on the primary and wal_receiver_timeout on the standby, both 60 seconds by default. If a network cable is cut, the other side notices only after that interval. Lower values detect failures sooner but can drop healthy connections during load spikes.
Asynchronous by default
With default settings, replication is asynchronous. The primary commits a transaction once the commit record is flushed to its own WAL. It does not wait for any standby. The walsender ships that record shortly afterwards.
This gives low commit latency, and a slow or broken standby does not stall the primary. The cost is a window of possible data loss. If the primary fails at the wrong moment, committed transactions that had not yet reached the standby are lost when you promote it. The size of that window is the lag at the time of failure.
Hot standby and recovery
A standby that only replays WAL is called a warm standby. Setting hot_standby = on makes it a hot standby, which accepts read-only queries while recovery continues. Queries run against the data files that the startup process is changing at the same time. PostgreSQL uses normal snapshot rules to give each query a consistent view.
This sets up a conflict. Replay must sometimes remove or change things that a running query still needs. For example, the primary may vacuum away old row versions that a long query on the standby can still see. The startup process then has to either wait for the query or cancel it. This tension is the subject of the query conflicts chapter. For now, remember that a hot standby is replaying WAL and serving queries at once, and the two activities can interfere.
Inspecting the running processes
You can see all of this on live servers. On the primary, the walsender shows up in the process list and in the statistics view:
SELECT pid, usename, application_name, state, sent_lsn, flush_lsn, replay_lsn
FROM pg_stat_replication;On the standby, the walreceiver has its own view. This view, pg_stat_wal_receiver, shows the connection status and the positions the standby has received:
SELECT status, receive_start_lsn, written_lsn, flushed_lsn, sender_host, slot_name
FROM pg_stat_wal_receiver;The status column is streaming during healthy operation. The written_lsn column in this view exists in PostgreSQL 13 and later. Older versions have received_lsn instead.
On Linux, ps shows the processes by title:
ps -ef | grep -E 'walsender|walreceiver|startup'Expect to see postgres: walsender replicator ... streaming ... on the primary. On the standby, expect postgres: walreceiver streaming ... and postgres: startup recovering ....
Common errors at this level
- Version or architecture mismatch. A standby on a different major version cannot replay the primary's WAL. Use logical replication for cross-version needs.
- Missing WAL on connect. The standby asks for an LSN the primary has already recycled. The fix is a slot, an archive, or a larger
wal_keep_size, or else a new base backup. - Standby not receiving but looks idle. The walreceiver is not running because
primary_conninfois wrong, the primary refuses the connection inpg_hba.conf, ormax_wal_sendersis exhausted. Check the standby log first. - Confusing receive lag with replay lag. A standby can have received all WAL and still be far behind in replay. Always compare both positions.
Exercise
A standby shows flushlsn equal to the primary's current WAL position in pgstatreplication, but replaylsn is much lower and growing slowly. Which process on the standby is the bottleneck, and what is one plausible cause?
Show answer
The startup process is the bottleneck, because the walreceiver has already received and flushed all the WAL. One plausible cause is that replay is waiting on a long-running read-only query that conflicts with the changes being replayed. Another is slow disk I/O on the standby while it applies changes to data files.
Exercise
Why must a physical standby run the same major PostgreSQL version as its primary, and why can it not accept writes?
Show answer
Physical replication ships WAL records that describe changes to data pages, so the standby must interpret and lay out pages exactly as the primary does, which requires the same major version and a compatible binary layout. The standby cannot accept writes because any local change would make its pages diverge from the primary's, and WAL replay would then corrupt or fail.