Databasemaxxing: Saving.. Do Not Turn Off The Console

Remember playing a game and saving would say 'Saving.. do not turn off the console', what would happen if the console did lose power during a save? Databases are synonymous with durability, as it's expected that nothing bad will ever happen.
A neat concept known as 'Write-Ahead Logging' was born to help solve this problem. The WAL records the changes needed to recover the database before those changes are written to the data files, providing the foundation for durability and crash recovery (and plays an important role in transaction atomicity!).
Database pages are typically larger than the underlying storage device's atomic write unit. Postgres typically uses 8kb pages, others might be 4kb or 16kb. If a failure interrupts a page write, only part of the page may reach disk, leaving a mixture of old and new data, resulting in the torn-write problem.
From here I'll use Postgres as the example DBMS.
There are 3 mechanisms that are good to know:
- WAL records -> Describe changes that Postgres needs to replay during recovery
- Full-page writes -> Protect against torn data-page writes
- Checkpoints -> Establish a recovery starting point and coordinate flushing dirty pages
WAL records help with assisting with capturing the details of the lower-level changes, not the sql statement being executed. It's critical that the records are successfully written to durable storage to be deemed durable, even if the corresponding data they reference wasn't as it's still living on dirty pages (because it can be replayed!).
Full-page writes are what will assist in recovering from torn writes. The best way to think of it is sometimes as you're interacting with Postgres, some of the statements may record to the log the additional information about the page a given tuple exists on.
Checkpoints establish a starting point for crash recovery. During a checkpoint, Postgres flushes dirty data pages to disk and writes a checkpoint record to WAL. Once the checkpoint completes, the changes covered by the checkpoint's redo position have been flushed. If a crash occurs, Postgres can begin recovery from the checkpoint's redo pointer rather than scanning the entire WAL history (which would be very slow!).
WAL records get assigned a log sequence number which corresponds to their ordering position. Keep in mind that e.g. a single INSERT doesn't generate a single WAL record and that there are also WAL records which aren't for physical changes, but outcomes (e.g. a WAL record for a transaction's COMMIT). A transaction can be considered durable only when the COMMIT WAL record has been flushed, the changes to the pages don't have to be and can still be dirty pages!
WAL records generated by a transaction
LSNs are also used to track page state for when the last WAL record that they were touched by. The cool thing about this, is that during recovery, if a page's LSN is already at or beyond the end LSN of the WAL record being replayed, the change has already been applied and can be skipped.
INSERT modifies page 0 for 'wal_example' table and holds the end LSN as the corresponding 1st WAL record in the list
Something fascinating about WAL is how it protects against torn writes. Full-page writes (enabled by default) cause Postgres to include a Full Page Image (FPI) in the WAL record for the first modification of a given page after a checkpoint.
This image provides a known-good copy of the page that can be restored during recovery if the corresponding on-disk page was only partially written. Further modifications to that same page generally only need to record their incremental changes until the next checkpoint.
Note: Although this capability is known as a 'full-page image', it doesn't necessarily occupy 8 KB in the WAL. Postgres can omit the unused space between the page's lower and upper boundaries, and the image can also be compressed.
Two INSERTs: the first includes FPI, whilst the second records only incremental changes with no FPI
Remember the HOT tuple article (https://x.com/ptr_to_joel/status/2122806100882075762)? Well, just like seeing HOT updates in pages, guess what you can see in the WAL!
WAL records generated by HOT and non-HOT update
Here's a simple crash recovery example. After starting up again from an 'unclean' shutdown, Postgres recovers to a consistent state on startup after processing the WAL from the latest checkpoint.
Running INSERTS then crashing Postgres and checking the logs on startup
From the startup logs, we can see that recovery begins at the redo pointer recorded by the previous checkpoint. Postgres then replays the available WAL records until it reaches the end of the valid WAL stream (indicated by the 'invalid record length' message stating 'expected at least 24, got 0'). This is expected when recovery reaches the end of available WAL and does not, by itself, indicate corruption.
Once the replay of the WAL is complete, then an end-of-recovery checkpoint is performed, flushing the recovered state and establishing a new recovery starting point!
The WAL isn't just critical for crash recovery, but the records themselves can be streamed to other servers in a distributed environment to maintain a copy of the primary database. So you can see that WAL enables a lot of benefits in ways more than one!