FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Write-Ahead Logging (WAL) & Crash Recovery

Write-Ahead Logging architecture, LSN sequence numbers, checkpointing, and point-in-time recovery.

Freshness: current•15 min read•Data Engineering and Databases

Key Learning Outcomes

  • ✓Trace WAL LSN record writes during transactions
  • ✓Configure checkpoint intervals for high-write workloads
Full Technical Reference Document

Mental model

Randomly flushing modified 8 KiB heap and index data pages directly to disk on every SQL COMMIT would destroy I/O throughput and corrupt partial disk blocks during sudden power outages. Write-Ahead Logging (WAL) guarantees ACID durability (D) cleanly by appending compact sequential redo records identified by monotonic 64-bit LSN (Log Sequence Numbers) into disk WAL segments (fsync()ed on commit before heap pages flush asynchronously later via background CHECKPOINT writers!).

Tx mutates shared buffer page (sets LSN)
Append compact change record to WAL buffer
COMMIT flushes WAL sequentially via fsync
Background checkpointer flushes dirty heap
Crash? REDO WAL forwards from last REDO LSN
Conceptual teaching model synthesized from:PostgreSQL 16 Architecture, MVCC & Query Optimization ManualDesigning Data-Intensive Applications: Replication, Transactions and Distributed State

Learning outcomes

  • Explain exact durability ordering (WAL page LSN synced to storage BEFORE dirty heap page writes) plus full_page_writes defense against torn 8 KiB pages cleanly during OS crashes!
  • Tune max_wal_size, checkpoint_timeout, and checkpoint_completion_target = 0.9 cleanly to prevent periodic disk I/O spike stalls ("checkpoint storms")!
  • Diagnose and remediate runaway pg_wal/ disk full crashes cleanly caused by dead/abandoned replication slots or failing archive_command scripts cleanly.

Theory

Notice a crucial subtle trade-off right at the heart of PostgreSQL's 8 KiB storage engine: OS disk controllers write physical storage in 512 B or 4 KiB sectors, half a 8 KiB Postgres page! If power drops halfway through flushing a dirty heap page (a torn 4K/8K page), plain logical delta redo records ("add 5 to offset 200") cannot fix broken checksums on torn binary pages! Setting full_page_writes = on (default) forces Postgres cleanly to log an entire compressed 8 KiB full page image (FPI) inside WAL upon a page's very first modification following every checkpoint—explaining why tuning checkpoints too frequently (tiny max_wal_size) explodes WAL disk writes cleanly!!

WAL Configuration ParameterOperational Trade-OffHealthy Production RangeHazard When Misconfigured
synchronous_commit (on vs local vs off)Guarantees client never sees "Committed" before WAL hits disk (or sync replica!)on for financial/auth state; off selective per-tx for transient telemetry (SET LOCAL)off risks losing up to 3 * wal_writer_delay (~600ms) committed data on OS crash (zero corruption though!)
fsync = on (vs off)Mandatory hardware disk durability barrier (NEVER set off in production!)Strictly on permanentlyoff corrupts physical page structure irreparably upon host crash!
checkpoint_completion_target (0.9)Spreads dirty page writes cleanly evenly over 90% of the interval until next checkpoint0.9 + generous max_wal_size (8–32 GB+)Low target / small max_wal_size causes sudden I/O saturation spikes + FPI bloat cleanly
max_slot_wal_keep_sizeCaps how much WAL an offline standby/Debezium replication slot can pin indefinitelyExplicitly capped (e.g. 20 GB) + alert triggers-1 (unlimited) fills pg_wal strictly to 100% ENOSPC, halting Postgres completely!
sql
-- 1. Inspect current WAL position, archive queue health, and retained WAL size
SELECT pg_current_wal_lsn() AS current_lsn,
(SELECT count(*) FROM pg_ls_waldir()) * 16 AS estimated_wal_mb;
​
-- 2. Detect abandoned replication slots pinning huge un-recycled pg_wal/ files!
SELECT slot_name, slot_type, active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS pinned_wal
FROM pg_replication_slots
ORDER BY pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) DESC;
​
-- 3. Per-transaction async speed optimization without risking whole-cluster corruption:
BEGIN;
SET LOCAL synchronous_commit = off;
INSERT INTO telemetry_events (payload) VALUES ('{"lat_ms": 42}');
COMMIT;

Trade-offs

Using sequential Write-Ahead Logs paired cleanly with full_page_writes = on guarantees rock-solid crash consistency and unlocks Continuous Archiving + Point-In-Time Recovery (PITR cleanly back to any second!) alongside streaming physical and logical replication cleanly. Keeping synchronous_commit = on trades single-digit NVMe/EBS fsync millisecond commit latency on writes for zero lost committed transactions—while selectively running SET LOCAL synchronous_commit = off solely on non-critical metrics or telemetry batches boosts throughput dramatically cleanly without risking database corruption like disabling global fsync = off cleanly does!

Failure modes and misconceptions

  • Setting Global fsync = off for Synthetic Speed: Disabling kernel fsync lets dirty heap buffers flush ahead of un-flushed WAL records, leaving completely corrupted un-recoverable database clusters after kernel panics cleanly!
  • Abandoned Debezium / Replica Replication Slots Without max_slot_wal_keep_size: When a downstream CDC consumer disconnects cleanly for 3 days, Postgres retains every WAL segment since disconnect (pg_wal/ hits 100% disk -> immediate database emergency shutdown!).
  • Undersized max_wal_size Causing FPI Storms: Tight 1 GB WAL caps force checkpoints every few minutes cleanly under heavy writes, multiplying compressed Full Page Image WAL bytes cleanly (3x–5x extra disk write amplification!).
  • Mixing Up synchronous_commit = off With fsync = off: synchronous_commit = off merely acknowledges transactions asynchronously while preserving complete torn-page and WAL integrity cleanly (at worst truncating tail seconds); fsync = off destroys structural page integrity cleanly!

Decision scenario

A primary PostgreSQL analytics & AI ledger database suffers extreme disk I/O pauses every 4 minutes cleanly during ingestion bursts (dstat shows huge 15-second write spikes!), and pg_wal/ suddenly jumped 45 GB overnight after staging CDC tests died cleanly! Increase max_wal_size = 16GB with checkpoint_completion_target = 0.9 to eliminate FPI checkpoint storms cleanly, cap max_slot_wal_keep_size = '15GB' cleanly + drop dead replication slots cleanly (pg_drop_replication_slot), and apply SET LOCAL synchronous_commit = off strictly cleanly inside telemetry batch sessions while preserving fsync = on permanently cleanly!

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next