Explain write-ahead logging for atomicity and durability. Why must log records flush before data pages? How does redo recovery fix crashes after log flush but before data flush?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great comprehensive question about Write-Ahead Logging (WAL), a fundamental concept in database systems for ensuring ACID properties, specifically atomicity and durability. Let me break this down systematically.
Write-Ahead Logging (WAL) Overview
WAL is a mechanism used by databases to ensure:
Atomicity - transactions either fully complete or don't execute at all
Durability - committed data survives system failures
The Core Principle
The fundamental principle of WAL is: log records must be written to persistent storage before the corresponding data pages are written.
This is often called the "Write-Ahead Logging protocol" or "Force Logging" principle.
The Problem WAL Solves
Without WAL, consider this scenario:
Transaction T1 modifies page X
System crashes
Page X is partially written
After recovery, we don't know:
What the original value was
What the new value should be
Whether T1 committed
How WAL Ensures Atomicity and Durability
1. Atomicity through Logging
Before modifying a data page, the database:
Creates a log record containing:
Transaction ID
Old value (undo log)
New value (redo log)
LSN (Log Sequence Number)
Writes to volatile buffer
Once all log records for a transaction are flushed, transaction can commit
Data pages are modified (eventually flushed, but timing doesn't matter)
This ensures:
If crash happens before log flush: changes are undone (rolled back)
If crash happens after log flush: changes are redone (rolled forward)
2. Durability through Forced Log Flush
When transaction commits:
All log records must be flushed to persistent storage (disk)
Only then can the transaction be acknowledged as committed
Data pages are written lazily (can be much later)
Why Log Records Must Flush Before Data Pages
The critical ordering requirement exists because if a data page reaches disk before its corresponding log record, a crash leaves us with modified data but no record of what changed or whether the transaction actually committed. This breaks recovery entirely—we can't undo incomplete transactions or redo committed ones. By forcing the log to disk first, we guarantee that after any crash, we have enough information to restore the database to a consistent state.
When the log is safely written before data pages, recovery becomes straightforward: we can replay committed operations from the log to reconstruct any data pages that were lost in the crash.
Recovery Process: Redo Recovery
After a crash, the database executes a multi-phase recovery:
Phase 1: Analysis
Scanning the log from the last checkpoint forward identifies which transactions were in-flight at the crash, which pages need updating, and which transactions successfully committed.
Phase 2: Redo Phase (Forward Recovery)
Starting from the checkpoint, the system replays all committed transactions to restore any data pages that weren't flushed before the crash.
code
for each log record in order:
if (transaction committed):
apply the redo log (new value)
write data page to disk
write LSN
This forward pass ensures all committed work is restored, which is why it's called "redo"—we're reapplying changes that were logged but potentially lost.
Phase 3: Undo Phase (Backward Recovery)
Moving backward through the log, the system removes any partial changes from transactions that never committed, restoring the database to a clean state.
Specific Scenario: Log Flush But Before Data Flush
When a transaction modifies a page and its log record reaches disk before the data page does, a crash leaves the log intact but the page unchanged. During recovery, the redo phase replays that logged operation, writing the new value back to the page and restoring consistency.
code
Timeline:
1. T1: BEGIN
2. T1: UPDATE page X (old value = 100, new value = 200)
3. Log record created: <T1, X, 100, 200, LSN=500>
4. Log buffer flushed to disk [LOG IS DURABLE]
5. Data page X modified in buffer (contains 200)
6. CRASH! [Data page X not yet flushed to disk]
7. Recovery begins...
After Recovery:
- We read the log from checkpoint
- We encounter log record: <T1, X, 100, 200, LSN=500>
- We check if T1 committed: YES (log record was flushed)
- We apply REDO: Write page X = 200 to disk
- Result: Consistent state, durability maintained
When the system crashes after flushing LSN 100-105 to the log but before any data pages reach disk, recovery identifies T1 as committed and reapplies its changes (PageA = 20), while undoing T2's modifications since it never committed (reverting PageB to 30 and PageC to 50). This ordering ensures that the log always contains enough information to restore consistency—if data were written before the log, a crash could leave pages in an inconsistent state with no record of what they should contain.
The implementation prioritizes log durability: modifications are buffered, log records are created and force-flushed to disk via fsync, the transaction is marked committed, and only then are data pages lazily written in batches. Each page tracks its pageLSN to identify which log records apply to it during recovery, allowing the system to skip pages already safely persisted while redoing changes for pages that weren't flushed. This approach balances correctness with performance—batching data writes is efficient, and the log guarantee means data pages can be delayed without risking inconsistency.
The core principle is that log records must reach disk before their corresponding data pages. This ensures that during recovery, if a page wasn't flushed, its modifications are available in the log to replay. The invariant logFlushLSN ≥ pageLSN must hold before any data page is written, preventing a scenario where a page hits disk but its changes aren't logged.
Different failure modes illustrate this: if a transaction commits and the log flushes but the data page hasn't yet been written, recovery can redo the changes from the log. If a transaction never committed and crashes, any uncommitted changes on disk get undone. The system maintains consistency by ensuring the log always leads the data.
Write-Ahead Logging (WAL) for Atomicity and Durability
Core Principle
Log records must be written to persistent storage BEFORE corresponding data pages. This is the fundamental rule that makes WAL work.
code
Timeline of Operations:
1. Modify page in memory buffer
2. Create log record (contains old & new values)
3. ★ FLUSH LOG RECORD TO DISK (forced)
4. Acknowledge commit to client
5. Eventually flush data page to disk (lazy, any time)
Why Log Records Must Flush First
❌ Wrong Way: Data Before Log
code
Thread 1:
- Page X modified (value: 100 → 200)
- Data page X flushed to disk [Page X = 200]
- CRASH !
- Log record never written
Recovery:
- Page X has value 200 on disk
- No log record exists
- System doesn't know:
* What the original value was (100)
* If this transaction committed
* What to do on recovery
→ INCONSISTENT & UNRECOVERABLE
✅ Correct Way: Log Before Data
code
Thread 1:
- Page X modified (value: 100 → 200)
- Log record written: <T1, X, oldval=100, newval=200, LSN=504>
- Log flushed to disk [LOG IS DURABLE]
- CRASH !
- Data page X never flushed to disk
Recovery:
- Read log from checkpoint forward
- Find: T1 committed (commit record in log)
- Execute REDO: write Page X = 200 to disk
→ CONSISTENT & RECOVERABLE
Key insight: The log is the source of truth about what should be on disk.
Redo Recovery: Fixing Crashes After Log Flush (Before Data Flush)
Recovery Has Three Phases
Phase 1: Analysis
Scan the log to identify:
Which transactions committed
Which data pages were modified (need redo)
Last checkpoint location
code
Log scan result:
- T5 committed (commit record found)
- T7 uncommitted (no commit record → need undo)
- Dirty pages: {A, B, C}
Phase 2: Redo (Forward Pass)
Replay all committed operations forward from checkpoint:
code
for each log record (in forward order):
if (transaction COMMITTED):
apply the operation (write new value)
update page on disk
update page's LSN
Why this works:
Even though data page wasn't on disk at crash
Log proves transaction committed
Replaying log record restores the change
Phase 3: Undo (Backward Pass)
Roll back uncommitted transactions:
code
for each log record (in reverse order):
if (transaction NOT committed):
apply undo log (restore old value)
write updated page to disk
Complete Example: Crash Scenarios
Scenario A: Committed Transaction, Data Not Flushed
code
Timeline:
LSN 100: <T1 START>
LSN 101: <T1, PageA, undo=10, redo=20> ← old value, new value
LSN 102: <T1 COMMIT>
[All log entries forced to disk]
*** CRASH *** [PageA still in buffer with value 20]
Recovery Redo Phase:
1. Read log forward
2. See T1 COMMIT record → transaction committed
3. For LSN 101: apply redo
UPDATE PageA = 20
4. Result: PageA on disk has value 20 ✓
Scenario B: Uncommitted Transaction, Data Partially Flushed
code
Timeline:
LSN 200: <T2 START>
LSN 201: <T2, PageB, undo=30, redo=40>
[LSN 201 flushed to log, but NO commit yet]
[PageB flushed to disk with value 40]
*** CRASH *** [T2 never committed]
Recovery:
Analysis: T2 in undo log (no commit record)
Undo Phase:
1. Scan log backward
2. Find LSN 201 belongs to uncommitted T2
3. Apply UNDO: restore PageB = 30
4. Result: PageB on disk has value 30 ✓
Buffer State Before Crash:
T1: COMMIT record in log [Durable]
T2: Changes in log [Durable]
T3: Changes in buffer only [Lost on crash]
PageA: flushed (T1 changes)
PageB: in buffer (T2 changes)
PageC: in buffer (T3 changes)
Redo Phase (T1, T2 committed):
- T1 changes: re-apply to PageA
- T2 changes: apply to PageB (was only in log)
Undo Phase (T3 uncommitted):
- T3: never started log record beyond BEGIN
- Nothing to undo for T3
The Critical WAL Invariant
code
BEFORE flushing PageX to disk:
ALL log records that modified PageX
MUST already be flushed to persistent storage
logFlushLSN ≥ dirtyPageLSN (always true at flush time)
In code:
c
// When page needs to flushed
void flushPage(Page* page) {
// Precondition
assert(logFlushLSN >= page->LSN);
// Now safe to flush
writePageToDisk(page);
}
Why Not Always Flush Data Immediately?
Approach
Pros
Cons
Flush data immediately
Simple
Slow (random disk I/O)
Lazy flush (with WAL)
Fast (batch writes), durable
Complex recovery
WAL allows:
✅ Multiple transactions to modify same page
✅ Batch multiple dirty pages into single disk write
✅ Maintain durability even with delayed data flushes
Recovery Algorithm Pseudocode
python
def recover():
# Phase 1: Analysis
latest_checkpoint = read_last_checkpoint()
committed_txns = set()
dirty_pages = {}
for log_record in read_log(from=latest_checkpoint):
if log_record.type == COMMIT:
committed_txns.add(log_record.txn_id)
if log_record.type in [INSERT, UPDATE, DELETE]:
page_id = log_record.page_id
dirty_pages[page_id] = log_record.LSN
# Phase 2: Redo (forward pass)
for log_record in read_log(from=latest_checkpoint):
if log_record.txn_id in committed_txns:
if log_record.type in [INSERT, UPDATE, DELETE]:
# Apply redo: write the new value
apply_redo(log_record)
update_disk(log_record.page_id, log_record.new_value)
# Phase 3: Undo (backward pass)
for log_record in read_log_backward(from=end_of_log):
if log_record.txn_id NOT in committed_txns:
if log_record.type in [INSERT, UPDATE, DELETE]:
# Apply undo: write the old value
apply_undo(log_record)
update_disk(log_record.page_id, log_record.old_value)
Summary Table
When Crash Occurs
Log Flushed
Data Flushed
Recovery Action
Before log flush
❌
❌
Changes lost (abort txn)
After log flush, before data flush
✅
❌
REDO apply log record
After data flush
✅
✅
Already on disk, verify LSN
The beauty of WAL: Durability is guaranteed by log flush alone. Data flushes can happen whenever convenient, and recovery will fix any gaps.