Course contentsShow
← Computer Science
Lesson 1657 of 2,87238. Database Transactions and IndexingFree lesson

Transaction Logs and Write-Ahead Logging

Explore how databases use logs to record operations before applying them, enabling recovery and atomicity.

Transaction Logs and Write-Ahead Logging

You'll learn how databases record every change to a log file before applying it, ensuring recovery and atomicity even when disasters strike.

The Core Idea

Imagine you're updating your bank account balance from 100to100 to 150. What happens if the power goes out halfway through? Without a safety net, your data could be left in an inconsistent state—half-updated or corrupted.

This is where transaction logs and write-ahead logging (WAL) come in. Before the database modifies any actual data on disk, it writes a detailed record of the intended change to a special log file. This log entry is written and saved first—hence "write-ahead." Only after the log is safely on disk does the database proceed to modify the actual data.

Why This Matters

The log serves as a permanent, sequential record of every operation. If a crash occurs:

  • Before commit: The database can check the log during recovery, see the transaction never completed, and safely ignore those changes (supporting rollback).
  • After commit but before data is fully written: The database can replay the log entries to complete the modifications (supporting atomicity).

Think of it like writing instructions on paper before doing dangerous chemistry experiments—if something goes wrong, you can check your notes to see what happened and either undo it or finish it properly.

The WAL Protocol

  1. Write the operation to the log
  2. Ensure the log entry is saved to disk (flush)
  3. Perform the actual data modification
  4. Mark the transaction as committed in the log

This ordering guarantees that committed transactions survive crashes and uncommitted ones can be rolled back.

Key Takeaway: Write-Ahead Logging ensures transaction atomicity and recoverability by recording all changes to a durable log before applying them to the database, creating a safety net for both commit and rollback operations.