Database.Middle.Explain write-ahead logging (WAL).

📘 What is Write-Ahead Logging (WAL)?

Write-Ahead Logging is a safety mechanism used by databases to protect your data from being lost or corrupted.

💡 The key idea:
Write changes to a log before applying them to the actual database.


🧠 Why Do We Need WAL?

Imagine this:

  • You’re updating a user’s balance in a database.
  • The system crashes halfway through.
  • How do we recover? How do we know what changed?

With WAL, the database remembers what it was going to do, so it can replay or undo those changes after a crash.


🔁 Step-by-Step Example (with WAL)

Let’s say you’re updating a row in a PostgreSQL database.

1. You run:

UPDATE users SET balance = balance - 100 WHERE id = 42;

2. The database does:

Step 1: Write the change to the WAL file (on disk):

"User 42 balance will be decreased by 100"

Step 2: Apply the change to the actual data file (in memory or disk).

Step 3: Once both are successful, the transaction is committed.

💥 What if the system crashes?

  • If only WAL was written ✅ but the actual data wasn’t yet updated:
    • 🛠 The database uses WAL to replay the change.
  • If WAL wasn’t written at all ❌:
    • The transaction is discarded (it never “existed”).

✅ This ensures Atomicity and Durability (remember ACID?).

📦 Where Is WAL Used?

SystemWAL Usage Purpose
PostgreSQLAll transactions use WAL for recovery
MySQL (InnoDB)Uses redo logs (similar to WAL)
SQLiteWAL is a journal mode for durability
KafkaUses a log-based design — WAL at core

📊 Benefits of WAL

FeatureBenefit
Crash RecoveryCan replay changes after failure
PerformanceWrites are fast — just write to WAL first
DurabilityEnsures data isn’t lost after a commit
ReplicationWAL can be shipped to replicas

🔥 Real-Life Analogy

Imagine you’re writing an important letter ✉️.

  1. First, you scribble it in your notepad (WAL).
  2. Then, you type and send it (database change).
  3. If your computer crashes, you can still finish the letter from your notepad.

That’s WAL: always write the plan first, then apply.


✅ Summary

FeatureDescription
What it isA log of changes written before the data
Main benefitProtects data from loss or corruption
Used inPostgreSQL, SQLite, MySQL (InnoDB), Kafka
Key toAtomicity and Durability in ACID
This entry was posted in Без рубрики. Bookmark the permalink.