In this lesson, you will learn how PostgreSQL guarantees that your data survives a sudden system crash by writing intent before action.
The Problem: Memory vs. Disk
In PostgreSQL, modifying data directly on the data files (the actual tables) is extremely slow because disks perform best with sequential writes, while database updates are often random. To solve this, PostgreSQL performs all changes in memory (the Shared Buffer Cache). However, if the power cuts out, everything in that memory is lost.
The Solution: Write-Ahead Logging (WAL)
Write-Ahead Logging follows a simple golden rule: Before any change is made to the actual data files on disk, a record describing that change must be flushed to the WAL.
Think of the WAL as a "ledger of intent." When you execute an UPDATE statement, the following steps occur:
- Modify in Memory: The system changes the row in the
Shared Buffer Cache. - Log the Intent: A record describing this change is appended to the WAL buffer.
- Commit: When you issue a
COMMIT, the database forces the WAL buffer to be flushed to permanent disk storage.
Crucially, the actual data files are updated in the background later (a process called "checkpointing"). If the system crashes before the background process finishes, PostgreSQL doesn't care. Upon restart, it simply reads the WAL file from the last known checkpoint and "replays" the logs to reconstruct the state of the data in memory.
Illustrating the Flow
Imagine you run this:
UPDATE accounts SET balance = 500 WHERE id = 1;
- Step 1: The
balanceis updated to500in the memory page. - Step 2: An entry is written to the WAL: "Transaction X modified block Y at offset Z to set value 500."
- Step 3: The WAL record hits the disk.
- Step 4: The database tells you "Success!"
If the server loses power one microsecond later, your data is safe. Even if the data file on disk still says balance = 100, the system will use the WAL record to restore the 500 upon reboot.
Key Takeaway: Write-Ahead Logging ensures durability by guaranteeing that a description of every change is safely persisted to disk before the actual data files are ever modified.