1 of 4

Your RightSignal

How databases work · 4 of 91 / 3

Write-ahead logging

The concept

Why a database survives a power cut in the middle of a save

With write-ahead logging (WAL), the database appends a note of each change to a separate log file, and that note reaches disk before the data page does. So a crash between a transfer's two page writes can't leave a mess.

Each log record gets a rising number, its log sequence number (LSN), and each page stores the LSN of its last change. A transaction is committed once its commit record is flushed, meaning confirmed as written to disk.

The changed pages themselves can stay in memory and be written out later.

What it’s forThe one rule the database must follow before writing any changed page from memory to disk.

write page P only if flushedLSN ≥ pageLSN(P)

P
a data page changed in memory, e.g. one 8 KB B-tree page
pageLSN(P)
the LSN of the most recent log record that changed page P
flushedLSN
the highest LSN the log has safely written to disk so far

What it givesA guarantee that no change ever reaches the data files before the log record that explains it.

  1. Log flushed up to LSN 120; page A has pageLSN 118 → 120 ≥ 118, A may be written.
  2. Page B has pageLSN 125 → 120 < 125, so the log must be flushed to at least 125 first.