Sub topic 1
Why a database needs a log
PostgreSQL promises that once COMMIT returns, your change survives a crash. It keeps that promise without writing every changed data page to disk at commit time. This chapter explains the problem that makes a log necessary. Later chapters cover the log itself and checkpoints.
Prerequisites
This chapter assumes you have:
- Basic SQL and
psqlskills. - A working idea of transactions and the ACID properties, especially atomicity and durability.
- A rough picture of how a database stores rows in fixed-size pages on disk. PostgreSQL pages are 8 kB by default.
- Some comfort reading PostgreSQL configuration parameters with
SHOW.
You do not need to know anything about WAL internals yet.
The promise to keep
Durability is the D in ACID. If the server reports that a transaction committed, the data must still be there after a power cut, a kernel panic, or a killed postgres process.
Atomicity is the related promise. A transaction either happens completely or not at all. After a crash you must never find half of a transfer applied.
Here is a small transaction that needs both guarantees:
CREATE TABLE accounts (
id int PRIMARY KEY,
balance numeric NOT NULL
);
INSERT INTO accounts VALUES (1, 100), (2, 100);
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;When COMMIT returns, both updates must be durable. If the server dies in the middle, neither update may be visible afterward.
Where your data actually lives
To see why this is hard, look at where a change goes when you run an UPDATE.
- PostgreSQL reads the 8 kB heap page that holds the row into shared memory, in an area called shared buffers. This happens only if the page is not already there.
- It modifies the page in memory. The page is now dirty: it differs from the copy on disk.
- It does the same for each index page that must change.
- Eventually, some background process writes the dirty pages back to the data files.
Steps 1 to 3 happen in RAM. RAM is lost when the process or machine dies. The data files on disk still hold the old versions of the pages until step 4 happens.
A second layer adds more delay. When PostgreSQL calls write(), the data usually lands in the operating system's page cache, not on the physical device. Only a call such as fsync() forces it to stable storage. A power failure can lose anything that was written but not yet fsynced.
The naive approach: flush data pages at commit
The simplest way to make a commit durable is to write every page the transaction changed to its data file and fsync them before returning from COMMIT. Database literature calls this a force policy: commit forces the data pages out.
It is correct in the easy case, but it has three serious problems.
Random I/O at commit time
The pages a transaction touches are scattered across table and index files. Writing them means many random writes, each 8 kB, even if you changed a single 4-byte integer in each. Random writes are the slowest pattern for spinning disks. They are also costly on SSDs.
Repeated writes of hot pages
Suppose a thousand small transactions all update rows in the same page. A force policy writes that page a thousand times. If PostgreSQL could keep the page in memory and write it once, it would save 999 writes.
No atomicity across pages
Our transfer touches at least two heap pages, and probably two index pages as well. You cannot write several pages in one atomic operation. A crash after the first page is on disk and before the second leaves the database in a state that never existed logically: money was taken from one account and not given to the other. The database has no way to tell, because the files hold no record of what was intended.
The opposite approach: write nothing until later
If you drop the force policy, commits become fast. Dirty pages stay in memory and are written in the background, in whatever order and batches suit the system. This is called a no-force policy.
But now a crash loses committed work. A transaction can return from COMMIT while all its changes exist only in shared buffers. If the machine loses power, the data files still hold the old state.
There is a related complication. The background writer, or a backend that needs to free a buffer, may write a dirty page to disk before its transaction commits. That is called a steal policy. It is needed because shared memory is finite and a large transaction can dirty more pages than fit. But it means the data files can contain changes from transactions that never committed. After a crash, those changes must be undone or ignored.
PostgreSQL steals pages freely and does not force them at commit. That gives good performance. It also means the data files alone, after a crash, can be missing committed changes and can contain uncommitted ones. Something else must carry enough information to repair that.
The solution: a sequential log of changes
The something else is the write-ahead log, usually shortened to WAL. It is an append-only stream of records that describe every change made to the database. For our transfer, the log would contain, in order, a record saying that a row in the heap page of account 1 was updated, a similar record for account 2, any index changes, and finally a record saying that the transaction committed.
At commit, PostgreSQL does not flush the data pages. It flushes the log, up to and including the commit record. The log has properties that make this cheap and sufficient:
- Sequential. WAL is written at its end, one record after another. Sequential appends are far faster than scattered page writes.
- Compact. A record describes a change, not a whole page, so a small update produces a small record. (There is an exception for the first change to a page after a checkpoint, covered in a later chapter.)
- Complete. If the log contains everything needed to redo a change, the data page can be rewritten later, or rebuilt after a crash.
- Ordered. Records have a fixed order, so replaying them reproduces the same state.
Once the commit record is safely on disk, the transaction is durable. The dirty data pages can be written whenever convenient. If the server crashes first, startup recovery reads the log and reapplies the changes that never reached the data files.
The solid path is what the client waits for. The dashed path happens on its own schedule.
What the log buys you
The log solves each of the problems above.
| Problem | How the log addresses it |
|---|---|
| Random I/O at commit | Commit performs one sequential flush instead of many scattered page writes. |
| Hot pages written repeatedly | Pages stay in memory and are written once in a while. |
| Crash loses committed work | Recovery replays logged changes missing from the data files. |
| Partial transactions on disk | Recovery uses the log's commit records to know which transactions finished. |
PostgreSQL decides which transactions count as committed through a commit record in the log and a transaction status record, not by examining data pages. A row version written by an uncommitted transaction stays invisible, because visibility rules consult that status. So the stolen-page problem is handled by visibility, and the missing-page problem is handled by replay.
A rule that makes it work
The log only helps if it is on disk before the data it describes. Suppose a dirty page reached the data file, the machine crashed, and the log record describing that change was lost. Recovery would then have no record of a change that is already partly on disk.
The rule is write-ahead: a changed data page may be written to disk only after the WAL records describing that change have been flushed. This gives the technique its name. The next chapter covers it precisely.
Checking what your server does
You can look at the settings that control how hard PostgreSQL works to keep this promise. These commands are safe to run on any server:
SHOW fsync;
SHOW synchronous_commit;
SHOW full_page_writes;
SHOW wal_level;On a default installation you should see fsync as on, synchronous_commit as on, full_page_writes as on, and wal_level as replica. The next chapters explain each one.
Other uses of the same log
Because the log is a complete, ordered record of changes, it is useful beyond crash repair. Copying it elsewhere lets a standby server replay the same changes and stay current, which is streaming replication. Keeping old log files alongside a base backup lets you restore to any chosen moment, which is point-in-time recovery. A later chapter returns to both. For now, remember that crash recovery is the original purpose and the other features reuse it.
Summary
- Changes happen in shared memory first, and memory is lost in a crash.
- Writing all changed pages at commit is slow, writes hot pages repeatedly, and cannot make a multi-page change atomic.
- Delaying all writes is fast but loses committed data in a crash.
- PostgreSQL appends a description of each change to a sequential log and flushes only that log at commit. Data pages are written later, and recovery replays the log if needed.
Exercise
A transaction updates one row in a table and one row's entry in an index, then commits. Explain why PostgreSQL does not simply write the two changed data pages to disk before returning from COMMIT. Give two reasons.
Show answer
First, the two pages are in different files at different locations, so writing them is random I/O. A single sequential WAL flush is much cheaper. Second, two page writes are not atomic as a pair, so a crash between them leaves the heap and index inconsistent. Replaying the log restores both changes. A further reason is that the same pages are likely to be changed again soon, and keeping them in memory lets PostgreSQL write them once instead of at every commit.
Exercise
A server returns from COMMIT, then loses power. The data files on disk still contain the old version of the changed page. Why is the committed change not lost, and what condition must have been true when COMMIT returned?
Show answer
The WAL records for the change, including the commit record, were flushed to stable storage before COMMIT returned. On restart, recovery reads the log and reapplies the change to the page. The condition is that the WAL flush completed, which depends on fsync being on and synchronous_commit being on (or its equivalent).