Sub topic 2
The write-ahead rule: log first, data pages later
This chapter assumes you know basic SQL and psql, the ACID properties, and the idea that tables are stored as fixed-size pages (8 kB by default in PostgreSQL). It covers the ordering rule that WAL is built on. Record formats, segment files, commit behavior and checkpoints each get their own chapter.
The rule
The write-ahead rule has two parts:
- Before a changed data page can be written to its file on disk, the WAL record describing that change must already be on durable storage.
- Before a transaction is reported as committed, all WAL records up to and including its commit record must be on durable storage.
Together they mean the log always runs ahead of the data files. After a crash, PostgreSQL can replay the log to repair anything the data files are missing.
The rule constrains the order of disk writes. It says nothing about when a data page must be written, and a committed change may sit only in memory and in the WAL for a long time.
Why not just write the pages?
A single UPDATE can touch a heap page, several index pages, and a visibility map page. Those pages live in different files and different places on disk. Forcing all of them to disk at every commit has two costs:
- Random writes are slow. The pages are scattered, so each flush may cost a seek on spinning disks or a separate write on SSDs.
- A crash in the middle of the flush leaves a half-applied change. The table page might be updated while the index page is not.
The log avoids both problems. WAL is appended sequentially to one file at a time. One flush makes a whole transaction's changes durable, however many pages they touched. The data pages are written later in the background, in batches, in whatever order is efficient.
How the pieces fit
Three areas of memory and disk are involved:
- Shared buffers hold cached copies of data pages. A page changed in memory but not yet written out is called dirty.
- WAL buffers hold WAL records that have been generated but not yet written to the WAL file.
- The WAL files and data files on disk are the durable copies.
The sequence diagram shows what happens for one change.
Reading the diagram from the top:
- The backend (the server process handling your session) modifies the page in shared buffers and marks it dirty.
- It appends a WAL record describing the change to the WAL buffers.
- It stamps the page with the position of that record in the log. That position is the page's LSN (log sequence number). The next chapter covers LSNs in detail. For now, treat an LSN as a byte offset into the WAL stream.
- At commit, the backend appends a commit record and flushes the WAL to disk. Only then does the client get its acknowledgement.
- Later, the background writer or checkpointer decides to write the dirty page out. Before it does, it checks the page's LSN and makes sure the WAL is flushed at least that far.
How the rule is enforced: the page LSN
PostgreSQL needs a cheap way to know whether the WAL covering a given page has been flushed. It stores that information in the page itself. Every data page header contains an LSN, which is the position just past the last WAL record that modified the page.
When the buffer manager is about to write a dirty buffer, it compares the page LSN with the point up to which WAL is known to be flushed. If the WAL is behind, it flushes the WAL first and then writes the page. This is the check that makes the rule hold even for pages written long before their transaction commits.
Inside the server, a change to a page follows a fixed pattern:
- Lock the buffer exclusively.
- Enter a critical section. An error here is escalated to a server crash, so a half-done change cannot persist.
- Modify the page and mark the buffer dirty.
- Insert the WAL record and stamp the page with its LSN.
- Leave the critical section and release the lock.
The page is changed in memory before the record is inserted. That is allowed because the rule is about what reaches disk. Nobody can write the page out while the buffer is locked, and the LSN stamp is in place before the lock is released.
Watching the page LSN
You can see the page LSN with the pageinspect extension, which needs superuser rights. This example compares a page's LSN with the current WAL insert position, before and after an update.
CREATE EXTENSION IF NOT EXISTS pageinspect;
CREATE TABLE rule_demo (id int PRIMARY KEY, note text);
INSERT INTO rule_demo VALUES (1, 'first');
SELECT lsn AS page_lsn_after_insert
FROM page_header(get_raw_page('rule_demo', 0));
SELECT pg_current_wal_insert_lsn() AS insert_lsn_now;
UPDATE rule_demo SET note = 'second' WHERE id = 1;
SELECT lsn AS page_lsn_after_update
FROM page_header(get_raw_page('rule_demo', 0));Expect these results:
- The page LSN after the update is larger than the one after the insert. The update's WAL record moved the stamp forward.
- Each page LSN is less than or equal to the insert position that you read at about the same time. A page can never claim a WAL record that has not been generated.
The exact values differ on every server.
What the rule allows
The rule leaves two decisions open, and PostgreSQL's choices explain much of its behavior. Textbooks name these policies "steal" and "no-force".
| Question | PostgreSQL's choice | Consequence |
|---|---|---|
| May a page with uncommitted changes be written to disk? (steal) | Yes | Data files can contain changes from transactions that later abort or are lost in a crash. |
| Must a committed transaction's pages be written at commit? (no-force) | No | Commit only needs a WAL flush. Data files can lag behind the committed state. |
Both choices are safe because of what the log and the rest of the system supply:
- No-force is covered by redo. If a crash loses a committed change that was only in memory, replaying the WAL reapplies it.
- Steal is covered by MVCC (multiversion concurrency control). A page on disk may hold tuples from an uncommitted transaction, but visibility rules consult the transaction's commit status, which is itself WAL-logged. A tuple whose transaction never committed stays invisible.
For this reason PostgreSQL's WAL is a redo-only log. It does not need to undo uncommitted changes during recovery. Crash recovery is covered in a later chapter.
Where the guarantee can break
The rule is only as strong as the layers underneath it. Common ways to defeat it:
fsync = off. PostgreSQL stops forcing WAL and data to stable storage. The ordering is no longer guaranteed, and a crash can corrupt the cluster beyond what recovery can fix. Use it only for disposable data, such as a throwaway test load.- Storage that lies about flushes. A disk or controller with a volatile write cache that acknowledges a flush early breaks the ordering in practice. PostgreSQL cannot detect this.
full_page_writes = offon storage that can write torn pages. This is covered in the chapter on full-page writes.
Some changes are deliberately outside the rule:
- Unlogged tables (
CREATE UNLOGGED TABLE) and temporary tables do not generate WAL for their contents. They are fast, but after a crash an unlogged table is emptied, because nothing exists to repair it. - Setting
synchronous_commit = offdoes not violate the write-ahead rule. The second half of the rule is relaxed for a short window: a commit may be acknowledged before its WAL is flushed. After a crash you can lose the most recent commits, but the database stays consistent. Part one of the rule, flushing WAL before data pages, is still enforced.
Common mistakes
- Thinking commit writes the table. After
COMMITreturns, the changed pages are often still dirty in memory. Only the WAL is guaranteed to be on disk. - Thinking WAL is a copy of the data pages. WAL records mostly describe changes, such as "insert this tuple at this offset of this page". The exception is a full copy of a page, which is written under certain conditions covered in a later chapter.
- Reading page LSNs as timestamps. An LSN is a position in the log. It increases monotonically but says nothing about wall-clock time.
- Assuming the data files are always consistent on their own. At any moment they may mix old and new page versions, which is why recovery must replay WAL before the server accepts connections.
Summary
- The write-ahead rule orders disk writes: WAL first, data page afterward.
- Each page carries an LSN. Before writing a dirty page, the buffer manager flushes WAL up to that LSN.
- Commit needs only a WAL flush. This is what makes commit cheap.
- PostgreSQL allows dirty pages of uncommitted transactions on disk and does not force pages at commit. WAL redo and MVCC visibility make that safe.
- The guarantee depends on
fsyncand on storage that honors flush requests.
Exercise
A backend updates a row and the change is stamped on the page with LSN 0/5000100. The background writer wants to write that page, and the WAL is flushed only up to 0/5000000. What must happen before the page is written, and why?
Show answer
The WAL must first be flushed at least up to 0/5000100. The write-ahead rule requires that the record describing the change is durable before the page containing the change reaches the data file. Otherwise a crash could leave a changed page on disk with no WAL record to explain or repeat the change.
Exercise
A table was updated and committed with synchronous_commit = on, and the server then crashes before any checkpoint wrote the table's dirty pages. Is the committed update lost? Which part of the rule makes this outcome possible?
Show answer
No, the update is not lost. At commit, the WAL up to the commit record was flushed (the second part of the rule), so the change is durable in the log. During crash recovery, PostgreSQL replays the WAL and reapplies the change to the data pages. Because commit does not force data pages to disk (no-force), the data files lagged behind, and redo repairs that.