🐘 PostgreSQL Intermediate

What is WAL (Write-Ahead Logging) in PostgreSQL?

Answer

WAL (Write-Ahead Logging) is the mechanism PostgreSQL uses to ensure data durability and enable crash recovery. Before modifying any data page, PostgreSQL writes a log record to the WAL (in pg_wal/) first. On crash, PostgreSQL replays WAL records to restore a consistent state. WAL is also the basis for replication — streaming replication ships WAL records to standby servers. Key concepts: LSN (Log Sequence Number — position in WAL), checkpoint (periodic sync of dirty pages to disk — reduces crash recovery time), wal_level (minimal/replica/logical), archive_mode (copy WAL files for PITR — Point-In-Time Recovery). WAL ensures durability with synchronous_commit = on. Setting it to off improves throughput but risks recent data loss on crash.