interviewpath
  • 0day streak
  • 10total XP
  • Level 1
0/6

Unit 6 · Databases · Lesson 3 of 10

Write-ahead logging, recovery and durability

Write-ahead logging is how databases make commits atomic and durable despite crashes: log records reach stable storage before the pages they describe, and recovery replays or undoes work from the log. Understanding WAL, checkpoints and what fsync really guarantees lets you reason about data-loss windows, replication and storage-engine design.
About 4 hFocus mode

Step 1: Learn the ideas

  • Failure model: crash-stop, lost volatile state, durable but slow storage
  • Buffer policies: steal/no-steal and force/no-force
  • Write-ahead logging, log sequence numbers and the commit record
  • Physical, logical and physiological log records
  • Checkpoints (sharp and fuzzy) and log truncation
  • ARIES: analysis, redo, undo and compensation log records
  • Group commit and asynchronous commit
  • fsync, device write caches, torn pages and full-page writes
  • Rollback journals (SQLite) versus shadow paging and copy-on-write designs
  • Archiving, point-in-time recovery and log shipping

Why it matters

"Committed" is a promise that must survive a power cut. Keeping it cheaply is the job of the log, and the same log also feeds replication, change-data capture and point-in-time recovery. Understanding it explains everyday operational facts: commit latency follows disk flush latency, restarting after a crash can take minutes, and turning off fsync makes benchmarks fast and data unsafe.

Core ideas

Buffer policy. Pages are changed in the buffer pool and written back later. A steal policy lets the buffer manager write a page containing uncommitted changes, so recovery needs undo. A no-force policy lets a transaction commit without writing its dirty pages, so recovery needs redo. Steal plus no-force gives the buffer manager freedom and turns each commit into a small sequential log write, at the price of supporting both.

Two rules. Write-ahead: the log record describing a change must be durable before the changed page may overwrite its on-disk version. Commit: all of a transaction's log records, including the commit record, must be durable before commit is acknowledged. Every record has a log sequence number (LSN); every page stores the LSN of the last change applied to it (pageLSN), and the buffer manager flushes the log up to pageLSN before writing the page.

Checkpoints. Without them recovery would scan the whole log. A fuzzy checkpoint records the active transactions and the dirty pages, with the earliest LSN that might still need redo, without stopping normal work. Recovery starts from there, and older log segments can be recycled or archived. Frequent checkpoints shorten recovery but write more. PostgreSQL also logs a full image of each page on its first change after a checkpoint, so a torn, half-written page can be repaired from the log.

