← Lessons

quiz vs the machine

Silver1120

Databases

Write Ahead Log Internals

Why every change is logged before the data page hits disk.

5 min read · intro · beat Silver to climb

Log Before Data

The write ahead log (WAL) enforces one rule: the log record describing a change must reach durable storage before the changed data page is written. This is what lets a database survive a crash without losing committed work.

Records and the LSN

Each change produces a log record stamped with a monotonically increasing log sequence number (LSN). Each page also stores the LSN of the last change applied to it.

  • On commit, the log up to that transaction is flushed to disk.
  • A page may stay dirty in memory long after commit because the log already protects it.
  • The page LSN tells recovery whether a logged change is already present on the page.

The WAL Buffer

Log records first land in an in memory WAL buffer, then are written sequentially. Sequential log writes are far cheaper than scattered random data writes, so logging adds little overhead.

Key idea

The WAL writes a log record with an LSN before the data page, flushes the log on commit, and uses page LSNs so recovery knows which changes already reached the page.

Check yourself

Answer to earn rating on the learn ladder.

1. What does the write ahead rule require?

2. What is stored on a page to help recovery?

3. Why is logging cheap despite happening for every change?