PostgreSQL Write Ahead Log (WAL) Explained

Updated

PostgreSQL write-ahead log illustration

The WAL is an append-only record of every change, written and flushed to disk before the change reaches the data files — that ordering is what makes crash recovery possible. SELECT pg_current_wal_lsn(); shows where the log head is right now, per the postgres docs. Segments are 16 MB files in pg_wal/. wal_level decides how much goes in them, and the difference between the settings is not academic: the same 46 MB bulk load below wrote 51 MB of WAL at logical and 114 kB at minimal.

The record goes down first, which is why the feature is called write-ahead logging, and that ordering is the one thing about WAL worth getting right.

That ordering shows up at COMMIT as the WAL flush. With synchronous_commit = on, the default, COMMIT returns to the client only after the transaction’s WAL has been flushed to permanent storage with the method set by wal_sync_method (fsync, fdatasync and open_datasync are among the choices). With synchronous_commit = off the server returns success before that flush, so a crash can lose the most recent transactions: PostgreSQL’s documentation puts the exposure at three times wal_writer_delay at most, and says the cost is lost transactions, not a corrupted database. On the PostgreSQL 18.6 build I ran for this page on 19 October 2026, SHOW synchronous_commit; returned on and SHOW wal_sync_method; returned open_datasync, the macOS default (on Linux the default is fdatasync).

Watching the log head move

The LSN is a byte offset into the cluster’s entire WAL history. Take one before and after a write and you have measured exactly how much WAL that statement generated:

SELECT pg_current_wal_lsn() AS lsn_before \gset
INSERT INTO wal_demo (payload)
  SELECT repeat(md5(g::text), 8) FROM generate_series(1,50000) g;
SELECT pg_current_wal_lsn() AS lsn_after \gset
SELECT :'lsn_before' AS before, :'lsn_after' AS after,
       pg_wal_lsn_diff(:'lsn_after', :'lsn_before') AS bytes_of_wal,
       pg_size_pretty(pg_total_relation_size('wal_demo')) AS table_size;

  before   |   after   | bytes_of_wal | table_size
-----------+-----------+--------------+------------
 0/153ED38 | 0/283E060 |     19919656 | 16 MB

50,000 rows, 16 MB of table, 19 MB of WAL. More log than data is normal — the WAL carries full page images after each checkpoint as well as the row changes themselves.

Segments, and switching them by hand

postgres=# SELECT pg_walfile_name(pg_current_wal_lsn());
 000000010000000000000002

$ ls -l pg_wal
-rw------- 1 ... 16777216 000000010000000000000001
-rw------- 1 ... 16777216 000000010000000000000002
drwx------ 2 ... archive_status
drwx------ 2 ... summaries

16,777,216 bytes = 16 MB, the default. It is fixed for the life of the cluster — wal_segment_size has context internal, so it can only be chosen at initdb --wal-segsize time, not in postgresql.conf. pg_switch_wal() closes the current segment early, which is how you flush a partially-filled segment to an archive:

postgres=# SELECT pg_walfile_name(pg_current_wal_lsn());   -- 000000010000000000000002
postgres=# SELECT pg_switch_wal();
 0/283E0B0
postgres=# SELECT pg_walfile_name(pg_current_wal_lsn());   -- 000000010000000000000003

wal_level: what each setting buys, measured

Three values. replica is the default and supports physical replication and point-in-time recovery; logical adds what logical decoding needs; minimal logs only enough to recover from a crash. Attempting a logical slot at replica:

postgres=# SELECT pg_create_physical_replication_slot('hw_phys');
 (hw_phys,)
postgres=# SELECT pg_create_logical_replication_slot('hw_log','pgoutput');
ERROR:  logical decoding requires "wal_level" >= "logical"

wal_level is postmaster-context, so editing it and reloading does nothing at all — and says nothing about it. The only sign is pg_settings:

postgres=# SHOW wal_level;
 replica
postgres=# SELECT name, setting, pending_restart FROM pg_settings WHERE pending_restart;
   name    | setting | pending_restart
-----------+---------+-----------------
 wal_level | replica | t

That is the same trap that catches shared_buffers; see reload vs restart. After a real restart the logical slot is created without complaint.

Now the number that makes minimal interesting. Identical bulk load — create a table and fill it in one transaction — at two levels:

-- wal_level = logical
 wal_generated | table_size
---------------+------------
 51 MB         | 46 MB

-- wal_level = minimal
 wal_generated | table_size
---------------+------------
 114 kB        | 46 MB

At minimal, a table created and written inside the same transaction skips WAL for the bulk data entirely — a crash before commit just discards the whole relation, so there is nothing to replay. That is roughly a 450-fold reduction — the repro script measured 53,066,672 bytes against 117,120 on a later run — and it is the reason minimal still exists for one-shot bulk loads into a database nobody is replicating. That repro script is wal-write-ahead-log-guide.sh, which starts a cluster of its own, restarts it a few times to change wal_level, deletes it at the end, and asserts relationships such as the logical-versus-minimal ratio rather than exact byte counts, which vary between runs.

What it costs you is everything else:

postgres=# SELECT pg_create_physical_replication_slot('x');
ERROR:  replication slots can only be used if "wal_level" >= "replica"
postgres=# SELECT pg_backup_start('t');
ERROR:  WAL level not sufficient for making an online backup
HINT:  "wal_level" must be set to "replica" or "logical" at server start.

