Sub topic 1
WAL and log sequence numbers: what gets replicated
Streaming replication copies one thing from the primary to the standby: the write-ahead log. This chapter explains what that log contains, how positions in it are numbered, and which parts of a server it does not cover. You need this model for every later chapter, including monitoring lag, replication slots and failover.
Prerequisites
This chapter assumes you can:
- Start and stop a PostgreSQL server and edit
postgresql.conf. - Use
psqland write basic SQL. - Explain what a transaction and a commit are.
- Read hexadecimal numbers such as
0/3000148.
You need a single PostgreSQL server (version 10 or later) where you can run SQL as a superuser or a member of pg_monitor. No standby is needed yet.
What the write-ahead log is
The write-ahead log (WAL) is a sequential record of every change made to the database. The rule is "write ahead": PostgreSQL writes the description of a change to the WAL and flushes it to disk before the transaction is reported as committed. The changed data pages in the shared buffer cache can be written to the table files later.
This ordering gives two benefits:
- Durability at low cost. A commit needs one sequential flush of the WAL. It does not need random writes to many table and index files.
- Crash recovery. After a crash, the server reads the WAL from the last checkpoint and replays changes that never reached the table files.
Replication reuses the second benefit. A standby is a server that stays permanently in recovery. It replays WAL that arrives from the primary instead of WAL it generated itself.
What a WAL record contains
A WAL record is a physical description of a change to specific pages. It is not a SQL statement. A typical record holds:
- The resource manager that owns it (heap, btree, transaction, and so on).
- The transaction ID.
- References to the blocks it changes (tablespace, database, relation, block number).
- The data needed to redo the change, such as the new tuple.
A transaction commit also writes its own record, and the standby learns about commits by replaying it.
Two details matter for replication:
- Full-page images. After each checkpoint, the first change to a page writes the whole 8 kB page into the WAL (controlled by
full_page_writes, on by default). This protects against torn pages after a crash. It also means WAL volume spikes right after a checkpoint. - Replay is idempotent. Every data page header stores the LSN of the last WAL record applied to it. During replay, PostgreSQL applies a record only if the page's LSN is older than the record's LSN. Replaying the same stretch of WAL twice therefore does no harm. A standby can safely restart and resume replay.
Log sequence numbers
A log sequence number (LSN) is a position in the WAL. It is a 64-bit count of bytes, starting from the first byte of WAL the cluster ever wrote. Every record has an LSN, and a larger LSN always means a later position.
PostgreSQL prints an LSN as two hexadecimal numbers separated by a slash: the high 32 bits and the low 32 bits. The value 0/3000148 means high part 0, low part 0x3000148, a position about 48 MB into the WAL history.
The pg_lsn data type stores LSNs. You can compare two values, and subtracting them gives the byte distance as a numeric. That subtraction is how lag is measured in bytes.
SELECT pg_current_wal_lsn();
-- Example result: 0/3000148
SELECT '0/3000148'::pg_lsn - '0/3000060'::pg_lsn AS bytes_apart;
-- Result: 232pg_wal_lsn_diff(a, b) returns the same value as a - b and is common in monitoring queries.
Measuring how much WAL a statement writes
Record the LSN, run the work, and compare. This uses psql's \gset to store a result in a variable.
CREATE TABLE wal_demo (id int, payload text);
SELECT pg_current_wal_lsn() AS before_lsn \gset
INSERT INTO wal_demo
SELECT g, repeat('x', 100) FROM generate_series(1, 10000) AS g;
SELECT pg_size_pretty(
pg_wal_lsn_diff(pg_current_wal_lsn(), :'before_lsn')
) AS wal_generated;The result is on the order of 1 to 2 MB. The exact number depends on page layout and whether a checkpoint occurred in between, because a checkpoint adds full-page images.
Segments and file names
WAL is stored in the pg_wal directory as segment files. Each segment is 16 MB by default. You can change that only when you create the cluster (initdb --wal-segsize).
A segment file name has 24 hexadecimal digits, made of three 8-digit groups:
- The timeline ID.
- The high part of the segment number (the "log" part).
- The low part of the segment number.
You can map an LSN to its file and to its offset inside that file:
SELECT pg_walfile_name('0/3000148');
-- 000000010000000000000003
SELECT * FROM pg_walfile_name_offset('0/3000148');
-- file_name: 000000010000000000000003, file_offset: 328The timeline is 00000001, and the segment number is 3 because 0x3000148 / 0x1000000 = 3. The offset 328 is 0x148. Timelines matter again when you promote a standby, so keep the first group in mind.
The different LSNs on one server
A running primary has several positions for the same stream. Replication monitoring uses them:
| Function or column | Meaning |
|---|---|
| `pg_current_wal_insert_lsn()` | Where the next record will be placed in the WAL buffers. |
| `pg_current_wal_lsn()` | The end of WAL that has been written to the operating system. |
| `pg_current_wal_flush_lsn()` | The end of WAL that has been flushed to durable storage. |
| `pg_last_wal_receive_lsn()` | On a standby: the end of WAL received and flushed from the primary. |
| `pg_last_wal_replay_lsn()` | On a standby: the last position that replay has applied. |
The order is insert, then write, then flush on the primary. On a standby, "received" is ahead of or equal to "replayed". The gap between the two is WAL that has arrived but is not yet visible to queries.
The pg_current_wal_* functions raise an error on a standby (recovery is in progress), because a standby is not generating WAL. On a standby, use the pg_last_wal_* functions.
wal_level decides what the log carries
The wal_level setting controls how much information goes into the WAL:
| Value | Use |
|---|---|
| `minimal` | Enough for crash recovery only. Some bulk operations skip WAL. Cannot be used for streaming replication or archiving. |
| `replica` | Adds what is needed for WAL archiving and physical replication, including read-only queries on a standby. This is the default since PostgreSQL 10. |
| `logical` | Adds what is needed to decode changes into row-level changes for logical replication. |
Changing wal_level requires a restart. A primary running with wal_level = minimal refuses to start walsender connections, and a standby cannot be built from it. Chapter content on configuring the primary covers the full settings.
What is replicated and what is not
Physical streaming replication ships the WAL of the whole cluster, so the standby becomes a byte-level copy of the primary's data. The consequences:
- Everything logged is replicated. All databases, all tables and indexes, roles, and the system catalogs arrive on the standby. You cannot choose a subset of databases or tables.
- Same major version and platform. The standby must run the same PostgreSQL major version and a compatible CPU architecture and operating system family, because the files are copied physically.
- Unlogged and temporary tables are not replicated. An
UNLOGGEDtable writes no WAL for its data, so on a standby it is empty and cannot be read. Temporary tables are local to a session and do not exist on the standby. - Configuration files are not replicated.
postgresql.confandpg_hba.conflive outside the WAL stream. Keep them in step yourself, especially settings that must be at least as large on a standby, such asmax_connections. - Replay is the only writer. A standby cannot accept writes, because any change it made would fork its data away from the primary's WAL.
Common errors
- Reading
pg_current_wal_lsn()on a standby. It fails. Usepg_last_wal_receive_lsn()orpg_last_wal_replay_lsn(). - Comparing LSNs as text.
'0/9'sorts after'0/10'as a string. Cast topg_lsnbefore comparing. - Using
pg_xlognames from old tutorials. PostgreSQL 10 renamedpg_xlogtopg_walandpg_current_xlog_location()topg_current_wal_lsn(). Examples using the old names fail on current versions. - Expecting WAL to disappear after commit. The server keeps segments until a checkpoint has passed them and nothing else needs them, such as an archive command, a standby, or a replication slot. Later chapters show how a stalled consumer makes
pg_walgrow.
Exercise
On a primary, pg_current_wal_lsn() returns 0/5001A28. Which WAL segment file holds that position on timeline 1 with the default segment size, and how many bytes into that file is it?
Show answer
The segment size is 16 MB, which is 0x1000000. The value 0x5001A28 divided by 0x1000000 gives segment 5, so the file is 000000010000000000000005. The offset is the remainder, 0x1A28, which is 6696 bytes. You can confirm this with SELECT * FROM pg_walfile_name_offset('0/5001A28');.
Exercise
A colleague says that creating an UNLOGGED table on the primary is a good way to keep a scratch table out of replication. What happens to that table on a hot standby, and why?
Show answer
The table exists on the standby (its definition is in the replicated catalogs), but it is empty and cannot be queried, because the primary wrote no WAL for its data. Queries against it fail with an error saying that unlogged tables cannot be accessed during recovery. The table is only usable on the primary.