0%
PostgreSQL Deep Dive: MVCC, Vacuum, Plans, and Replication
MVCC and Vacuum
Indexes and Query Planning
Concurrency and Schema
WAL and Checkpoints
Every change PostgreSQL makes to a table or index is first described in the write ahead log, the WAL, and only later written to the data files. This single rule is what lets Postgres promise durability without writing every modified page to disk at commit time, and it is also the foundation for crash recovery, physical replication, point in time recovery and logical decoding. Understanding the WAL explains why commits are cheap but not free, why checkpoints cause periodic write spikes, why disk usage can explode when a replica falls behind, and why some settings that appear to speed up writes actually trade away safety. This section starts with the core problem the WAL solves.
The durability problem
A committed transaction must survive a crash. The obvious way to guarantee this is to write every page the transaction modified to disk and wait for the writes to finish before reporting success. That approach is slow for two reasons. A transaction that touches ten rows spread over ten pages would need ten random writes, each waiting for the storage device, and a busy table would see the same hot page written to disk again and again for every small change. It is also unsafe on its own, since a crash in the middle of writing several pages leaves some written and some not, with no record of which changes belonged together. The WAL replaces many random page writes with one sequential append of a compact description of the changes.
The write ahead rule
The rule is simple: before a modified data page can be written to disk, the WAL records that describe its changes must already be on disk. Each page carries the log sequence number, LSN, of the last WAL record that touched it, in the pd_lsn header field. When the buffer manager wants to write a dirty page, it first checks that the WAL has been flushed at least up to that LSN, and flushes it if not. Because of this rule, whatever state the data files are in after a crash, the WAL contains enough information to bring every page forward to a consistent state that includes every committed change.
Sequential beats random
Appending to a log is the cheapest kind of write a storage device can do. Records from all transactions are written one after another into the same file, so a commit that changes ten pages produces a few hundred bytes of WAL in one contiguous region, and many concurrent commits can share a single flush. Hot pages that change thousands of times between checkpoints are written to the data files only once per checkpoint, absorbing all those changes. The data files are still written eventually, but in large batches, in the background and spread over time, rather than on the critical path of every commit.
What happens at commit
When a transaction commits, its backend writes a commit record into the WAL buffers in shared memory and then asks for the WAL to be flushed up to the end of that record. The flush is an fsync or fdatasync on the WAL segment file, or an equivalent open flag, depending on wal_sync_method. Only when the flush returns does the backend report success to the client. If another backend has already flushed past that point, for example because it committed slightly later, the first backend finds its record already durable and returns immediately. This is group commit, and it is why commit throughput on a busy server can be far higher than the raw fsync rate of the disk.
What the WAL does not do
The WAL does not replace the data files and is not a log structured store. Reads always come from shared buffers or the data files, never from the WAL. Old WAL is recycled once the data it protects has been written and no consumer needs it, so the WAL is not a permanent history unless it is archived. The WAL also does not protect against logical mistakes: a DELETE without a WHERE clause is faithfully logged and faithfully replayed. Recovering from that requires a backup and point in time recovery to a moment before the mistake, which is the subject of a later lesson.
WAL as the source for everything else
Because the WAL is a complete, ordered description of every physical change, many features are built on top of it rather than having their own mechanisms. Streaming replication ships WAL to standby servers that replay it. Archiving copies WAL segments to long term storage so a base backup can be rolled forward to any point. Logical decoding reads the WAL and reconstructs row level changes for logical replication and change data capture. Even the pg_rewind tool, which resynchronizes a former primary after failover, works by reading the WAL to find which pages changed. Getting the WAL right is therefore central to almost every operational concern.
The WAL buffers and the WAL writer
Backends do not write WAL records directly to the file. They first copy them into the WAL buffers, a ring in shared memory sized by wal_buffers, which defaults to about 3 percent of shared buffers capped at one segment. Inserting into the buffers is coordinated by a small set of WAL insertion locks, so several backends can copy their records concurrently into reserved positions. The WAL writer process wakes every wal_writer_delay, 200 milliseconds by default, and writes out whatever has accumulated, which matters mostly for asynchronous commits and for transactions that generate a lot of WAL before committing. A synchronous commit does not wait for the WAL writer; the backend flushes up to its own commit record if no one else has done so.
Crash recovery step by step
When Postgres starts after a crash, the startup process reads pg_control to find the last checkpoint, then reads WAL forward from that checkpoint redo point. For each record, it reads the pages the record refers to and compares the page LSN with the record LSN. If the page LSN is already at or past the record, the change is already on disk and the record is skipped. Otherwise the change is applied and the page LSN advanced. Replay continues until the end of valid WAL, where a missing or corrupt record marks the point where writing stopped. At that point every committed transaction is reflected in the pages, transactions without a commit record are simply treated as aborted, and the server opens for connections.
Why replay is idempotent
The page LSN comparison makes replay safe to run more than once. If the server crashes again during recovery, the next attempt starts from the same checkpoint and skips everything already applied, since those pages now carry newer LSNs. This idempotence is what makes it acceptable for the data files to be in any mix of old and new states after a crash: each page is brought forward independently from wherever it happens to be. It also explains why recovery speed depends on how many pages need to be read, which in turn depends on how much WAL lies between the redo point and the end, and on whether those pages are already in the cache.
Aborted transactions need no undo
Postgres has no undo log. When a transaction aborts, or when recovery finds a transaction with no commit record, nothing needs to be rolled back in the data files. The row versions it wrote are still there, but their xmin belongs to a transaction marked as aborted in the commit log, so every snapshot treats them as invisible, and vacuum eventually removes them. This is a direct consequence of the MVCC design covered in the next part of the course, and it is why rollback in Postgres is nearly instant regardless of how much the transaction changed, while the cost is shifted to vacuum, which must later clean up the dead rows.
A data page may not reach disk before the WAL that describes its change. Commit flushes only the WAL, group commit shares flushes, and dirty pages are written later in batches. Replication, backups and change data capture all consume the same log.