No replication, no online base backup, no PITR. minimal also requires max_wal_senders = 0 or the server refuses to start. (Note the function name there: pg_start_backup was renamed pg_backup_start in PostgreSQL 15, so older snippets error with function pg_start_backup(unknown) does not exist.)

Checkpoints

A checkpoint flushes dirty buffers to the data files and records a point in the WAL from which recovery can start; everything older can be recycled. The counters live in pg_stat_checkpointer, which is where PostgreSQL 17 moved them from pg_stat_bgwriter — and renamed them, so checkpoints_timed and checkpoints_req are now num_timed and num_requested:

postgres=# SELECT num_timed, num_requested, buffers_written FROM pg_stat_checkpointer;
 num_timed | num_requested | buffers_written
-----------+---------------+-----------------
         0 |             1 |            2039

postgres=# CHECKPOINT;
postgres=# SELECT num_timed, num_requested FROM pg_stat_checkpointer;
         0 |             2

log_checkpoints is on by default on this build (boot_val is on; it was off by default before PostgreSQL 15, which I could not test here), and each checkpoint writes a line worth reading:

LOG:  checkpoint complete: wrote 15090 buffers (92.1%); 0 WAL file(s) added, 0 removed,
      24 recycled; write=0.276 s, sync=0.053 s, total=0.337 s; sync files=92,
      longest=0.022 s, average=0.001 s; distance=399118 kB, estimate=399118 kB

If num_requested is climbing faster than num_timed, checkpoints are being forced by WAL volume rather than by the clock, and max_wal_size is too small for your write rate.

Archiving, and the failure that fills your disk

wal_level = replica
archive_mode = on
archive_command = 'test ! -f /archive/%f && cp %p /archive/%f'

archive_mode needs a restart. Two pg_switch_wal() calls later:

$ ls /archive
000000010000000000000006
000000010000000000000007

postgres=# SELECT archived_count, last_archived_wal, failed_count FROM pg_stat_archiver;
 archived_count |    last_archived_wal     | failed_count
----------------+--------------------------+--------------
              2 | 000000010000000000000007 |            0

Now the part that takes production down. An archive_command that fails does not stop the server and does not block writes — PostgreSQL simply keeps the unarchived segments, forever, and pg_wal grows until the filesystem is full. Setting the command to false and generating three segments:

postgres=# SELECT archived_count, failed_count, last_failed_wal FROM pg_stat_archiver;
 archived_count | failed_count |     last_failed_wal
----------------+--------------+--------------------------
              2 |            6 | 000000010000000000000008

$ ls pg_wal/archive_status | tail -3
000000010000000000000008.ready
000000010000000000000009.ready
00000001000000000000000A.ready
$ du -sh pg_wal
 96M

Alert on pg_stat_archiver.failed_count and on the count of .ready files. A full pg_wal is one of the few ways to make PostgreSQL genuinely stop accepting writes.

pg_stat_wal

postgres=# SELECT * FROM pg_stat_wal;
wal_records      | 126904
wal_fpi          | 526
wal_bytes        | 25047198
wal_buffers_full | 2402
wal_write        | 3152
wal_sync         | 0
stats_reset      | 2026-08-10 16:38:05.806964-05

wal_fpi is full page images — high values mean checkpoints are frequent relative to your write pattern, and raising max_wal_size or checkpoint_timeout will cut WAL volume. wal_buffers_full counts times a backend had to flush because wal_buffers was full; a number in the thousands, as above, is the signal to raise it. wal_write_time and wal_sync_time stay at 0 unless track_wal_io_timing is on.

On PostgreSQL 18.6 (run 19 October 2026), pg_stat_wal no longer has wal_write, wal_sync, wal_write_time or wal_sync_time: the PostgreSQL 18 release notes list those four columns as removed. The WAL write and fsync counts and times are now rows with object = 'wal' in pg_stat_io, and track_wal_io_timing controls whether the times are collected there. Same 50,000-row insert as above, on a fresh 18.6 cluster with track_wal_io_timing = on:

postgres=# SELECT * FROM pg_stat_wal;
 wal_records | wal_fpi | wal_bytes | wal_buffers_full |          stats_reset          
-------------+---------+-----------+------------------+-------------------------------
       76099 |     834 |  23793218 |             1136 | 2026-10-19 10:08:17.391049-05

postgres=# SELECT backend_type, context, writes, fsyncs FROM pg_stat_io WHERE object = 'wal' AND (writes > 0 OR fsyncs > 0) ORDER BY backend_type, context;
    backend_type    | context | writes | fsyncs 
--------------------+---------+--------+--------
 client backend     | init    |      1 |      1
 client backend     | normal  |   1138 |      0
 standalone backend | init    |      1 |      1
 standalone backend | normal  |    759 |      0
 walwriter          | normal  |      1 |      0

fsyncs stays 0 in the normal context because wal_sync_method was open_datasync on this Mac, which writes the WAL files with O_DSYNC instead of calling fsync() separately.

To read the records themselves, pg_waldump 000000010000000000000003 prints them decoded. And never delete files from pg_wal/ by hand — use pg_archivecleanup, which knows which segments are still needed.


Verified 2026-08-10 on PostgreSQL 17.10 (Homebrew), aarch64-apple-darwin25.6.0. Every LSN, byte count, error message and log line above was produced on a throwaway cluster and pasted unedited, including the 51 MB / 114 kB comparison and the deliberately broken archive_command. The PostgreSQL 18 note was run on PostgreSQL 18.6 (Homebrew) on 19 October 2026.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.