Sub topic 3
WAL records and LSNs
This chapter assumes you know basic SQL and psql, the idea of transactions, and that PostgreSQL stores table data in fixed-size 8 kB pages. It also assumes you have read the previous chapter on the write-ahead rule, which says a change must reach the log before the changed data page reaches disk. Here you will look at what is in the log and how PostgreSQL addresses positions in it.
What a WAL record contains
The write-ahead log (WAL) is a single, append-only stream of bytes. Each change to the database is described by one or more WAL records appended to that stream. A record describes a change to a data page, not a SQL statement. "Insert tuple at offset 7 of block 12 of this relation" is a typical description.
Every record has the following parts:
- A fixed header with the total record length, the transaction ID (
xid), a pointer to the previous record (xl_prev), flags, the resource manager ID, and a CRC checksum. - The resource manager ID. A resource manager is the PostgreSQL component that knows how to apply and describe a kind of record. Examples are
Heap(table rows),Btree(B-tree index pages),Transaction(commit and abort) andXLOG(checkpoints and other WAL-level events). - Block references. These name the relation file and block number the record changes. Where needed they carry a full-page image, a copy of the whole page (covered in a later chapter).
- A data payload. This holds the information the resource manager needs to redo the change.
Records are padded to 8-byte alignment. The header's CRC lets crash recovery tell a valid record from a half-written one at the end of the log. The xl_prev link lets tools walk the stream backward and check that records form an unbroken chain.
One SQL statement often produces several records. An INSERT into an indexed table writes a Heap record for the row and a Btree record for each index entry. The COMMIT then writes a Transaction record.
The LSN: a byte position in the stream
A log sequence number (LSN) is the position of a byte in the WAL stream. It is a 64-bit integer that starts at the beginning of the cluster's WAL history and only grows. The first record of an LSN range starts at that LSN. The LSN just after a record's last byte is where the next record begins.
PostgreSQL prints an LSN as two hexadecimal numbers separated by a slash, such as 0/1000028. The part before the slash is the high 32 bits and the part after is the low 32 bits. Because an LSN is a byte offset, subtracting two LSNs gives the number of bytes of WAL between them.
The pg_lsn data type stores LSNs. It supports comparison, and subtracting two pg_lsn values returns a numeric byte count:
SELECT '0/3000000'::pg_lsn - '0/1000000'::pg_lsn AS bytes_between,
'0/3000000'::pg_lsn > '0/1000000'::pg_lsn AS is_later;This returns 33554432 and true, which is 32 MB. Never compare LSNs as text, because 9/0 sorts after 10/0 as a string.
The addresses in the diagram are illustrative. The real values on your server will differ.
Reading positions in SQL
PostgreSQL tracks three positions in the WAL stream, and they can differ at any moment:
| Function | Meaning |
|---|---|
| `pg_current_wal_insert_lsn()` | Where the next record will be placed. Records up to here are in WAL buffers in memory. |
| `pg_current_wal_lsn()` | The write position: WAL handed to the operating system with `write()`, but not necessarily on stable storage. |
| `pg_current_wal_flush_lsn()` | The flush position: WAL known to be durable after `fsync` or an equivalent call. |
The order is always insert ≥ write ≥ flush. The next chapters on commit show why the flush position decides durability.
The following query shows the current position and the file that holds it:
SELECT pg_current_wal_lsn() AS current_lsn,
pg_walfile_name(pg_current_wal_lsn()) AS wal_file;pg_walfile_name_offset() gives the same file name plus the byte offset inside the file:
SELECT file_name, file_offset
FROM pg_walfile_name_offset(pg_current_wal_lsn());With the default 16 MB segment size, the file name is built from the timeline ID and the segment number, so the same LSN always maps to the same file. For 0/1000028 the segment number is 1 and the offset is 0x28, which is 40 bytes. The file is 000000010000000000000001 on timeline 1. The offset of 40 is the size of the long header on the first page of a segment. That is why the first record in a segment starts at offset 40.
These functions work only on a primary. On a standby they raise an error, and you should use pg_last_wal_receive_lsn() or pg_last_wal_replay_lsn() instead.
Measuring how much WAL a statement writes
Because LSNs are byte positions, you can measure WAL volume by taking a position before and after a statement. In psql, \gset stores a query result in a variable:
CREATE TABLE wal_demo (id int PRIMARY KEY, 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 larger than the raw 10,000 × ~100 bytes of payload. The WAL also holds record headers, the primary key index records, and possibly full-page images for pages touched for the first time since the last checkpoint. Other sessions also write WAL, so on a busy server the number includes their activity. Test on a quiet server for clean numbers.
The LSN stored on every data page
Each data page has a header field, pd_lsn, that holds the LSN just after the last WAL record that modified the page. This is how the write-ahead rule is enforced. Before the buffer manager writes a dirty page to disk, it checks pd_lsn and makes sure WAL has been flushed at least up to that position. If the log is already flushed that far, the page can go out immediately. If not, the WAL flush happens first.
Page LSNs also make replay safe to repeat. During recovery, a record is applied only if the page's pd_lsn is older than the record. A page that was already written to disk after the change is left alone.
You can see a page's LSN with the pageinspect extension, which needs superuser rights:
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT lsn,
lsn <= pg_current_wal_insert_lsn() AS not_ahead_of_wal
FROM page_header(get_raw_page('wal_demo', 0));not_ahead_of_wal should always be true. A page LSN beyond the end of the WAL would mean the log is missing changes the page already contains, which is a sign of corruption or a damaged pg_wal directory.
Decoding records with pg_waldump
pg_waldump is a command-line tool that reads segment files and prints each record. Run it as the operating system user that owns the data directory. It works while the server is running.
pg_waldump -p "$PGDATA/pg_wal" -s 0/1000028 -n 10-s sets the starting LSN and -n limits the number of records. Use an LSN from your own server, taken with pg_current_wal_lsn() before you run a test statement. The start LSN should be the start of a record. A value in the middle of a record makes the tool skip forward to the next valid record start.
Each output line shows the resource manager, record length, transaction ID, the record's own LSN, the prev LSN, and a description. A line for a heap insert looks like this (illustrative, with values that will differ on your server):
rmgr: Heap len (rec/tot): 59/59, tx: 740, lsn: 0/01000028, prev 0/00FFFFF0, desc: INSERT off: 1, flags: 0x00On PostgreSQL 15 and later, the pg_walinspect extension offers the same information through SQL functions such as pg_get_wal_records_info(start_lsn, end_lsn), which helps when you have no shell access to the server.
Common errors
- Comparing LSNs as text. Cast to
pg_lsnfirst. - Using
pg_current_wal_lsn()as proof of durability. It is the write position. Usepg_current_wal_flush_lsn()if you need to know what is on stable storage. - Calling the primary-only functions on a standby. You get an error such as "recovery is in progress".
- Assuming one statement means one record. Indexes, TOAST data and commit records each add their own.
- Passing a mid-record LSN to
pg_waldump -s. Take the LSN from a position function or from earlierpg_waldumpoutput.
Exercise
A primary server reports the current WAL position as 0/3A00128 on timeline 1, with the default 16 MB segment size. Which WAL file holds this position, and what is the byte offset inside it?
Show answer
The segment number is 0x3A00128 divided by 0x1000000, rounded down, which is 3. The file name is 000000010000000000000003. The offset is the remainder, 0xA00128, which is 10486056 bytes. You can confirm this with SELECT * FROM pgwalfilename_offset('0/3A00128');
Exercise
You run SELECT pgcurrentwal_lsn() right after a commit and get 0/5000200. Does that prove the commit record is on stable storage?
Show answer
No. pgcurrentwallsn() is the write position, which means the WAL was handed to the operating system. Only pgcurrentwalflush_lsn() reaching or passing the commit record's end position shows the record has been flushed to stable storage.