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!).
Learning outcomes
- Explain exact durability ordering (
WAL page LSN synced to storage BEFORE dirty heap page writes) plusfull_page_writesdefense against torn8 KiBpages cleanly during OS crashes! - Tune
max_wal_size,checkpoint_timeout, andcheckpoint_completion_target = 0.9cleanly 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 failingarchive_commandscripts 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 Parameter | Operational Trade-Off | Healthy Production Range | Hazard 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 permanently | off 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 checkpoint | 0.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_size | Caps how much WAL an offline standby/Debezium replication slot can pin indefinitely | Explicitly 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 sizeSELECT 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_walFROM pg_replication_slotsORDER 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 = offfor Synthetic Speed: Disabling kernelfsynclets 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_sizeCausing FPI Storms: Tight1 GBWAL caps force checkpoints every few minutes cleanly under heavy writes, multiplying compressed Full Page Image WAL bytes cleanly (3x–5xextra disk write amplification!). - Mixing Up
synchronous_commit = offWithfsync = off:synchronous_commit = offmerely acknowledges transactions asynchronously while preserving complete torn-page and WAL integrity cleanly (at worst truncating tail seconds);fsync = offdestroys 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!