WAL Basics
Learning Focus
Use this lesson to understand PostgreSQL WAL and why it is the foundation for durability, recovery, and replication.
Concept Overview
WAL (Write-Ahead Log) records changes before data files are updated.
This enables:
- crash recovery
- physical replication
- point-in-time recovery (PITR) when WAL is archived
Key Ideas
| Concept | Meaning |
|---|---|
| WAL segment | a file containing a portion of WAL history |
| LSN | log sequence number (position in WAL) |
| checkpoint | point where dirty pages are flushed and WAL can be recycled |
Useful Observability Queries
SELECT pg_current_wal_lsn();
SELECT pg_walfile_name(pg_current_wal_lsn());
Force a WAL segment switch (ops use):
SELECT pg_switch_wal();
Common Mistakes & Troubleshooting
| Mistake | Risk | Fix |
|---|---|---|
| Treating replication as a backup | Corruption replicates | Keep independent backups |
| Not archiving WAL but expecting PITR | Cannot restore to a specific point | Enable WAL archiving |
Quick Reference
pg_current_wal_lsn()
pg_switch_wal()