Sub topic 1
Why a Database Needs a Log
Prerequisites
This chapter assumes you know basic SQL and psql, what a transaction is, and the ACID properties. You should also know that PostgreSQL stores table rows in fixed-size 8 KB pages on disk. Run the examples against a local test server.
The durability problem
A database must keep committed data after a crash, such as a power loss. A change first modifies data pages in memory (shared buffers), and those pages reach disk later. If the server crashed after a COMMIT but before its pages were written, the change would be lost. Writing every changed page to disk at each COMMIT would be safe but slow, because one update can touch many scattered pages.
PostgreSQL uses the write-ahead log (WAL), a sequence of records that describe each change. WAL is written sequentially and flushed to disk at commit.
The write-ahead rule: log first, data pages later
The write-ahead rule says a data page may reach disk only after the WAL records describing its changes have reached disk. Sequential log writes are much cheaper than random page writes, so commits stay fast. After a crash, PostgreSQL replays WAL to rebuild changes that were not yet in the data files.
WAL records and LSNs
Each change produces a WAL record. Each record has a log sequence number (LSN), which is its byte position in the WAL stream. LSNs print as two hexadecimal numbers separated by a slash, such as 0/1A2B3C4D. Run this query to see the current position:
SELECT pg_current_wal_lsn() AS current_lsn,
pg_walfile_name(pg_current_wal_lsn()) AS wal_file;Save an LSN before a statement, run the statement, then subtract with pg_wal_lsn_diff() to measure how much WAL it generated.
WAL segment files in pg_wal
WAL is stored as segment files in the pg_wal directory inside the data directory. By default each file is 16 MB. Its name, such as 000000010000000000000001, combines the timeline and the LSN range. The function pg_walfile_name() tells you which file holds a given LSN.
Exercise
Why does COMMIT stay fast even though data pages are written later?
Show answer
COMMIT only needs the WAL records flushed to disk. WAL is written sequentially, which is cheap. The scattered data page writes happen later, at checkpoints or through the background writer.