ARIES at intuition level.

  1. Analysis: starting at the last checkpoint, rebuild the tables of active transactions and dirty pages.
  2. Redo: from the smallest recovery LSN, reapply every logged change whose page does not yet reflect it (pageLSN smaller than the record's LSN), including changes of transactions that will be rolled back. This "repeats history".
  3. Undo: roll back transactions without a commit record, newest change first, writing compensation log records (CLRs) so that a crash during recovery never undoes the same change twice. Repeating history first means undo always operates on a consistent state, which is what allows record-level locking and logical undo.

Durability assumptions. fsync (or fdatasync, or O_DSYNC writes) asks the OS to push data and required metadata to the device, and the device to make it persistent. Each link can fail: drives with volatile write caches that do not honor flush commands, file systems that reorder writes, and fsync errors after which the kernel has already dropped the dirty pages, so that a retried fsync "succeeds" without the data. PostgreSQL responded to the last case by treating an fsync failure as a crash (PANIC) and recovering from WAL instead of retrying. Replication changes the question from "on this disk" to "on how many machines", and waiting for a synchronous replica adds a network round trip to every commit.

Throughput knobs. Group commit flushes several transactions' commit records together, raising throughput while each transaction still waits for a flush. Asynchronous commit (synchronous_commit = off in PostgreSQL) acknowledges before the flush: the database stays consistent after a crash, but a short window of acknowledged transactions can be lost. fsync = off is different and dangerous: a crash can leave the database corrupted.

Other designs. SQLite's default rollback journal saves original page contents to a journal before changing the database file in place (undo logging). Its WAL mode appends new page versions to a separate file and copies them back at checkpoints (redo logging), so readers continue while one writer appends. LSM-tree engines log memtable inserts and treat their immutable sorted files as the durable state.

Common misconceptions

  • "COMMIT returned, so the data is on disk." Only if the log was flushed and the device honored the flush; asynchronous commit and lying caches break this.
  • "The WAL exists only for crash recovery." The same stream drives physical replication, point-in-time recovery and logical decoding.
  • "Checkpoints make commits durable." Log records make commits durable; checkpoints bound recovery work and allow log recycling.
  • "Retrying fsync after an error is safe." On several systems the failed write-back is forgotten and the retry reports success.
  • "Recovery undoes losers first, then redoes winners." ARIES redoes everything first, then undoes losers.

How to approach it

Build the model on paper: a buffer pool, a log with LSNs and a crash at an awkward moment, then recover by hand. Read SQLite's atomic-commit page, which walks through every step and names each failure point. In interviews, answer durability questions along the whole chain (application, database log, OS, device, replicas) and name the setting you would change and what it costs. Storage and research roles may ask you to justify each LSN check or to evaluate a new logging scheme, so practice explaining why each rule exists.

Suggested order

  1. 1Read OSTEP Ch. 42 (Crash Consistency: FSCK and Journaling) to recall why the order of writes matters at the file-system level.
  2. 2Read CMU 15-445 Fall 2025 Lecture #21 notes (Database Logging): buffer policies, WAL, logging schemes and checkpoints.
  3. 3Read Lecture #22 notes (Database Recovery) and trace ARIES on a small log with a crash in the middle of undo.
  4. 4Read SQLite’s Atomic Commit In SQLite page, then its Write-Ahead Logging page, listing every point where a crash could occur and what saves the data.
  5. 5Read the PostgreSQL WAL chapter pages: Reliability, Write-Ahead Logging (WAL), Asynchronous Commit and WAL Configuration.
  6. 6Read the PostgreSQL wiki page on fsync errors and explain why the project switched to treating fsync failure as a crash.

Step 2: Check off what you can do

Tap each one you can genuinely do or explain. Each earns 10 XP.

Step 3: Go deeper

  • CMU 15-445/645 Intro to Database SystemsStart here

    Carnegie Mellon University Database Group

    Section: Fall 2025 Lecture #22: Database Recovery (notes)

    ARIES analysis, redo and undo with LSNs, checkpoints and compensation records; read Lecture #21 (Database Logging) first.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • SQLite documentation: commit protocol, WAL, file format and query planningStart here

    SQLite (sqlite.org)

    Section: Atomic Commit In SQLite

    A real commit protocol explained step by step, with the hardware and OS assumptions it depends on; continue with the Write-Ahead Logging page.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • PostgreSQL documentation: Transaction Isolation

    PostgreSQL Global Development Group

    Section: Write-Ahead Logging (WAL)

    How PostgreSQL applies the WAL rule; the neighboring Reliability, Asynchronous Commit and WAL Configuration pages cover flushes, caches and checkpoints.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Operating Systems: Three Easy Pieces

    University of Wisconsin–Madison (free online book)

    Section: Ch. 42: Crash Consistency: FSCK and Journaling

    File-system journaling as a simpler relative of database logging; clarifies write ordering and checkpointing.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • PostgreSQL wiki: Fsync Errors

    PostgreSQL wiki

    How write-back errors are reported, and sometimes lost, by operating systems, and how PostgreSQL changed its error handling.

    Open(opens in a new tab)Link responded, 5 Oct 2026

Step 4: Practice

Build the crash-tested store: a log with checksummed records, an fsync per commit, replay on startup, and a loop that kills the process at random moments and checks every acknowledged key after restart. Then measure commit latency with an fsync per commit, with several commits per flush (group commit) and without fsync, and explain what each setting risks. On PostgreSQL, compare pgbench throughput with synchronous_commit on and off and state exactly what a crash could lose in each case.

Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).

Step 5: Test yourself

Answer each one out loud or on paper before you finish the lesson.

  1. Question 1Why must the log be flushed up to a page’s pageLSN before that page is written back?
  2. Question 2What does a fuzzy checkpoint record, and where does redo start?
  3. Question 3Why does ARIES redo changes made by transactions it will later undo?
  4. Question 4What problem do full-page writes solve, and why only on the first change after a checkpoint?
  5. Question 5How does group commit raise throughput without weakening durability?
  6. Question 6What can go wrong if an application retries fsync after it fails?

You’re done when you can

  • Recover a hand-written ARIES log with a crash during undo, producing the correct final state and the compensation records written.
  • Explain in under two minutes why steal plus no-force requires both undo and redo.
  • Build and crash-test a small WAL-backed store and report whether any acknowledged write was lost.
  • State without notes what synchronous_commit = off and fsync = off each risk.

Finish the lesson

How confident do you feel?

Lesson complete!

+50 XP

Reviews will come up on the Practice tab so it sticks.

Your notes and study time

Log study time