A database promises that once it says "committed", your data is safe, even if the power goes out a millisecond later. At the same time, it keeps most of its data in memory and writes pages to disk lazily, because writing every changed page immediately would be far too slow. Those two facts seem to contradict each other. The write-ahead log (WAL) is how databases make them fit together.
This article explains the problem, how the WAL works step by step, what happens during crash recovery, and the settings that affect it.
The problem
Table and index data live in pages, typically 8 KB or 16 KB. When you update a row, the database changes the page in its in-memory buffer pool. The page is now "dirty": newer in memory than on disk.
Writing that page to disk on every commit has three problems:
- It is slow. A transaction may touch pages scattered across many files. Forcing each one to disk means many random writes.
- It is wasteful. Changing a 50-byte value rewrites a whole page.
- It is not atomic. A transaction that touches ten pages could crash after writing four of them. And a single page write can itself be interrupted halfway (a torn page).
If the database just kept everything in memory instead, a crash would lose every committed change since the last write.
The idea: log first, data later
The rule behind the WAL is simple: before a change to a data page reaches disk, a record describing that change must already be safely on disk in the log.
The log is an append-only file (in practice a series of segment files). Each record describes a change, such as "in page 812 of table accounts, set this row to these bytes", and gets a position in the log called a log sequence number (LSN).
Appending to the end of one file is a sequential write, which is much faster than scattered page writes. Several transactions committing at the same time can share one flush (group commit).
A commit, step by step
Take UPDATE accounts SET balance = 900 WHERE id = 1; COMMIT;
- The database finds the page holding account 1 and loads it into the buffer pool if needed.
- It creates a WAL record describing the change and appends it to the in-memory WAL buffer.
- It modifies the page in memory and marks it dirty, stamped with the LSN of the record.
- On
COMMIT, it appends a commit record and flushes the WAL up to that point to disk, usingfsyncor an equivalent call to make sure the data is on stable storage, not just in an operating system cache. - Only then does the client get "COMMIT" back.
The data page itself is still only in memory. It will be written later, by a background writer or at a checkpoint. Before that page is written, the database checks that the WAL is flushed at least up to the page's LSN. That is the "write-ahead" rule in action.
Crash recovery
The power fails. On restart, memory is gone. Disk contains:
- data pages, some up to date, some old, written at various times;
- the WAL, containing every committed change, in order.
Recovery replays the log. It starts from the last checkpoint and, for each record, checks whether the page on disk already includes that change (by comparing the page's LSN with the record's LSN). If not, it reapplies it. This is the redo phase.
What about transactions that were running but never committed? The handling depends on the engine:
- In PostgreSQL, every row version records which transaction created it. After recovery, a transaction with no commit record is treated as aborted, so its row versions are simply invisible and are cleaned up later. No undo phase is needed.
- InnoDB keeps a separate undo log. After redo, it rolls back the changes of uncommitted transactions using that undo information.
- The classic ARIES recovery algorithm, which many databases follow in some form, has analysis, redo and undo phases.
Either way, the result is that committed transactions survive and uncommitted ones leave no trace.
Checkpoints
Without help, the log would grow forever and recovery would replay it from the beginning. Checkpoints prevent that. During a checkpoint, the database writes all dirty pages to disk and records the checkpoint's position in the log. After that, older log segments are no longer needed for crash recovery and can be recycled or archived.
Checkpoints are a trade-off. Frequent checkpoints mean faster recovery but more page writes. Rare checkpoints mean less write work but a longer replay after a crash. PostgreSQL also writes a full copy of a page into the WAL the first time it changes after a checkpoint (full-page writes), which protects against torn pages.
The WAL does more than recovery
Because the log contains every change in order, it is useful beyond crashes:
- Replication. Replicas receive the WAL stream and replay it to stay in sync. PostgreSQL streaming replication works this way.
-
Point-in-time recovery. Keep a base backup plus archived WAL segments, and you can restore the database as it was at any moment, for example just before someone ran
DELETEwithout aWHERE. - Change data capture. Tools can decode the log into a stream of row changes to feed search indexes, caches or analytics. MySQL's binary log is a separate log used for replication and similar purposes, alongside InnoDB's own redo log.
Settings worth knowing
-
Synchronous commit. PostgreSQL's
synchronous_commit = offreturns before the WAL flush. A crash can lose the last few moments of commits, but the database stays consistent. InnoDB'sinnodb_flush_log_at_trx_commitcontrols a similar trade-off. -
fsyncmust stay on. Turning off flushing entirely (PostgreSQL'sfsync = off) can corrupt the database after a crash, not just lose recent data. - Storage that lies. Disks or controllers with volatile write caches that acknowledge writes before they are durable undermine everything above.
- Disk space. A replica that falls behind or a broken WAL archive can make WAL files pile up and fill the disk.
In short
- Databases change pages in memory and write them lazily; the WAL makes that safe.
- Rule: the log record reaches disk before the data page does. A commit is durable once its log records are flushed.
- After a crash, replaying the log from the last checkpoint restores committed changes; uncommitted ones are discarded.
- The same log powers replication, point-in-time recovery and change data capture.
Originally published at abdeldjalilchougui.biz.
Top comments (0)