Video in progress
What is WAL, and why isn't committed data lost when the server suddenly goes down?
PostgreSQL first writes every change to the Write-Ahead Log, and at commit it only fsyncs the WAL to disk. The table pages are written later. After a crash, the database replays the WAL from the last checkpoint and recovers everything that was committed.
📖 Answer
Writing the table pages to disk on every commit would be very expensive: a single UPDATE touches several pages and indexes, all in different places on disk. The WAL, though, is a log written sequentially, so flushing it is cheap.
The commit sequence goes roughly like this:
- The changes happen in pages in
shared_buffers, and those pages are marked "dirty". - A WAL record is created for every change.
- On
COMMIT, the WAL is flushed to disk, and only then does the client get "OK". - The checkpointer and the background writer write the dirty pages to disk later.
If the server goes down, recovery reads the WAL from the last checkpoint and applies it to the pages. Uncommitted transactions simply stay invisible thanks to MVCC.
The WAL has other jobs too: streaming replication sends exactly this WAL to the replica, and PITR backup is also built on the WAL archive.
For speed you can set synchronous_commit = off: a commit doesn't wait for the WAL flush. After a crash, the commits of the last few hundred milliseconds may be lost, but the database isn't corrupted. fsync = off is a completely different thing: after a crash the database can be corrupted, and I never set it on prod.
Sign up to mark studied questions and save your progress.