SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Common Database Types
  • SQL vs NoSQL
  • ACID Transactions
  • B-Trees and B+ Trees
  • LSM Trees
  • Transaction Isolation Levels
  • Locking and MVCC
  • Normalization
  • OLTP vs OLAP
  • BASE and PACELC
  • Write-Ahead Log (WAL)
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Basics

Write-Ahead Log (WAL)

Write the change to a log first, so a crash never loses it. The trick behind durability and replication.

⏱ 14 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A write-ahead log (WAL) is a rule databases follow: write down what you are about to do, in a safe log, before you do it. If the machine crashes, the log tells the database how to finish or undo the work.

  • Changing the real data pages means many scattered writes. Appending to a log is one sequential write, which is much faster to flush to disk.
  • After a crash the database replays the log: it redoes committed changes and undoes unfinished ones.
  • The same log can also feed replication, point-in-time recovery and change data capture.

02Concept: What is it?

A database keeps its data in pages on disk, and works on a copy of the hot pages in memory because memory is far faster. When you change a row, the page in memory changes first. Saving every changed page to disk straight away would be slow, because the pages are scattered all over the disk. But if the database waits, a crash would lose the changes that were only in memory, even ones the user was already told were saved. That would break the D (Durability) in ACID.

The fix is the write-ahead log. Before a change goes anywhere else, a short record describing it ("transaction 7: account B, 300 → 400") is appended to the log. A commit is not complete until its log records have been flushed to disk (the operating system call is often called fsync). Only then is the user told "OK". The data pages themselves can be written later, in the background, at a convenient time.

After a crash, the database starts and reads the log. For every transaction that has a COMMIT record, it makes sure the change is in the data pages (redo). For every transaction without one, it makes sure the change is not (undo). The rule that keeps this safe: a log record must reach disk before the data page it describes.

Where a change goes
✍️ChangeUPDATE ...
→↓1. describe it
📜Logappend and flush (fast, in order)
→↓2. tell the user OK
🙂Clientcommitted
🧠Memory pagechanged at once
⇢⇣3. later, in the background
💾Data page on diskwritten at a checkpoint
The log is the promise. The data pages catch up later.
🧠Why sequential matters
Appending to the end of a file is much cheaper than writing many different pages in different places. That is why the log makes commits fast and safe at the same time.

03Real-Life Example

🍵The Chef's Order Book
A busy restaurant kitchen writes every order in a book before cooking. Cooking each dish takes time and the cook gets interrupted. If the power fails and the stoves go cold, the book still shows every order that was taken. When the lights return, the chef reads the book: orders marked "paid" are cooked again if the dish was not served, and orders that were only half written are crossed out. The book is fast to update (one line at the bottom), while the real work in the kitchen is scattered and slow.
Kitchen
Database
The order book
The write-ahead log
Writing a line at the bottom
Appending a log record (sequential)
Cooking the dish
Changing the data pages
Customer paid, so it is promised
Commit record flushed to the log
Power cut
Crash
Cooking again the paid orders
Redo committed changes
Crossing out half-written orders
Undo uncommitted changes
Tearing off old pages that are fully served
Checkpoint, and trimming the old log
The log tells the story after a crash
💥Crash
→↓restart
📖Read the logfrom the last checkpoint
→↓redo committed, undo the rest
✅Consistent again

04Why Do We Need It?

🛡️Durability
Once the user hears OK, the change survives a crash, because the log is already on disk.
⚛️Atomicity
A half-finished transaction can be undone, so you never see only half of a transfer.
⚡Fast commits
One sequential flush is cheaper than flushing many scattered data pages.
🔁Replication
Send the log to other machines and they can replay it to build an identical copy.
⏪Point-in-time recovery
A backup plus the log up to a chosen moment lets you rewind to just before a mistake.
📡Change streams
The log is a clean, ordered list of every change, which is ideal for change data capture.
Write the promise first, do the slow work later. That is how a database can be both fast and safe.

05Where Do We Use It?

