How WAL mode works in SQLite

In the default rollback-journal mode, a writer copies the original pages into a journal, modifies the database file in place, and holds an exclusive lock while it does so. Readers and writers exclude each other. WAL mode reverses the arrangement: modified pages are appended to a separate log, the database file is left alone, and the log is copied back into the database later. Readers assemble their view from the database file plus the log, so one writer and any number of readers run concurrently.

Files

When the last connection closes cleanly, it checkpoints the log and deletes both -wal and -shm.

Log format

The log starts with a 32-byte header:

FieldMeaning
magic0x377f0682 or 0x377f0683. The low bit selects big- or little-endian checksum arithmetic.
version3007000
page sizeMust match the database.
checkpoint seqIncremented each time the log restarts.
salt-1, salt-2Changed on every restart. Salt-1 is incremented, salt-2 is random.
checksumTwo 32-bit values covering the header.

Each frame is a 24-byte header followed by one page:

FieldMeaning
page numberWhich database page this frame holds.
commit sizeDatabase size in pages after the commit. Nonzero only on the last frame of a transaction.
salt-1, salt-2Copies of the header salts. A mismatch means the frame belongs to an earlier generation of the log.
checksumCumulative: computed over the previous frame’s checksum, the first 8 bytes of this frame header, and the page content.

Because checksums chain, a frame is valid only if every frame before it is valid. A transaction is durable exactly when its commit frame is present and valid.

Write path

  1. The writer takes the WAL write lock. Only one connection holds it at a time. A connection that began as a reader and then tries to write fails with SQLITE_BUSY_SNAPSHOT if its snapshot is no longer the newest.
  2. Dirty pages are appended to the log as frames. If the page cache spills before commit, those frames are appended early; they stay invisible because no reader looks past the last committed frame.
  3. The final frame is written with a nonzero commit size. Under synchronous=FULL the log is fsynced here. Under synchronous=NORMAL it is not; the log is fsynced at checkpoint instead. That setting can lose recent commits on power loss or OS crash, but it cannot corrupt the database.
  4. The writer adds the new frames to the wal-index, then publishes a new wal-index header with the updated last-frame number (mxFrame). Publishing the header is the moment the transaction becomes visible.
  5. The write lock is released. The database file has not been touched.

If a page is modified in several transactions, it appears in several frames. The newest frame wins.

The wal-index

The wal-index lives in -shm, mapped into every connection. It consists of 32 KB blocks.

The change counter in the header lets a connection detect that another connection has committed, so it can discard stale page-cache entries.

Read path

  1. At the start of a read transaction the reader copies mxFrame from the wal-index header. That value is its snapshot.
  2. It registers the snapshot with a shared lock on a read-mark slot. Each slot holds a frame number. The reader uses a slot whose value is at most its mxFrame, updating one under a brief exclusive lock if needed. If the whole log has been checkpointed (nBackfill == mxFrame), it uses slot 0, whose value is always 0, and reads only from the database file.
  3. For every page it needs, the reader searches the hash tables for the newest frame numbered at most its mxFrame. If one exists, the page is read from the log. Otherwise it is read from the database file.
  4. When the transaction ends, the reader releases its slot.

The snapshot never changes during the transaction, so later commits are invisible to it. Readers take no lock that the writer needs, and the writer takes none that readers need.

Checkpointing

A checkpoint copies the newest version of each logged page into the database file. The sequence is:

  1. Take the checkpoint lock. Only one checkpoint runs at a time; it does not block readers or the writer.
  2. Compute the highest safe frame: the lowest read mark of any reader in use, capped at mxFrame. Frames beyond a reader’s mark may not be copied, because overwriting the corresponding database pages would change what that reader sees.
  3. fsync the log, then write the pages in ascending page-number order, extending or truncating the database file to the committed size as needed, then fsync the database.
  4. Store the highest copied frame in nBackfill.

A checkpoint does not shrink the log. Copied frames stay in the file until they are overwritten.

ModeBehavior
PASSIVECopies what it can without waiting for any reader or writer. This is the automatic mode.
FULLWaits for the writer and for all readers to reach the latest snapshot, blocks new writers, then copies everything.
RESTARTAs FULL, then also waits for all readers to finish with the log, so the next writer can start at the beginning.
TRUNCATEAs RESTART, then truncates the log file to zero bytes.

Automatic checkpoints run on the connection whose commit pushes the log past wal_autocheckpoint pages (default 1000). That commit pays the cost of the checkpoint.

Log restart

At the start of a write transaction, the writer checks whether nBackfill == mxFrame and whether it can take exclusive locks on the read-mark slots, meaning no reader is using the log. If both hold, it restarts the log: the next frame is written at position 1, the checkpoint sequence is incremented, salt-1 is incremented, salt-2 is randomized, and a new header is written. Old frames now carry stale salts and are rejected without being erased.

The file keeps its size after a restart unless journal_size_limit is set, in which case it is truncated to that limit.

Crash recovery

The database file is never modified by uncommitted transactions, so recovery needs no undo. The first connection to open the database after a crash, once no other connection holds it, rebuilds the wal-index from the log:

  1. Validate the log header.
  2. Scan frames from the start, checking each frame’s salts and cumulative checksum.
  3. Stop at the first invalid frame.
  4. Set mxFrame to the last valid commit frame. Everything after it, including torn writes and uncommitted frames, is ignored and later overwritten.

A crash in the middle of a checkpoint is harmless: the same frames are copied again by the next checkpoint, and copying a page image is idempotent.

Limits and failure modes

Common settings

PRAGMA journal_mode = WAL;          -- persists in the database file
PRAGMA synchronous = NORMAL;        -- no log fsync at commit
PRAGMA busy_timeout = 5000;         -- ms to wait on a lock
PRAGMA wal_autocheckpoint = 1000;   -- pages
PRAGMA journal_size_limit = 67108864; -- truncate log after restart
PRAGMA wal_checkpoint(TRUNCATE);    -- manual, returns busy|log|checkpointed