PostgreSQL WAL: how it works
PostgreSQL can report a transaction as committed before it writes every changed table page to disk. The Write-Ahead Log (WAL) makes that safe: the recovery record reaches durable storage before the related data-page write is allowed to reach storage.
WAL supports crash recovery and physical replication. With wal_level = logical, PostgreSQL can also decode committed row changes for Change Data Capture.
From a changed buffer to durable WAL
An INSERT, UPDATE, or DELETE changes pages in shared buffers and creates the required WAL records. PostgreSQL may write those dirty pages later, but it must first flush WAL through each page's latest required LSN.
With the default synchronous_commit = on, PostgreSQL waits for the committing transaction's WAL records to reach durable local storage before reporting success. synchronous_commit = off permits an earlier acknowledgment and accepts a short data-loss window after an operating-system or hardware crash.
Three built-in functions expose the current WAL positions:
| Function | Position |
|---|---|
pg_current_wal_insert_lsn() | End of WAL inserted into PostgreSQL's internal WAL buffers |
pg_current_wal_lsn() | End of WAL written out from the internal buffers |
pg_current_wal_flush_lsn() | End of WAL known to be on durable storage |
The distance from insert to flush is WAL that PostgreSQL has generated but has not yet confirmed as durable. Synchronous commit flushes through the committing transaction's required WAL. Other sessions may insert later records at the same time, so the global insert and flush positions need not become equal after every commit.
PostgreSQL documents an asynchronous-commit risk window of up to three times wal_writer_delay. See Asynchronous Commit for the exact behavior.
WAL segment files
WAL lives in pg_wal as sequential segment files. A segment is 16 MB by default; initdb --wal-segsize selects another size when the cluster is created.
A WAL filename contains a timeline ID followed by the segment sequence encoded as two eight-character fields. PostgreSQL creates a new timeline when archive recovery completes, including after point-in-time recovery or standby promotion. Timelines preserve the old branch instead of overwriting it.
Convert an LSN to its segment filename with:
SELECT pg_walfile_name(pg_current_wal_lsn());
PostgreSQL can recycle a segment after crash recovery, archiving, standbys, and replication slots no longer require it. Recycling renames the file for a future segment position.
WAL record structure
Every WAL record starts with a fixed header. PostgreSQL 18 defines it in xlogrecord.h:
typedef struct XLogRecord
{
uint32 xl_tot_len; /* total length of the record */
TransactionId xl_xid; /* transaction ID, when present */
XLogRecPtr xl_prev; /* previous WAL record */
uint8 xl_info; /* generic and resource-manager flags */
RmgrId xl_rmid; /* resource manager for this record */
pg_crc32c xl_crc; /* record checksum */
} XLogRecord;
xl_rmid selects the PostgreSQL resource manager that understands the record. Heap, B-tree, and transaction records have different payloads and replay functions.
xl_prev points to the previous WAL record. xl_xid identifies the transaction for records that carry an XID. Logical decoding combines record data with transaction state to emit only committed logical changes.
The bytes after the header depend on the resource manager and operation. They can include block references, full-page images, block data, and resource-manager-specific main data. Reading them correctly requires PostgreSQL-aware code.
Full-page writes protect against torn pages
When full_page_writes is enabled, the first WAL record that modifies a page after a checkpoint includes the complete page image. PostgreSQL uses 8 KB pages by default, though the block size is a build-time choice.
An operating-system crash can interrupt a page write and leave an on-disk page containing old and new sectors. The ordinary row-level WAL change cannot safely repair a page whose structure is already torn. Recovery can instead restore the full-page image and then replay later WAL records.
Subsequent changes to the same page before the next checkpoint normally need only their smaller change records. full_page_writes is enabled by default. PostgreSQL warns that disabling it can cause unrecoverable or silent corruption after a system failure.
Full-page images increase WAL volume after checkpoints. Two controls affect that cost:
- Longer checkpoint intervals reduce how often pages need their first post-checkpoint image, but can increase recovery work.
wal_compressioncompresses full-page images withpglz,lz4, orzstdwhen the corresponding support is available. Compression saves WAL bytes at the cost of CPU during logging and replay.
PostgreSQL 18 exposes cumulative wal_fpi, wal_records, and wal_bytes counters in pg_stat_wal. wal_fpi counts images, so dividing it by wal_records does not give the proportion of records that contain an image. These counters can show how image count and total WAL volume change over the same measured interval, but they do not isolate the bytes used by full-page images.
When pg_walinspect is installed, pg_get_wal_stats can measure full-page-image bytes over a selected LSN range:
-- Replace these LSNs with a range available on this server.
SELECT
pg_size_pretty(sum(fpi_size)::bigint) AS fpi_bytes,
pg_size_pretty(sum(combined_size)::bigint) AS inspected_wal_bytes,
round(
100.0 * sum(fpi_size) / NULLIF(sum(combined_size), 0),
2
) AS fpi_share_percent
FROM pg_get_wal_stats('0/1E847D00', '0/1E84F500');
fpi_share_percent reports the share of inspected WAL-record bytes used by full-page images.
Checkpoints bound crash recovery work
At a checkpoint, PostgreSQL flushes dirty data pages to disk and writes a checkpoint record to WAL. Changes needed by those pages were already flushed under the write-ahead rule. PostgreSQL then records the checkpoint position in pg_control.
Crash recovery reads pg_control, finds the checkpoint record, and starts REDO at the checkpoint's redo position. WAL older than that boundary may still be required by archiving, standbys, or replication slots.
Automatic checkpoints begin when either threshold is reached:
| Trigger | Parameter | PostgreSQL 18 default |
|---|---|---|
| Time since the previous checkpoint | checkpoint_timeout | 5 minutes |
| WAL generated since the previous checkpoint | max_wal_size | 1 GB soft limit |
PostgreSQL can skip a timed checkpoint when no WAL has been written since the previous one. The CHECKPOINT command forces one manually and is not intended for routine operation.
The checkpointer spreads page writes across the interval controlled by checkpoint_completion_target, which defaults to 0.9. Frequent checkpoints increase page-write traffic and can increase full-page-image volume. Longer intervals reduce that frequency but may leave more WAL to replay after a crash.
wal_level controls available uses
wal_level controls the information PostgreSQL records:
minimalsupports crash recovery but not WAL archiving or replication.replicais the default and supports archiving and physical replication.logicaladds the information required for logical decoding.
Each level contains the information from the lower levels. PostgreSQL 14 through 18 require logical for Remac's logical source path.
An illustrative publisher configuration is:
wal_level = logical
max_replication_slots = 4 # logical consumers plus operational reserve
max_wal_senders = 4 # concurrent replication connections
max_replication_slots must cover the expected logical consumers and any table-synchronization reserve. max_wal_senders must cover those slots plus simultaneously connected physical replicas and reconnect headroom.
For the difference between logical and physical WAL consumption, see Logical vs physical replication.
Replication slots retain required WAL
A disconnected consumer can return only if the required WAL still exists. A replication slot records a consumer's required position and prevents PostgreSQL from recycling WAL that may still be needed.
Physical and logical slots
| Physical slot | Logical slot | |
|---|---|---|
| Purpose | Raw WAL streaming | Logical decoding |
Minimum wal_level | replica | logical |
| Output plugin | None | Required, such as pgoutput |
| Associated with one database | No | Yes |
SELECT pg_create_physical_replication_slot('standby_slot');
SELECT pg_create_logical_replication_slot('cdc_slot', 'pgoutput');
SELECT pg_drop_replication_slot('cdc_slot');
Retained-WAL disk risk
An inactive or lagging slot can retain WAL until pg_wal fills the available disk. The default max_slot_wal_keep_size = -1 allows unlimited retention.
Inspect slot state with:
SELECT slot_name, slot_type, active,
pg_size_pretty(
pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)
) AS slot_wal_backlog,
wal_status,
safe_wal_size
FROM pg_replication_slots;
slot_wal_backlog is the byte distance between the slot's restart_lsn and the current WAL write location. It shows how far the slot trails, not how many bytes that slot alone occupies on disk.
Measure the ordinary files currently present in pg_wal separately with pg_ls_waldir():
SELECT pg_size_pretty(COALESCE(sum(size), 0)::bigint) AS pg_wal_disk_usage
FROM pg_ls_waldir();
pg_wal_disk_usage is the total size of those files. It can include files kept or recycled for checkpoints, configured WAL limits, standbys, archiving, replication slots, and other retention requirements, so PostgreSQL does not attribute that total to one slot. By default, pg_ls_waldir() requires superuser or pg_monitor privileges.
wal_status reports the availability of WAL claimed by the slot:
| Status | Meaning |
|---|---|
reserved | Required WAL remains within max_wal_size |
extended | Required WAL exceeds max_wal_size but is still retained |
unreserved | Some required WAL is no longer reserved and may be removed at the next checkpoint |
lost | The slot can no longer use its required WAL |
Set max_slot_wal_keep_size to a finite value to bound slot retention. If the slot falls beyond the available WAL, the consumer must create a new slot and initialize again from a consistent snapshot. PostgreSQL can also invalidate a slot for reasons other than retained-WAL limits, so operators should inspect invalidation_reason where available.
Monitor WAL generation and replication
pg_stat_wal
SELECT wal_records, wal_fpi, wal_bytes, wal_buffers_full
FROM pg_stat_wal;
| Column | Meaning |
|---|---|
wal_records | Total WAL records generated |
wal_fpi | Total full-page images generated |
wal_bytes | Total WAL bytes generated |
wal_buffers_full | Times WAL data was written because WAL buffers became full |
Use changes over a measured interval rather than treating the cumulative totals as rates. wal_bytes supports capacity and bandwidth estimates. If wal_buffers_full rises steadily, inspect WAL bursts and the wal_buffers setting.
pg_stat_replication
SELECT client_addr, state, sent_lsn, flush_lsn, replay_lsn,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
For physical replication, the lag intervals measure how long recent WAL took to reach three reported stages and for the sender to learn about them:
| Column | Reported stage |
|---|---|
write_lag | Standby wrote the WAL but had not flushed or applied it |
flush_lag | Standby wrote and flushed the WAL but had not applied it |
replay_lag | Standby wrote, flushed, and applied the WAL |
These values measure recent commit or visibility delay. They are not a prediction of how long a lagging standby will take to catch up, and they eventually become NULL on an idle, fully caught-up standby.
For byte-level replay distance:
SELECT client_addr,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes
FROM pg_stat_replication;
Logical decoding plugins may omit lag-tracking messages. For logical consumers, also inspect pg_replication_slots, confirmed_flush_lsn, retained WAL, and consumer metrics.
Next: logical and physical replication
The next article compares logical and physical replication. For the broader category, return to transaction log processing.
We built Remac to read PostgreSQL changes through logical decoding and deliver them to Kafka, RabbitMQ, Amazon S3, PostgreSQL, HTTP webhooks, files, and standard output. PostgreSQL is the first implemented source. MySQL, MongoDB, and Oracle are planned.