🐘Relational databases
PostgreSQL has a write-ahead log. MySQL's InnoDB has a redo log, and other engines use the same idea under other names.
🍃NoSQL and key-value stores
Many keep a commit log or append-only file before applying changes. LSM tree databases write to a log before the in-memory table.
🔁Replicas
Physical replication in some databases ships the WAL to followers, which replay it.
⏪Backups
Archiving the log continuously allows point-in-time recovery.
📡Change data capture
Tools read the log to turn every row change into an event.
🗂️File systems
Journaling file systems use the same idea to avoid a corrupted disk after a crash.

06Types / Parts / How It Works

What is inside a log

Each record has a position (often called a log sequence number, LSN) that only goes up, which gives a total order to every change. The main kinds of record are:

An illustrative log
LSN 101  BEGIN   T1
LSN 102  UPDATE  T1  A: 500 -> 400
LSN 103  UPDATE  T1  B: 300 -> 400
LSN 104  COMMIT  T1          <- the promise is made here
LSN 105  UPDATE  T2  C: 10 -> 20
LSN 106  CHECKPOINT           <- pages up to here are on disk
LSN 107  (crash)              <- T2 never committed

Redo and undo

Case after a crashWhat the log saysWhat recovery does
Committed, but pages not yet writtenCOMMIT is in the logRedo: apply the change to the page
Not committed, but the page was already savedNo COMMIT in the logUndo: put the old value back
Committed and already on diskBefore the last checkpointNothing to do
Not committed and not on diskNo COMMITNothing to do, forget it

Checkpoints keep recovery short

A checkpoint saves a mark
old lognot needed for recovery
📍checkpoint
log since thenreplay this part
Time to recover without checkpointsreplay everything
Time to recover with a recent checkpointreplay a little
Recovery starts at the last checkpoint, not at the beginning of time. Older log can then be archived or removed.
Checkpoint Replayed on restart

Group commit and the cost of fsync

Flushing to a physical disk is the slow part of a commit. Group commit lets many transactions that commit at nearly the same moment share one flush, which gives much better throughput. Some databases also allow a relaxed setting that flushes the log every moment instead of every commit. That is faster, but a crash can lose the last moment of commits, so it is a conscious trade of durability for speed.

VisualizerCrash the database at three moments, with and without a logKeep the log On and step through all three crash points: before the commit, after the commit, and after a checkpoint. Then switch the log Off and run the middle one again to see 100 vanish.
Where does the crash happen?
Write-ahead log
Memory (RAM)
A = 500B = 300C = 10log buffer (not yet safe):(empty)
Log on disk (written in order)
(empty)
Data pages on disk
A = 500B = 300C = 10
Step 1 of 7
The database is running
Account A has 500, account B has 300 and a counter C has 10. They sit on disk and a copy sits in memory (RAM). Transaction T1 will move 100 from A to B. Transaction T2 will change C.

A simplified teaching model with made-up values. With the log off, the page of A reaching disk before the page of B is just one possible outcome of a crash. Real databases write many pages, in any order.

07How to Use It / Steps / Implementation

Living well with a WAL

  1. 1
    Keep the log on a safe, fast disk
    Commit speed is bounded by how quickly the log can be flushed. Many setups put it on fast storage, separate from the data.
  2. 2
    Do not turn off the flush to look fast
    Disabling the flush (or the log) can make benchmarks look great, and then lose committed data in a crash.
  3. 3
    Tune the checkpoints
    Frequent checkpoints shorten recovery but cause more writing. Rare checkpoints do the opposite. Find a balance.
  4. 4
    Watch the log size
    The log grows with writes. Make sure old files are archived or removed, or the disk will fill up and the database will stop.
  5. 5
    Archive the log for recovery
    Keep a base backup and the log after it, so you can restore to any moment. Test the restore.
  6. 6
    Monitor replicas that read the log
    A slow replica holds the log back. Watch how far behind it is.
  7. 7
    Use batching
    Group several changes into one transaction to share one flush, instead of committing row by row.
⚠️Disks and caches can lie
A drive or a controller with a volatile write cache may report a write as done before it is really safe. Use hardware and settings that honour flush requests, or the log cannot do its job.

08Key Terms to Know

