skip to content

WAL records and LSNs

pg_walinspect on a real INSERT: record types, lengths, and the blocks each record touches.

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

the WAL is one long stream of records, and an LSN (log sequence number) is just a byte position in it. every record names its resource manager (Heap, Btree, Transaction, XLOG, ...) and a record type, carries the xid that wrote it, and lists the blocks it touches. pg_walinspect reads them back from SQL: an INSERT is a heap record, one index record per index, and a commit record.

the picture

you know how people say "the WAL" like it's a mysterious binary blob only replicas understand? it's a list. a long, append-only list of small, self-describing records, each saying "on this page of this relation, do this". you can read it from SQL, and it's more readable than you'd think.

think of a ship's log. every entry has a position in the book (the LSN), who made it (the xid), which department (the resource manager: engine room, galley, bridge), what kind of entry it is (the record type), and which compartments it's about (the block references). some entries carry a full sketch of a compartment as it looked (a full-page image). the commit entries are the captain's signature.

  • the same for every record
  • ├── xl_tot_lentotal length of this record, header included
  • ├── xl_xidthe transaction that wrote it (0 for bookkeeping)
  • ├── xl_prevthe LSN of the record before it: the log is a chain
  • ├── xl_info, xl_rmidwhich resource manager, which record type
  • └── xl_crca CRC of the whole record: a torn or garbage record fails it
  • zero or more
  • ├── relation, fork, block numberwhich page this record changes
  • └── full-page imageoptional: a copy of the page, holes left out
  • main datathe change itself: the tuple, the key, the commit time
drawn by hand · after src/include/access/xlogrecord.h, postgres 18
one WAL record, drawn by hand from postgres's xlogrecord.h. the header is 24 bytes; the rest depends on what's being logged.

reading it back

pg_walinspect reads the WAL between two LSNs. postgres 16 added pg_get_wal_block_info, which lists each record's block references, so a join tells you which relation each record touched. this block wraps that join in a small function, marks the current position, and inserts one row:

sqldb=lab · session rec
CREATE FUNCTION wal_since(start pg_lsn)
RETURNS TABLE (lsn pg_lsn, rmgr text, record_type text, len int4, fpi int4, rel name)
LANGUAGE sql AS $$
  SELECT r.start_lsn, r.resource_manager, r.record_type, r.record_length, r.fpi_length, c.relname
  FROM pg_get_wal_records_info(start, pg_current_wal_insert_lsn()) AS r
  LEFT JOIN pg_get_wal_block_info(start, pg_current_wal_insert_lsn()) AS b ON b.start_lsn = r.start_lsn
  LEFT JOIN pg_class AS c ON c.relfilenode = b.relfilenode
$$;
SELECT set_config('my.start', pg_current_wal_insert_lsn()::text, false) IS NOT NULL AS marked,
       set_config('my.lsn', pg_current_wal_insert_lsn()::text, false) IS NOT NULL AS also;
INSERT INTO accounts VALUES (4, 'dave', 10.00);
SELECT * FROM wal_since(current_setting('my.lsn')::pg_lsn) ORDER BY lsn;
output, from postgres 18.6
#1 · CREATE FUNCTION
#2 · SELECT 1
markedboolalsobool
tt
(1 row)
#3 · INSERT 0 1
#4 · SELECT 5
lsnpg_lsnrmgrtextrecord_typetextlenint4fpiint4relname
0/17F7580XLOGFPI_FOR_HINT35973548pg_constraint
0/17F83A8XLOGFPI_FOR_HINT42734224null
0/17F9460HeapINSERT254200accounts
0/17F9560BtreeINSERT_LEAF173120accounts_pkey
0/17F9610TransactionCOMMIT340null
(5 rows)

(set_config keeps the starting LSN in a session setting, so marking it doesn't write any WAL.)

the last three rows are the INSERT. Heap INSERT put the tuple on page 0 of accounts. Btree INSERT_LEAF added its key to accounts_pkey. Transaction COMMIT made both count. the heap and btree records are big because each carries a full-page image: this is the first change to those pages since the dataset's last checkpoint (full-page writes is about why).

the rows above them are a surprise: XLOG FPI_FOR_HINT, whole catalog pages. this is the session's first statement, so planning it read catalog rows nobody had read since the dataset was built, set their hint bits, and, with checksums on, had to log those pages too. (a row with no name is a catalog whose file pg_class doesn't list by relfilenode: pg_class, pg_attribute, pg_proc and pg_type are "mapped".) reading wrote WAL. the second insert is clean:

sqldb=lab · session rec
continues session rec (1 earlier block run first)
SELECT set_config('my.lsn', pg_current_wal_insert_lsn()::text, false) IS NOT NULL AS marked;
INSERT INTO accounts VALUES (5, 'erin', 20.00);
SELECT * FROM wal_since(current_setting('my.lsn')::pg_lsn) ORDER BY lsn;
output, from postgres 18.6
#1 · SELECT 1
markedbool
t
(1 row)
#2 · INSERT 0 1
#3 · SELECT 3
lsnpg_lsnrmgrtextrecord_typetextlenint4fpiint4relname
0/17F9638HeapINSERT690accounts
0/17F9680BtreeINSERT_LEAF640accounts_pkey
0/17F96C0TransactionCOMMIT340null
(3 rows)

the same three records, this time only the changes. here are both, and two updates, captured statement by statement:

T1INSERT INTO accounts VALUES (4, 'dave', 10.00)

