Sub topic 10
Write-ahead logging and crash recovery
This chapter assumes you know BEGIN, COMMIT and ROLLBACK, and that you have met atomicity and durability as ACID properties. Here we look at the mechanism that backs both of them: the write-ahead log (WAL). Examples use PostgreSQL, but most relational databases use the same idea under different names (the redo log in MySQL InnoDB, the transaction log in SQL Server).
The problem: memory is fast, disks are slow
A database keeps its table and index data in fixed-size pages, 8 KB in PostgreSQL. When you run an UPDATE, the database changes a copy of the page in memory, in an area called the buffer cache. The changed page is now a dirty page. Writing it back to its place in the data file is a random write, and doing that on every commit would be slow.
If the database waited to write dirty pages until later, a crash would lose the change. The server would restart with a data file that does not contain work you were told was committed. That would break durability.
If the database wrote some dirty pages early, before commit, a crash could leave half of a transaction on disk. That would break atomicity.
The write-ahead log solves both problems without forcing every data page to disk at commit.
The write-ahead rule
The WAL is an append-only file on disk. Every change is first described as a log record, and the record is written to the log before the changed data page is allowed to reach the data file. This is the write-ahead rule, and it has two parts:
- Log before data. A dirty page may be written to the data file only after the log records describing its changes are safely on disk.
- Log before commit. A transaction counts as committed only after its commit record is safely on disk.
Appending to a log is a sequential write, which is much faster than scattered page writes. Because the log holds a full description of the change, the data pages can be written lazily in the background.
The important point is the order. The client hears "committed" only after the log flush. The data file write can happen seconds or minutes later.
What a log record contains
A WAL record describes a change to a page: which page, what bytes changed, and which transaction made the change. Each record gets a position in the log called the log sequence number (LSN). LSNs only increase. Every data page stores the LSN of the last record that changed it, and that detail is what makes recovery safe to repeat, as shown below.
You can see the current position in PostgreSQL:
SELECT pg_current_wal_lsn();
CREATE TABLE IF NOT EXISTS wal_demo (id integer PRIMARY KEY, note text);
BEGIN;
INSERT INTO wal_demo VALUES (1, 'first row');
SELECT pg_current_wal_insert_lsn();
COMMIT;
SELECT pg_current_wal_lsn();The second value is larger than the first, because the insert and the commit appended records. You can compute the byte difference with pg_wal_lsn_diff(lsn_a, lsn_b).
How COMMIT becomes durable
At COMMIT the database writes a commit record and then asks the operating system to flush the log to stable storage (an fsync call or equivalent). Only when the flush returns does the database report success. If power fails one millisecond later, the commit record is on disk, so the transaction can be reconstructed.
Many sessions committing at the same moment can share one flush. This is called group commit, and it is why commit throughput is much higher than one disk flush per transaction would allow.
In PostgreSQL the synchronous_commit setting controls this behavior:
SHOW synchronous_commit;
-- Trade durability for speed in this transaction only.
BEGIN;
SET LOCAL synchronous_commit = off;
INSERT INTO wal_demo VALUES (2, 'low value event');
COMMIT;With off, COMMIT returns before the log flush. A crash can lose the last fraction of a second of commits (by default up to about three times wal_writer_delay, which is 200 ms). The database stays consistent: those transactions disappear entirely rather than partly. You give up durability for those transactions and keep atomicity.
Crash recovery
After a crash, the data files may be in an arbitrary state. Some dirty pages that were in memory never reached disk. Some pages that did reach disk may belong to transactions that never committed. On restart, the database repairs this by replaying the log. Classic designs describe the work in phases:
- Find the starting point. The database reads the most recent checkpoint record, which says where in the log recovery must begin.
- Redo. It reads log records forward from that point and reapplies each change to the data pages. Before applying a record to a page, it compares the record's LSN with the LSN stored on the page. If the page is already at or past that LSN, the change is already there and the record is skipped. This check makes redo idempotent, so recovery can itself crash and be restarted safely.
- Undo uncommitted work. Changes from transactions with no commit record must not become visible.
Step 3 differs between systems. In PostgreSQL, row versions written by a transaction that never committed are simply treated as invisible, because visibility depends on whether the transaction is recorded as committed (see the MVCC chapter). No physical undo pass is needed. Databases that update rows in place, such as InnoDB, keep undo records and roll back the unfinished transactions during recovery.
Either way, the result is the same:
- Every transaction whose commit record reached the log is fully present (durability).
- Every transaction without a commit record is fully absent (atomicity).
Checkpoints
If recovery had to replay the log from the beginning of time, restarts would take hours. A checkpoint limits this. During a checkpoint, the database writes all dirty pages to the data files and records in the log that everything before a certain LSN is now safely in the data files. After that, older log segments are no longer needed for crash recovery and can be recycled or archived.
Checkpoint frequency is a trade-off:
| Setting | Effect of more frequent checkpoints | Effect of less frequent checkpoints |
|---|---|---|
| Recovery time after a crash | Shorter, less log to replay | Longer, more log to replay |
| Write load during normal operation | Higher, pages are flushed more often | Lower, pages are flushed in larger batches |
| Disk space for WAL | Lower | Higher |
In PostgreSQL, checkpoint_timeout and max_wal_size control how often checkpoints happen. You can force one with CHECKPOINT;, which requires elevated privileges.
Torn pages and full-page writes
A data page is 8 KB, but a disk may guarantee atomic writes only for smaller units. A crash in the middle of a page write can leave a torn page: part old, part new. Replaying a small change on top of a torn page would not repair it.
PostgreSQL handles this with full-page writes. The first time a page is modified after a checkpoint, the whole page image goes into the WAL. Recovery can then restore the page from the log and apply later changes on top. InnoDB uses a separate doublewrite buffer for the same purpose. This extra logging is one reason WAL volume jumps right after each checkpoint.
Common mistakes and edge cases
- Assuming COMMIT always means the data is on the platters. Disks and controllers with volatile write caches may acknowledge a flush before the data is stable. Use storage with a battery-backed or capacitor-backed cache, or disable the volatile cache.
- Confusing WAL with a backup. The WAL on the same disk as the data is lost with that disk. For point-in-time recovery, archive WAL segments elsewhere and combine them with a base backup.
- Ignoring WAL disk space. If archiving or a replica falls behind, the server keeps old log segments. The WAL directory can fill the disk and stop the database.
- Expecting ROLLBACK to be logged like COMMIT. An aborted transaction needs no flush to be correct. If the crash happens first, recovery finds no commit record and treats the transaction as aborted.
- Long transactions and recovery. A long-running transaction does not make crash recovery run its work again, but its log records stay in the WAL and can delay log recycling in some designs.
The WAL has a second use. Replicas read the same stream of records and replay them, which is how streaming replication keeps a standby server in sync.
Exercise
A client runs INSERT and COMMIT and receives a success message. The server loses power 5 milliseconds later, before any dirty data page is written to the data file. With default settings (synchronous_commit = on), is the row present after restart, and which mechanism makes that so?
Show answer
Yes, the row is present. The success message was sent only after the commit record was flushed to the WAL on disk. On restart, recovery reads the log forward from the last checkpoint and redoes the insert on the data page, so the row reappears even though the data file never received the dirty page.
Exercise
A transaction updated 10,000 rows and the server crashed before the client sent COMMIT. Part of the changed pages had already been written to the data files. After restart, how many of the 10,000 updates are visible, and why does the write-ahead rule allow some of those pages to be on disk at all?
Show answer
None of the updates are visible. The transaction has no commit record in the log, so recovery treats it as aborted: PostgreSQL treats its row versions as invisible, and an in-place-update system rolls them back using undo records. Pages may be written early because the log records describing their changes were flushed first, which lets recovery identify and neutralize the uncommitted changes.