TermMeaning in easy words
Write-ahead log (WAL)A log of changes that is saved to disk before the data pages are changed
Log recordOne entry describing a change, a commit or a checkpoint
LSNLog sequence number: a number that only goes up and gives every record its place in order
fsyncA request to the operating system to really write the data to the physical disk
Commit recordThe log entry that makes a transaction official
RedoReplay a committed change that is missing from the data pages
UndoReverse a change from a transaction that never committed
CheckpointA moment when the changed pages are saved, so recovery can start from there
Crash recoveryThe steps after a restart that use the log to restore a consistent state
Group commitSeveral transactions sharing one log flush to raise throughput
Log shippingSending the log to another machine so it can replay it

09Pros, Cons and Trade-offs

✅ Pros
  • Committed data survives crashes
  • Half-finished work can be undone
  • Commits are fast because the log is sequential
  • The same log powers replication, recovery and change streams
  • Data pages can be written lazily and in good order
⚠️ Cons
  • Every write is written twice: once to the log, once to the page
  • The log needs space, care and cleaning
  • The flush to disk limits commit speed
  • Recovery after a crash takes time
  • Wrong disk or cache settings can silently break the promise

Trade-offs

ChoiceWe gainWe lose
Flush on every commitNo committed data is lostSlower commits
Flush every momentHigher throughputLast moment of commits can be lost in a crash
Frequent checkpointsFast recoveryMore background writing
Rare checkpointsLess writingLonger recovery, bigger log
Keep the log for a long timePoint-in-time recovery, replicas can catch upMore disk space
Group commitMuch better throughputA tiny extra wait for each commit

10Common Problems and Mistakes

Common mistakes

  1. Turning off the flush for speed. A power cut then loses data you already confirmed.
  2. Ignoring log growth. A forgotten replica or a stuck archive job keeps the log from being removed until the disk is full.
  3. Trusting a disk cache that lies. Without real flushes the log is not safe.
  4. Never testing recovery. A backup and log archive that has not been restored is only a hope.
  5. One huge transaction. It creates a giant log and a very long rollback if it fails.
  6. Confusing the log with a backup. The log helps recover from a crash and rebuild from a backup, but it does not replace one.

Things to watch

💽Log disk space
Alert well before it fills. A full log disk can halt all writes.
🐢Slow flushes
High flush time shows up as slow commits for everyone.
🧲Lagging consumers
A replica or a change-data-capture reader that falls behind can pin old log files.
⏱️Recovery time
Measure how long a restart takes. It decides how long you are down after a crash.

11Real-World Examples

🐘PostgreSQL
Uses a write-ahead log for crash recovery, streaming replication and point-in-time recovery.
🐬MySQL (InnoDB)
Uses a redo log for crash safety and a separate binary log that replication and change data capture tools read.
🔴Redis
Offers an append-only file that records every write, so the data can be rebuilt after a restart.
🧱LSM databases
New writes go to a log first, and then to an in-memory table that is later flushed to sorted files.
📡Debezium and friends
Read the database log to turn each change into an event on a stream.
🗂️Journaling file systems
Write a small journal first, so a crash does not leave the file system half updated.
📝Note
Names, options and defaults differ between products and versions. Check the documentation of the database you use.
Mini case: one log, three uses
🗄️Primary databasewrites the log first
→↓log
📜WAL
→↓crash recovery
🔧Restart
→↓replay
🗄️Replica
→↓rewind
⏪Point-in-time restore
The same ordered list of changes helps with crashes, copies and rewinds.

12Related Topics to Read Next

ACID Transactions→

The WAL is how databases keep atomicity and durability.

Replication→

Followers often replay the primary's log.

Point-in-Time Recovery→

A backup plus the log lets you rewind to a chosen moment.

Change Data Capture (CDC)→

Reads the log to stream every change.

LSM Trees→

A storage engine that writes to a log before its in-memory table.

Backups, RPO, RTO and Disaster Recovery→

The log decides how little data you can lose.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Rule: log first, data later. The log must be on disk before the page it describes.
  • ✔Commit means the commit record is flushed to the log.
  • ✔Crash recovery: redo committed work, undo unfinished work.
  • ✔Why fast: one sequential append beats many random page writes.
  • ✔Checkpoint: saves pages and shortens the next recovery.
  • ✔Bonus uses: replication, point-in-time recovery, change data capture.
  • ✔Danger: disabled flushes, lying disk caches, a full log disk.
  • ✔One line: “Write down the promise first, so a crash can never erase it.”
← Previous
BASE and PACELC
Next →
Relational Databases