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
app.db: the main database. Header bytes 18 and 19 are set to 2, which is what makes WAL mode persistent across connections.app.db-wal: the log. It contains full page images, not diffs.app.db-shm: the wal-index, a memory-mapped file shared by every connection. It is a derived structure and can be rebuilt from the log.
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:
| Field | Meaning |
|---|---|
| magic | 0x377f0682 or 0x377f0683. The low bit selects big- or little-endian checksum arithmetic. |
| version | 3007000 |
| page size | Must match the database. |
| checkpoint seq | Incremented each time the log restarts. |
| salt-1, salt-2 | Changed on every restart. Salt-1 is incremented, salt-2 is random. |
| checksum | Two 32-bit values covering the header. |
Each frame is a 24-byte header followed by one page:
| Field | Meaning |
|---|---|
| page number | Which database page this frame holds. |
| commit size | Database size in pages after the commit. Nonzero only on the last frame of a transaction. |
| salt-1, salt-2 | Copies of the header salts. A mismatch means the frame belongs to an earlier generation of the log. |
| checksum | Cumulative: 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
- 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_SNAPSHOTif its snapshot is no longer the newest. - 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.
- The final frame is written with a nonzero commit size. Under
synchronous=FULLthe log is fsynced here. Undersynchronous=NORMALit 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. - 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. - 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 first block begins with a 136-byte header: two copies of the wal-index header (
mxFrame, page count, salts, change counter, checksum), followed by checkpoint state (nBackfill, five read marks, lock bytes). Readers read both copies and retry if they differ, which means a writer is mid-update. - Each block holds the page numbers for 4096 frames (4062 in the first block) and a hash table of 8192 16-bit slots mapping a page number to a frame position in that block.
- Locks are byte-range locks on the
-shmfile: write, checkpoint, recovery, and five read-mark slots.
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
- At the start of a read transaction the reader copies
mxFramefrom the wal-index header. That value is its snapshot. - 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. - 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. - 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:
- Take the checkpoint lock. Only one checkpoint runs at a time; it does not block readers or the writer.
- 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. - 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.
- Store the highest copied frame in
nBackfill.
A checkpoint does not shrink the log. Copied frames stay in the file until they are overwritten.
| Mode | Behavior |
|---|---|
| PASSIVE | Copies what it can without waiting for any reader or writer. This is the automatic mode. |
| FULL | Waits for the writer and for all readers to reach the latest snapshot, blocks new writers, then copies everything. |
| RESTART | As FULL, then also waits for all readers to finish with the log, so the next writer can start at the beginning. |
| TRUNCATE | As 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:
- Validate the log header.
- Scan frames from the start, checking each frame’s salts and cumulative checksum.
- Stop at the first invalid frame.
- Set
mxFrameto 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
- One writer at a time. Use
BEGIN IMMEDIATEfor transactions that will write, and setbusy_timeout. - Same host only. The wal-index requires shared memory and working file locks, so network filesystems are unsupported. The exception is
locking_mode=EXCLUSIVEset before the first WAL access, which keeps the wal-index in heap memory for a single connection. - Long-running readers grow the log. A reader pinned to an old snapshot prevents checkpoints from passing its mark and prevents log restart. The log grows without bound while it lives, and lookups slow as hash tables multiply. Keep read transactions short and watch the values returned by
PRAGMA wal_checkpoint. - Atomicity across attached databases. Commits are atomic per file, not across all databases in an
ATTACHset. - Large transactions. The log must hold every page the transaction modifies, plus any cache spill.
- Read-only access. Opening a WAL database needs write access to
-shmunless the database is opened as immutable or the-shmand-walfiles already exist (SQLite 3.22 and later). - Old libraries. SQLite before 3.7.0 cannot open a database in WAL mode.
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