Sub topic 4
WAL segment files in pg_wal
This chapter covers how PostgreSQL stores the write-ahead log on disk. It assumes you can use psql, know that a WAL record has an LSN (a log sequence number, a byte position in the log), and understand that data changes are logged before data pages are written. It also assumes you can read PostgreSQL configuration parameters.
From a stream of records to files
Conceptually, WAL is one very long stream of bytes. Every record has a position in that stream, and the position is its LSN. PostgreSQL cannot keep one file that grows forever, so it cuts the stream into fixed-size pieces called WAL segment files. They live in the pg_wal directory inside the data directory ($PGDATA/pg_wal). Older releases called it pg_xlog, and you may still see "xlog" in function names and tool names from before version 10.
Each segment is the same size. The default is 16 MB. The size is fixed when the cluster is created, with initdb --wal-segsize (PostgreSQL 11 and later). It must be a power of two between 1 MB and 1 GB. You cannot change it on an existing cluster except with pg_resetwal, which is a last-resort tool and not part of normal operations.
You can check the size on a running server:
SHOW wal_segment_size;Reading a segment file name
A segment file name is 24 hexadecimal characters. It is built from three 8-character fields:
| Characters | Meaning |
|---|---|
| 1 to 8 | Timeline ID |
| 9 to 16 | Logical "log" number, the high part of the segment number |
| 17 to 24 | Segment number within that log number |
For example, 000000010000000000000003 is timeline 1, log 0, segment 3. The names increase in hexadecimal order, so a normal directory listing sorted by name also sorts the files by age within a timeline.
The timeline ID matters after point-in-time recovery or a promotion of a standby. Each of these events starts a new timeline, and the new WAL is written in files whose names begin with the new timeline number. A later chapter covers timelines in more detail. For now, treat the first field as "which branch of history this WAL belongs to".
With the default 16 MB size, one "log" number holds 256 segments (4 GB of WAL), so the last field runs from 00 to FF. With other segment sizes the number of segments per log number changes, but the naming scheme stays the same.
Mapping an LSN to a file
An LSN is printed as two hexadecimal numbers separated by a slash, for example 0/3000A28. The part after the slash is the offset in the low 32 bits. The part before it is the high 32 bits. To find the segment file that holds an LSN, divide the byte position by the segment size.
You rarely need to do this by hand, because PostgreSQL does it for you:
SELECT pg_current_wal_lsn() AS current_lsn,
pg_walfile_name(pg_current_wal_lsn()) AS wal_file;pg_current_wal_lsn() returns the position where the next WAL record will be written. pg_walfile_name() turns an LSN into the name of the file that contains it. If you also want the byte offset inside that file, use pg_walfile_name_offset():
SELECT file_name, file_offset
FROM pg_walfile_name_offset(pg_current_wal_lsn());Take the LSN 0/3000A28 on a server with 16 MB segments on timeline 1. The byte position is 0x3000A28. Dividing by 16 MB (0x1000000) gives segment 3, and the remainder 0xA28 is the offset in the file. The file is 000000010000000000000003.
Note that you must run these functions on a primary. On a standby, pg_current_wal_lsn() raises an error because the server is not writing WAL. Use pg_last_wal_receive_lsn() or pg_last_wal_replay_lsn() there.
What happens when a segment fills up
PostgreSQL writes WAL sequentially into the current segment. WAL records are packed into 8 kB WAL pages inside the file (the block size is wal_block_size, 8192 by default). Records can span a page boundary, and they can span a segment boundary too. The part of a record that continues into the next file is marked as a continuation, so a reader must be able to open both files to decode that record.
When the current segment is full, the server switches to the next one. To avoid a stall at that moment, it does not create a new file from scratch if it can avoid it. It normally reuses an old file that is no longer needed (see the section on recycling below) by renaming it to the next name in the sequence. Only if no old file is available does it create and zero-fill a new one. Pre-filling the file matters because it ensures disk space is allocated before it is needed, and, on many file systems, it makes later fsync calls cheaper than they would be on a sparse or growing file.
You can force a switch to a new segment by hand:
SELECT pg_switch_wal();This closes the current segment (the unused rest of the file is not meaningful data, it is just the file's remaining space) and starts the next. It returns the LSN at the end of the segment just closed. It is useful in tests and in archive setups where you want the latest changes to reach the archive without waiting for the segment to fill. On a server with no WAL activity since the last switch, the call does nothing, so the same file stays current.
The archive_timeout setting does the same thing automatically. If it is set, the server forces a switch when that many seconds have passed since the last one and there has been WAL activity. This bounds how stale an archive can be on a quiet system. Be careful with small values. Each forced switch produces a full-size segment file, and if you archive it, a mostly empty 16 MB file gets copied every time (unless your archive command compresses it, which makes the empty tail cheap).
Seeing the segments on disk
List the directory from a shell on the database host:
ls -l "$PGDATA/pg_wal"You will see the numbered segment files, each the full segment size, plus an archive_status subdirectory. That subdirectory holds small marker files, named after segments with the suffix .ready or .done. A .ready marker means the segment is waiting for the archiver to copy it. A .done marker means the archive command succeeded. If you do not use archiving, the directory stays empty.
You may also see .history files after a timeline switch, and .partial files created when a standby is promoted. Those belong to the timeline mechanism.
If you prefer to stay in SQL, a superuser or a member of pg_monitor (or a role granted execute on the function) can list the files:
SELECT name, size, modification
FROM pg_ls_waldir()
ORDER BY name
LIMIT 10;This is handy when you do not have shell access, for example on a managed service. Do not delete or rename anything in pg_wal by hand. The server tracks which files it needs, and removing a file that crash recovery or a replica still needs can make the cluster unrecoverable.
How many files to expect
The number of files in pg_wal is not fixed. It depends on checkpoints, on settings, and on whatever is holding old WAL. As a rough guide for a healthy server:
- The directory usually stays near
max_wal_sizein total size under heavy write load, and not belowmin_wal_size. - Files up to
min_wal_sizeare kept for reuse even when idle. - A directory far larger than
max_wal_sizemeans something is retaining WAL. Common causes are a failingarchive_command, an inactive replication slot, or a standby that has fallen behind withwal_keep_sizeset high.
Chapter material on recycling later in this tutorial explains exactly which conditions keep a segment alive. For now, remember that a growing pg_wal is a symptom to investigate, not something to fix by deleting files.
Inspecting the contents of a segment
The pg_waldump program decodes a segment file and prints one line per record. It reads files directly, so it works while the server is running and also on a stopped cluster or a copy of the files.
pg_waldump -p "$PGDATA/pg_wal" -s 0/1000028 -n 10The -p option gives the directory, -s the starting LSN, and -n the number of records to print. Use an LSN from your own server. A starting LSN must point to the start of a record. If you give an LSN from the middle of a record, pg_waldump reports an error. An LSN returned by pg_current_wal_lsn() on a server that has been idle is usually a valid record boundary, though one taken in the middle of activity may not be, because it can fall just after a record that was still being written.
Each output line shows the resource manager (such as Heap, Btree, Transaction or XLOG), the record length, the transaction ID, the LSN, and a short description. This is useful for seeing what kind of work generated your WAL.
A good experiment ties the ideas in this chapter together:
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 the amount of WAL the insert wrote, counting heap records, index records and the commit record. Compare it with the table's size from pg_relation_size('wal_demo'). WAL is usually larger than the data it describes, because indexes are logged too and the first change to each page after a checkpoint can add a full copy of the page.
Diagram: the journey of a segment
A segment file moves through a cycle. It is written, possibly archived, and then either removed or renamed for reuse.
Common mistakes
- Deleting "old" files to free space. If
pg_walis full, find out why. Checkarchive_command, replication slots and standbys first. Removing files by hand can destroy the ability to recover. - Reading the file name as a date. The name is a position, not a timestamp. Use
modificationfrompg_ls_waldir()or file times if you need the age. - Assuming one commit equals one file. Thousands of transactions fit in a 16 MB segment, and a single large transaction can span many segments.
- Calling WAL functions on a standby. Functions like
pg_current_wal_lsn()only work while the server can write WAL. - Changing
wal_segment_sizecasually. It is chosen atinitdbtime. Very small sizes mean more files and more switches. Very large sizes mean bigger archive units and coarser retention.
Exercise
A primary running with 16 MB segments on timeline 1 reports the current LSN 0/5001F00. Which segment file contains that LSN, and which SQL function would give you the same answer? Also, why does pg_current_wal_lsn() fail if you run it on a standby?
Show answer
The byte position 0x5001F00 divided by 16 MB (0x1000000) gives segment 5, so the file is 000000010000000000000005. The function pg_walfile_name('0/5001F00') returns it, and pg_walfile_name_offset() also returns the offset 0x1F00 within the file. On a standby, pg_current_wal_lsn() fails because the server is in recovery and is not writing WAL. You should use pg_last_wal_replay_lsn() or pg_last_wal_receive_lsn() instead.
Exercise
You run ls $PGDATA/pg_wal and find 400 segment files on a server where max_wal_size is 1 GB. List two likely causes and one thing you must not do.
Show answer
Likely causes include a failing or slow archive_command (segments stay marked .ready), an inactive or lagging replication slot that holds back WAL, or a very large wal_keep_size. You must not delete the files by hand, because the server or a replica may still need them for recovery.