In this lesson, you will learn how the Write-Ahead Log (WAL) acts as a safety net to ensure your database remains consistent and atomic, even if the power cuts out unexpectedly.
The Problem: Memory vs. Disk
When you update data, the database doesn't immediately write the change to the permanent storage files (the "data pages"). Doing so would be incredibly slow because disk drives prefer writing large, sequential chunks of data rather than jumping around to small, random memory addresses. Instead, the database performs the update in high-speed RAM.
But what happens if the system crashes before that RAM is saved to the disk? You would lose your transaction, violating the Atomicity guarantee.
The Solution: Sequential Appends
To solve this, the database uses a Write-Ahead Log (WAL). Before any change is made to the actual data pages, the database writes a description of the change as a simple, sequential append to the end of a log file on disk.
Because the log is sequential, writing to it is extremely fast—the disk head doesn't have to seek around. Think of it like a ledger where you simply add a new line at the bottom:
-- Conceptual log entries
1. [LSN 001] UPDATE Account SET Balance = 500 WHERE ID = 1;
2. [LSN 002] UPDATE Account SET Balance = 1500 WHERE ID = 2;
Guarantees During Restart
When the system restarts after a crash, the database looks at this log. This process is called Recovery:
- Redo: The system scans the log from the last successful "checkpoint." It replays the logged actions to reconstruct the state of the data in memory, ensuring that any committed transaction that hadn't reached the disk yet is finalized.
- Undo: If the log shows a transaction was in progress but never finished (no "commit" record), the database reverses those partial changes.
Because the log acts as a single, immutable source of truth written in order, the database can effectively "travel back in time" to the exact moment of the crash and reconstruct the state, ensuring that transactions are either fully applied or fully ignored.
Key Takeaway: The Write-Ahead Log guarantees atomicity by forcing every change to be recorded in a fast, sequential append-only file before data pages are updated, allowing the system to replay or revert operations during a recovery.