a new account. the heap insert carries a copy of page 0 (the first change since the dataset's checkpoint), the primary key gets a leaf entry, then the commit.

flush line: durable from here backin wal_buffers, not on diskredo pointer, record headerjust appended, being replayeddirty page
step 1/4
real output, postgres 18.6 (PGlite 0.5.12) · records
step through four statements on lab's accounts. each record shows its LSN, length, resource manager and type, and the block it touched (+FPI when it carries the page). autocommit flushes at every COMMIT, so the flush line follows the commit record.
1st INSERT: heap254 B
1st INSERT: btree173 B
2nd INSERT: heap69 B
2nd INSERT: btree64 B
COMMIT34 B
real output, postgres 18.6 (PGlite 0.5.12) · records
record lengths in bytes, from the same capture. the first insert pays for two page images; the second is the change alone.

254 bytes against 69 for the same kind of row. the 200 bytes of difference is page 0 as it stood before the change (postgres leaves out the empty middle of the page, so a page with three small rows logs small). a commit record is 34 bytes: the commit time, plus a little bookkeeping.

an UPDATE, HOT or not

predict the output
UPDATE accounts SET id = 20 WHERE id = 2: how many WAL records, commit included?
sql
UPDATE accounts SET balance = balance + 10 WHERE id = 1;  -- heap, commit
UPDATE accounts SET id = 20 WHERE id = 2;                 -- ?
sqldb=lab · session rec
continues session rec (2 earlier blocks run first)
SELECT set_config('my.lsn', pg_current_wal_insert_lsn()::text, false) IS NOT NULL AS marked;
UPDATE accounts SET balance = balance + 10 WHERE id = 1;
UPDATE accounts SET id = 20 WHERE id = 2;
SELECT * FROM wal_since(current_setting('my.lsn')::pg_lsn) ORDER BY lsn;
output, from postgres 18.6
#1 · SELECT 1
markedbool
t
(1 row)
#2 · UPDATE 1
#3 · UPDATE 1
#4 · SELECT 7
lsnpg_lsnrmgrtextrecord_typetextlenint4fpiint4relname
0/17F96E8XLOGFPI_FOR_HINT81658116null
0/17FB6E8Heap2PRUNE_ON_ACCESS520null
0/17FB720HeapHOT_UPDATE700accounts
0/17FB768TransactionCOMMIT340null
0/17FB790HeapUPDATE690accounts
0/17FB7D8BtreeINSERT_LEAF640accounts_pkey
0/17FB818TransactionCOMMIT340null
(7 rows)

HOT_UPDATE versus UPDATE plus INSERT_LEAF, 70 bytes against 133 before the commit records. on a table with five indexes the non-HOT update writes five index records. that's most of what indexes cost. (the unnamed FPI_FOR_HINT and PRUNE_ON_ACCESS rows at the top are catalog pages again, hinted and pruned as the UPDATE was planned.)

resource managers

every record belongs to a resource manager: the part of postgres that knows how to replay it. recovery reads a record, looks at its rmgr id, and hands it to that module's redo function.

sqldb=lab
SELECT rm_id, rm_name FROM pg_get_wal_resource_managers() ORDER BY rm_id;
output, from postgres 18.6
SELECT 22
rm_idint4rm_nametext
0XLOG
1Transaction
2Storage
3CLOG
4Database
5Tablespace
6MultiXact
7RelMap
(22 rows)showing 8 ·

22 built in. Heap and Heap2 split the heap's record types between them (the first ran out of room in the 4-bit type field), Btree, Hash, Gin, Gist, SPGist and BRIN are the index types, Transaction has COMMIT and ABORT, XLOG has checkpoints and page images, Standby tells replicas which transactions are running. extensions can register their own (that's what rm_builtin is for). pg_get_wal_stats sums any stretch of WAL by resource manager. here's everything this session has written since its first mark:

sqldb=lab · session rec
continues session rec (3 earlier blocks run first)
SELECT "resource_manager/record_type" AS rmgr, count, record_size, fpi_size
FROM pg_get_wal_stats(current_setting('my.start')::pg_lsn, pg_current_wal_insert_lsn())
WHERE count > 0
ORDER BY rmgr;
output, from postgres 18.6
SELECT 5
rmgrtextcountint8record_sizeint8fpi_sizeint8
Btree3181120
Heap4262200
Heap21520
Transaction41360
XLOG314715888
(5 rows)

an LSN is an address

an LSN is a 64-bit byte offset into the WAL since the cluster was created, printed as two hex halves: the high 32 bits, a slash, the low 32. subtract two and you get bytes:

sqldb=lab
SELECT pg_current_wal_insert_lsn() AS here,
       pg_wal_lsn_diff(pg_current_wal_insert_lsn(), '0/0') AS bytes_since_initdb,
       file_name, file_offset
FROM pg_walfile_name_offset(pg_current_wal_insert_lsn());
output, from postgres 18.6
SELECT 1
herepg_lsnbytes_since_initdbnumericfile_nametextfile_offsetint4
0/17E9D28250749840000000100000000000000018297768
(1 row)

the lab database is about 25 MB into its WAL (25,074,984 bytes). on disk the stream is cut into 16 MB segment files in pg_wal/, named after the timeline and the LSN they start at. file_offset is where in that file the position falls. every page header stores an LSN (pd_lsn), every replica reports how far it has got as an LSN, and pg_wal_lsn_diff between two of them is "how many bytes behind" (streaming replication uses exactly that).

keylines

  • the WAL is an append-only stream of records. an LSN is a byte position in it.
  • each record has a resource manager, a type, an xid, block references and maybe a full-page image.
  • an INSERT is a heap record, one index record per index, and a commit record.
  • a HOT update writes one heap record. a non-HOT one adds an index record per index.
  • pg_get_wal_records_info, pg_get_wal_block_info and pg_get_wal_stats read it from SQL.