Skip to content

SQLite in Depth ​

"SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine." — SQLite project, About SQLite (sqlite.org/about.html)

Summary: SQLite is a real, fully transactional SQL database that lives inside your process as a library and stores everything in one file; it gives up client/server networking and concurrent writers, and gets simplicity, speed and a very small failure surface in return. Focus: The file and page format, rollback journal vs WAL and checkpoints, the lock ladder and SQLITE_BUSY, BEGIN IMMEDIATE, PRAGMAs, flexible typing vs STRICT, FTS5, JSON, backups, corruption, and Go and Laravel usage, plus where Litestream, LiteFS, rqlite and libSQL fit. Learning goal: Decide when SQLite is the right production database, configure it correctly (WAL, busy_timeout, synchronous, foreign_keys), write code that never loses a write to SQLITE_BUSY, and back it up without corrupting it.

This page is the complete reference for SQLite as a production database engine: the embedded model, the single-file format built from pages and B-trees, the two atomic-commit mechanisms (rollback journal and write-ahead log), checkpointing, the four lock states, the one-writer rule, the busy handler, BEGIN DEFERRED/IMMEDIATE/EXCLUSIVE, isolation, every PRAGMA a practitioner meets, type affinity and STRICT tables, upsert, RETURNING, window functions, JSON/JSONB, FTS5, in-memory and shared-cache databases, limits, backup (.backup, VACUUM INTO, the backup API), the causes of file corruption, and the testing culture behind it. It then covers running it from Go (modernc.org/sqlite, mattn/go-sqlite3) and Laravel (the sqlite driver and :memory: tests), and the replication layer around it (Litestream, LiteFS, rqlite, libSQL/Turso). It does not re-teach what sibling pages own: the four ACID properties are in ACID & Transactions, anomaly definitions in Isolation Levels, how a WAL gives crash recovery in general in Durability, WAL & Crash Recovery, B-tree theory in B-Tree vs B+Tree, and generic backup strategy in Backup, PITR & Disaster Recovery.

Page map ​

If you are looking forGo to
The whole thing in tables you can memoriseEverything in one minute
Why an embedded database exists, and what it costsWhy SQLite exists
History, public domain, testing, how widely it is deployedWhere it comes from
Serverless, in-process, zero-configThe embedded model
Pages, B-trees, the 100-byte header, rowidThe file format
Rollback journal, hot journal, atomic commitRollback journal
WAL, wal-index, checkpoint modes, WAL growthWAL and checkpointing
SHARED, RESERVED, PENDING, EXCLUSIVELocking states
SQLITE_BUSY, busy_timeout, BEGIN IMMEDIATEBUSY and the write lock
Is SQLite serializable, what do readers seeIsolation
Dynamic typing, affinity, STRICTTypes
journal_mode, synchronous, foreign_keys, cache_size, mmap_size, temp_storePRAGMAs
Upsert, RETURNING, window functions, CTEs, generated columnsModern SQL
json_extract, ->>, JSONBJSON
MATCH, bm25, tokenizersFTS5
:memory:, cache=sharedIn-memory and shared cache
281 TB, 2000 columns, 64 tables in a joinLimits
.backup, VACUUM INTO, sqlite3_rsyncBackup
How a SQLite file gets damagedCorruption
100% branch coverageTesting culture
What PostgreSQL, MySQL, DuckDB do differentlyComparison
Litestream, LiteFS, rqlite, libSQL/TursoReplication and scale-out
Go: pools, DSNs, writersGo
Laravel: driver, config keys, :memory: testsLaravel
Error codes and retryMechanics, Retry
Which database for which workloadChoosing
Monolith to distributedIn architecture
Reproduce itLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The model.

PropertySQLiteConsequence
Process modelA library inside your process; no server, no portNo network latency, no connection auth, no separate ops
StorageA single file (one ordinary file, plus -wal, -shm or -journal while in use)Copy, ship, attach and delete it like a file
ConcurrencyUnlimited readers, exactly one writer at a timeGreat for read-heavy and short-write workloads, wrong for many concurrent writers
IsolationSerializable (by serializing writers); WAL readers see a snapshotNo dirty reads, no lost updates; the price is SQLITE_BUSY instead of waiting rows
DurabilityAtomic commit via rollback journal (default) or WALSurvives power loss when synchronous and the disk honour fsync
TypesDynamic by default (affinity); STRICT tables since 3.37.0Wrong-typed data is accepted silently unless you opt in to STRICT
SizeUp to about 281 TB, 1 GB per row/BLOBThe limit you hit first is write concurrency, not size
NetworkNot a protocol; never share the file over NFS/SMB for writingReplication is a separate layer (Litestream, LiteFS, rqlite)

The two journaling modes.

Rollback journal (default, DELETE)WAL (journal_mode=WAL)
Where changes go firstOriginal pages are copied to -journal; new data is written into the main fileNew data is appended to -wal; the main file is untouched
Commit pointJournal file deletedCommit record appended to the WAL
Readers and writerA writer needs exclusive access for the final write; readers block itReaders never block the writer, the writer never blocks readers
WritersOneOne
fsyncs per commitSeveral (journal, then database, then delete)One on the WAL (synchronous=FULL), none per commit with NORMAL
Extra workNoneCheckpointing (WAL back into the main file)
Network filesystemWorks poorly but possibleNot supported: needs shared memory on one host
Typical useApplication file formats, single-user toolsServers and anything with concurrent readers

The PRAGMAs you set on every connection.

PRAGMAValue for a server appWhy
journal_modeWALConcurrency and speed; persists in the file
busy_timeout5000 (ms)Wait for the lock instead of failing at once
synchronousNORMAL with WALSafe against app crashes; may lose the last commits on power loss, never corrupts
foreign_keysONOff by default in the library; per connection
cache_size-65536 (64 MiB) or moreDefault is only about 2 MiB
temp_storeMEMORYSorts and temp tables stay off disk
mmap_size268435456 or larger, if the files are on a local diskFewer copies on reads
wal_autocheckpointdefault 1000 pagesMove WAL back into the file regularly

Where SQLite wins and loses.

SituationVerdict
Mobile, desktop, browser, IoT, embedded, testsWins by default
One web app on one server, read-heavy, short writesWins (with WAL) and removes a whole component
Edge/regional apps with local readsWins with LiteFS or libSQL replication
Many app servers writing the same dataLoses; use PostgreSQL or MySQL
Hundreds of concurrent writers, long write transactionsLoses
Analytical scans over hundreds of millions of rowsLoses to DuckDB or a warehouse
Need roles, row-level security, wire protocol, online schema toolsLoses

Why SQLite exists ​

Most database engines are a separate server process: your program opens a socket, sends SQL, and waits. That is the right design when many programs share one data set and need access control. It is the wrong design when the data belongs to exactly one program, because you pay for a network hop, a connection pool, a config file, a daemon to patch and a second thing that can be down. SQLite removes the server: the SQL engine is a C library linked into your program, and a database is a file the library opens. The project's own framing is "SQLite does not compete with client/server databases. SQLite competes with fopen()." (sqlite.org/whentouse.html).

What you gain by being embeddedWhat you give up
A query is a function call: microseconds, no round tripOther machines cannot connect to it
Zero administration: no users, no ports, no tuning daemonNo roles, no GRANT, no row-level security
The database is one file: backup, copy, ship, diffYou must back up carefully (a naive cp of a live file can be corrupt)
Tiny failure surface: nothing to be unreachableOne writer at a time, whole-database write lock
Deterministic tests: :memory: is free and privateBehaviour differs from PostgreSQL/MySQL in typing and DDL
Same engine on phone, laptop, server, browserNo built-in replication or failover

The analogy we reuse on this page: a notebook on your own desk versus a shared filing room. A client/server database is a filing room with a clerk: many people queue at the window, the clerk enforces rules and keeps the books for everyone. SQLite is a notebook on your own desk: nothing is faster to open, and you need no clerk, but only one person writes in it at a time, and if you want colleagues to read it from another building you must photocopy pages and send them (replication is a separate service).

Three common misunderstandings, up front ​

  1. “SQLite is a toy for prototypes.” It is the most widely deployed database in the world, has a larger test suite than almost any server database, and many production sites (read-heavy, single node) run on it. What it is not is a multi-writer, networked database.
  2. “Because it is just a file, I can copy or sync the file while the app runs.” A live database is the main file plus -wal (or -journal) plus shared state. Copying only app.db in the middle of a write, or syncing it with Dropbox or over NFS, is one of the classic ways to corrupt it. Use .backup, VACUUM INTO or Litestream.
  3. “It is dynamically typed, so a column type is just a comment.” A column type sets an affinity that coerces values; it does not reject wrong ones. Only STRICT tables enforce types, and foreign_keys is off unless you turn it on for each connection.

Where it comes from ​

SQLite's own change log (sqlite.org/changes.html, read for this page) dates the first public release, "Initial Public Release of Alpha code", to 2000-05-29. The author, D. Richard Hipp, and the origin story (a US Navy damage-control application that had to work without a database server) come from Hipp's talks and are secondary information that this page did not verify against a primary page. The primary documents used on this page are the project's own: About SQLite, Appropriate Uses For SQLite, SQLite Is Serverless, File Format, Write-Ahead Logging, File Locking And Concurrency, Atomic Commit, Isolation In SQLite, Datatypes, STRICT Tables, FTS5, JSON Functions, Limits, How To Corrupt, and How SQLite Is Tested. The source code is in the public domain, the file format is documented as stable and enduring, and the project states a long-term support commitment.

Year (release)MilestoneWhy it matters here
2000First releaseEmbedded, serverless, file-based from day one
3.7.0 (2010-07-21)Write-ahead loggingReaders and the writer stop blocking each other
3.8.3Common table expressionsRecursive queries
3.9.0 (2015-10-14)FTS5 and the JSON1 extension added to the source tree (both compile-time options then)Modern full-text search with bm25; JSON functions on request
3.24.0 (2018-06-04)Upsert (ON CONFLICT DO UPDATE)One-statement insert-or-update
3.25.0 (2018-09-15)Window functionsRanking and running totals in SQL
3.35.0 (2021-03-12)RETURNINGGet generated ids and new values back
3.37.0 (2021-11-27)STRICT tablesReal type enforcement
3.38.0 (2022-02-22)JSON functions built in, -> and ->>JSON without a loadable extension
3.45.0 (2024-01-15)JSONB binary JSONFaster JSON processing

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, the precise definition, a sequence you can follow step by step, real scenarios, what each engine does, and the fix in SQL, Go and Laravel.

The embedded, serverless model Must-know ​

In plain words: There is no database server. Your program links the SQLite library and reads and writes the database file directly, so a query is just a function call that touches a file.

Common misunderstanding: "Serverless" means Lambda or cloud functions. In SQLite's vocabulary it means there is no server process at all: the page SQLite Is Serverless says "the process that wants to access the database reads and writes directly from the database files on disk. There is no intermediary server process."

Definition: SQLite is an in-process library. Every connection (sqlite3 handle) lives in the application's address space, has its own page cache and parser, and coordinates with other connections (in this or other processes) only through locks on the database file and, in WAL mode, a shared-memory file. There is no authentication, because whoever can open the file can read all of it; access control is the operating system's file permissions.

 1  app process A:  sqlite3_open("app.db")   -> own page cache, own parser
 2  app process B:  sqlite3_open("app.db")   -> own page cache, own parser
 3  A: SELECT ...   -> read(2) the pages it needs, take SHARED lock via fcntl
 4  B: UPDATE ...   -> take RESERVED lock, change pages in its own cache
 5  B: COMMIT       -> journal + write(2) + fsync(2)
 6  A: next read    -> notices the file changed (change counter) and drops stale cache
 -- no socket, no daemon: the operating system's file locks are the only coordinator

Real scenarios: the file format of an application (a document, a game save, a browser's history), phone and desktop apps, a router's configuration, a CI cache, unit tests with :memory:, a single-server Laravel or Go app, a per-tenant database file, an edge function with a local replica.

ProductProcess model
SQLiteIn-process library, file locks
DuckDBIn-process library (columnar, analytics)
PostgreSQLPostmaster plus a backend process per connection
MySQL InnoDBOne server (mysqld) with a thread per connection
SQL Server, OracleServer processes, listener, shared memory
MongoDBmongod server, wire protocol
RedisSingle-threaded server for commands, wire protocol (RESP)
CockroachDBDistributed cluster, PostgreSQL wire protocol

Fix / how to use it:

sql
-- Open a database (creates the file) and look at what the engine is
sqlite3 app.db
sqlite> SELECT sqlite_version();
sqlite> PRAGMA compile_options;     -- ENABLE_FTS5, THREADSAFE=..., etc.
sqlite> .open --readonly app.db     -- CLI: reopen read-only

In Go the "connection string" is a file path with options (see Go); in Laravel it is DB_CONNECTION=sqlite and DB_DATABASE=/absolute/path/database.sqlite (see Laravel).

The file format: pages and B-trees Must-know ​

In plain words: The database file is a stack of equal-size blocks called pages. Every table and every index is a B-tree built out of those pages, and a small table at the start of the file lists where each tree begins.

Common misunderstanding: "A SQLite table is a heap of rows plus separate indexes, like PostgreSQL." No: a normal SQLite table is a B-tree keyed by a 64-bit integer rowid, with the row stored in the leaf. An index is a second B-tree keyed by the indexed columns and ending with the rowid, so an index lookup is two B-tree searches unless the index covers the query.

Definition: The first 100 bytes of the file are the database header (magic string SQLite format 3 followed by a NUL byte, page size at offset 16, file format versions at 18 and 19 where 2 means WAL, change counter at 24, size in pages at 28, freelist trunk page at 32, schema cookie at 40, text encoding at 56, user_version at 60, application_id at 68). The page size is a power of two between 512 and 65536 (default 4096 since 3.12.0). Page 1 is the root of the sqlite_schema table (also known as sqlite_master), which has one row per table, index, view and trigger with its rootpage and its CREATE text. B-tree pages are one of four types, flagged by their first byte: 0x02 interior index, 0x05 interior table, 0x0a leaf index, 0x0d leaf table. Table interior pages hold only rowid separators; all rows are in the leaves. A row that does not fit in a page spills its tail into overflow pages. Pages that were freed by DELETE go to the freelist; they are reused but the file does not shrink until VACUUM (or auto_vacuum). Integers inside records use a variable-length encoding (a varint of 1 to 9 bytes), and each record starts with a header of serial types that tells the type and size of each column.

One file = N pages of the same size (512 to 65536 bytes, default 4096)page 1100 B header + schema rootpage 2page 3page 4page 5freelistpage 6... page NEach table and each index is its own B-tree rooted at one pagesqlite_schema (p1)table users: root p2index users_email: root p4rootpageone row per table / index / view / trigger, with its CREATE textTable B-tree (key = rowid, rows live in the leaves)interior: rowid 100 | 200leaf: rows 1..99cells: len, rowid, recordleaf: rows 100..199overflow pagebig TEXT / BLOB tailIndex B-treekey (email, rowid) onlylookup: index leaf gives rowid,then second B-tree search in the table(WITHOUT ROWID: PK is the table key)
 1  SELECT * FROM users WHERE id = 150;       -- id is INTEGER PRIMARY KEY = rowid
 2    read page 1                              -- find rootpage of "users" = 2
 3    read page 2 (interior table page)        -- 150 is between separators 100 and 200
 4    read leaf page                           -- binary search the cell with rowid 150
 5    decode the record header                 -- serial types give each column's size
 6  SELECT * FROM users WHERE email = 'a@b.c'; -- uses index users_email (root p4)
 7    walk the index B-tree to key (email, rowid)
 8    take the rowid, search the table B-tree again   -- second descent
 -- 3 or 4 page reads for a warm tree; the first levels are almost always in the page cache

Real scenarios: rowid makes INTEGER PRIMARY KEY lookups the fastest path (no separate index); a table with a TEXT primary key has both the table B-tree and a hidden unique index, which is why WITHOUT ROWID tables (the primary key is the table B-tree) are smaller and faster for composite or text keys; deleting half of a big table leaves the file the same size until VACUUM; a table with large BLOBs is slower to scan because wide rows push data into overflow pages.

EngineTable storageIndex points to
SQLiteB-tree keyed by rowid (or by the PK with WITHOUT ROWID)The rowid (or the PK)
PostgreSQLHeap file of tuples, no clustering by defaultctid (page, offset)
MySQL InnoDBClustered B+tree on the primary keyThe primary key value
SQL ServerHeap, or clustered B+tree if a clustered index existsRID or the clustering key
OracleHeap by default (index-organized tables optional)ROWID

For the theory of B-trees versus B+trees see B-Tree vs B+Tree; for heap pages see Database Internals.

Fix / how to use it:

sql
PRAGMA page_size;               -- 4096 by default; change before the first table (or via VACUUM)
PRAGMA page_count;              -- pages in the file
PRAGMA freelist_count;          -- free pages waiting for reuse
SELECT name, rootpage FROM sqlite_schema WHERE type IN ('table', 'index');
CREATE TABLE tags (tenant_id INTEGER NOT NULL, name TEXT NOT NULL, n INTEGER NOT NULL,
  PRIMARY KEY (tenant_id, name)) WITHOUT ROWID;
VACUUM;                         -- rebuilds the file and returns free pages to the OS

The rollback journal and atomic commit Must-know ​

In plain words: Before SQLite changes a page in the database file, it copies the original page into a side file called the journal. If the power fails mid-write, the next opener sees the journal and puts the originals back, so a transaction either happened entirely or not at all.

Common misunderstanding: "Committing means the data is written to the database file." In rollback-journal mode the commit point is the moment the journal file is deleted (or its header zeroed), not the moment pages reach the main file.

Definition: In journal_mode=DELETE (the default) a write transaction (per Atomic Commit In SQLite): acquires a SHARED lock to read, then a RESERVED lock; creates the app.db-journal file; writes the original content of every page it is about to change into the journal; changes pages in its private page cache; waits for the journal to be flushed to disk; escalates to PENDING and then EXCLUSIVE; writes the changed pages into the main file; flushes it; and finally deletes the journal, which is the commit. A journal that exists after a crash is a hot journal: the next connection that opens the database finds it, takes a lock, and rolls back by copying the original pages back. Other journal modes: TRUNCATE (zero the file instead of deleting), PERSIST (overwrite the header with zeros), MEMORY (journal in RAM: a crash mid-transaction can corrupt), OFF (no rollback at all: ROLLBACK stops working), and WAL.

 1  BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1;
 2    SHARED lock (read pages) -> RESERVED lock (I will write)
 3    create app.db-journal; write ORIGINAL page 7 into it
 4    modify page 7 only in the private page cache
 5  COMMIT;
 6    fsync the journal                 -- originals are now safe on disk
 7    PENDING -> EXCLUSIVE (wait for readers to leave)
 8    write page 7 into app.db; fsync app.db
 9    delete app.db-journal             -- COMMIT POINT
10    unlock
 -- power failure after 7 and before 9: journal exists = hot journal -> next open restores the original page 7
 -- power failure after 9: the transaction is durable

Real scenarios: an app that crashes during a large UPDATE leaves a hot journal that the next start repairs silently; deleting app.db-journal by hand "because it looks like junk" after a crash corrupts the database; restoring app.db from backup but keeping an old -journal mismatches them and corrupts it.

ProductAtomic commit mechanism
SQLite (default)Rollback journal (undo of original pages), delete = commit
SQLite (WAL)Write-ahead log (redo), commit record = commit
PostgreSQLWAL (redo) plus MVCC tuple versions; no undo log
MySQL InnoDBRedo log plus undo log
SQL ServerTransaction log (redo and undo)
OracleRedo log plus undo tablespace
MongoDB WiredTigerJournal (redo) plus checkpoints

Fix / how to use it:

sql
PRAGMA journal_mode;            -- delete (default)
PRAGMA journal_mode = WAL;      -- switch; returns 'wal'; persists in the file
PRAGMA synchronous;             -- 2 = FULL (default), 1 = NORMAL, 0 = OFF, 3 = EXTRA
PRAGMA journal_size_limit = 67108864;   -- shrink leftover journal/WAL to 64 MiB after use

WAL, the wal-index and checkpointing Must-know ​

In plain words: In WAL mode SQLite stops touching the main file on commit. It appends the changed pages to a log, and a background step later copies them into the main file. Readers keep reading the old pages while the writer appends, so they do not wait for each other.

Common misunderstanding: "WAL allows many writers." It does not. The WAL page says it directly: "since there is only one WAL file, there can only be one writer at a time." What WAL changes is that readers and the writer no longer block each other.

Definition: Since 3.7.0 (2010-07-21) a database can use journal_mode=WAL. The writer appends frames (a page image plus a 24-byte frame header) to app.db-wal; a transaction ends with a frame whose header marks it as a commit. When a read transaction starts it records the last valid commit frame as its end mark and keeps that view for its whole duration; to read a page it looks in the WAL up to its end mark, else in the main file. Finding the newest frame for a page quickly is the job of the wal-index, stored in shared memory in the app.db-shm file, which is why all processes must be on the same host and why WAL does not work over a network filesystem. Checkpointing copies committed frames from the WAL back into the main file. It runs automatically when the WAL reaches 1000 pages (wal_autocheckpoint), and manually with PRAGMA wal_checkpoint(MODE) or sqlite3_wal_checkpoint_v2. Modes: PASSIVE (do as much as possible without waiting), FULL (wait for writers and readers so everything is copied), RESTART (like FULL, and also wait until readers use only the main file so the next writer restarts the WAL), TRUNCATE (like RESTART, and truncate the WAL file to zero bytes). A checkpoint cannot pass the end mark of the oldest active reader, so one long read transaction stops the WAL from being reset and it grows. The WAL is persistent: the mode is recorded in the database header (version bytes 18 and 19 become 2), and the last connection to close normally checkpoints and deletes -wal and -shm.

Writer (only one)Reader A (end mark 4)Reader B (end mark 6)app.db-wal (append only, frames = page copies)f1f2f3f4commitf5f6commitf7 ...append: fsync atcommit if FULLapp.db-shm: wal-index (shared memory)page number to newest frame; end marks; locksA sees f1..f4, B sees f1..f6: each keeps one snapshotapp.db (main file, unchanged until a checkpoint)pages not found in the WAL before the end mark are read from hereCheckpointcopies committed frames from the WAL into app.db (automatic at 1000 pages, or PRAGMA wal_checkpoint).It stops at the oldest reader end mark (here f4): a long read transaction keeps the WAL from being reset and it keeps growing.
 1  W:  BEGIN IMMEDIATE; UPDATE ... ; COMMIT;      -- frames f5, f6 appended, f6 is a commit frame
 2  R1: BEGIN; SELECT ...                          -- end mark = f4 (last commit at the time)
 3  W:  BEGIN IMMEDIATE; UPDATE ... ; COMMIT;      -- appends f7, f8; R1 does not wait, does not see them
 4  R1: SELECT ...                                 -- same snapshot as step 2 (repeatable)
 5  CK: PRAGMA wal_checkpoint(PASSIVE);            -- copies f1..f4 into app.db, stops at R1's end mark
 6  R1: COMMIT;                                    -- read transaction ends
 7  CK: PRAGMA wal_checkpoint(TRUNCATE);           -- now copies the rest and truncates app.db-wal to 0 bytes
 -- a reader that never ends (a forgotten open transaction) = a WAL that never shrinks

Real scenarios: a web app with many readers and a few writers goes from "database is locked" errors to none after enabling WAL; a nightly job holding a long SELECT cursor makes app.db-wal grow to gigabytes; a -wal file left on disk after a crash is replayed on the next open (recovery); a read-only mount fails to open a WAL database that has no -shm unless the process can create it (since 3.22.0 read-only opens are possible if the -wal and -shm files already exist or can be created).

PropertyRollback journalWAL
Readers block writerYes at the final write (EXCLUSIVE needs readers gone)No
Writer blocks readersYes while EXCLUSIVENo
Large transaction (hundreds of MB)FineHistorically slower; since 3.11.0 about as efficient
Many small commitsSlow (several fsyncs per commit)Fast (one sequential append)
Needs same host (shared memory)NoYes
Multi-file ATTACH atomicityAtomic across filesAtomic per file only
Change page_size laterPossibleNot once in WAL mode

Fix / how to use it:

sql
PRAGMA journal_mode = WAL;
PRAGMA wal_autocheckpoint = 1000;         -- pages; 0 disables automatic checkpoints
PRAGMA wal_checkpoint(PASSIVE);           -- returns busy | log frames | checkpointed frames
PRAGMA wal_checkpoint(TRUNCATE);          -- also resets the WAL file to 0 bytes
PRAGMA journal_size_limit = 134217728;    -- cap what is kept after a checkpoint

In Go and Laravel you set WAL once per connection through the DSN or config (see Go and Laravel).

Locking states and the one-writer rule Must-know ​

In plain words: In the default mode each connection climbs a ladder of locks: it reads (SHARED), announces it will write (RESERVED), asks the readers to leave (PENDING), and finally writes alone (EXCLUSIVE). Many can read at once but only one can be on the write side of the ladder.

Common misunderstanding: "SQLite locks rows or tables." The lock granularity is the entire database file. Even a one-row UPDATE is a whole-database write lock; only the duration is short.

Definition: The File Locking And Concurrency page defines five states per connection. UNLOCKED: no access. SHARED: may read; any number of connections can hold it. RESERVED: plans to write; only one at a time, and SHARED locks may still be acquired by others. PENDING: wants to write as soon as current readers finish; no new SHARED locks are granted, which prevents writer starvation. EXCLUSIVE: writing; no other lock of any kind. A statement that cannot get its lock invokes the busy handler (see BUSY) and, if that gives up, fails with SQLITE_BUSY. Locks are implemented with POSIX advisory locks (fcntl) on a few bytes at fixed offsets of the file (the lock-byte page near the 1 GB offset), LockFileEx on Windows.

UNLOCKEDno accessSHAREDread; many at onceRESERVEDintends to write; 1 onlyPENDINGno new SHAREDEXCLUSIVEwrites the file; aloneBEGIN / SELECTfirst write stmtcache spill / commitreaders goneCOMMIT or ROLLBACK: journal deleted, back to UNLOCKEDWhat can coexist (rollback-journal mode)SHARED + SHARED + SHARED: any number of readers.SHARED... + one RESERVED: readers keep reading while one writer prepares changes in its page cache.PENDING: writer waits for existing readers to finish; new readers get SQLITE_BUSY (this prevents writer starvation).EXCLUSIVE: nobody else, not even readers, until the commit finishes.WAL mode replaces this ladder: readers take a read-mark slot in the wal-index, a single WAL_WRITE_LOCK serialises writers,and readers never block the writer or the other way round.
 1  A: BEGIN;  SELECT ...            -- A: UNLOCKED -> SHARED
 2  B: BEGIN;  SELECT ...            -- B: SHARED (many readers are fine)
 3  A: UPDATE t SET ...              -- A: SHARED -> RESERVED (B still reads)
 4  B: UPDATE t SET ...              -- B holds SHARED and wants RESERVED, which A holds
 5  A: COMMIT;                       -- A would need PENDING then EXCLUSIVE: it must wait for B's SHARED to go
 6                                   -- if B also waited for A, both would wait forever (deadlock)
 7  SQLite refuses to let that happen: B's upgrade gets SQLITE_BUSY at once, without invoking the busy handler
 -- the fix is BEGIN IMMEDIATE (take RESERVED first), not a bigger timeout

Real scenarios: two web workers incrementing a counter with BEGIN then SELECT then UPDATE produce intermittent "database is locked"; a reporting script with an open read transaction stalls the nightly VACUUM; an app that opens a second connection inside a write transaction to read the same table hangs until the timeout.

ProductLock granularity for a writerReaders vs writer
SQLiteWhole database fileRollback mode: block at commit; WAL: never block
PostgreSQLRow (and table modes for DDL)MVCC, readers never block
MySQL InnoDBRow, gap and next-key locksMVCC consistent reads never block
SQL ServerRow, page, table; escalatesBlocking by default; READ_COMMITTED_SNAPSHOT avoids it
OracleRowUndo-based read consistency, no blocking
MongoDBDocumentWiredTiger MVCC
RedisNone needed; single command threadNot applicable
CockroachDBRow/key intentsMVCC

The lock modes of server databases are in Locks & Concurrency.

Fix / how to use it:

sql
-- inspect: which locking mode and mode of readers
PRAGMA locking_mode;            -- NORMAL (default); EXCLUSIVE keeps the lock after each transaction
PRAGMA locking_mode = EXCLUSIVE; -- single-process apps: no per-transaction lock traffic, nobody else can open

SQLITE_BUSY, busy_timeout and BEGIN IMMEDIATE Must-know ​

In plain words: When the lock you need is taken, SQLite either returns an error at once (database is locked) or waits a while if you told it to. The reliable pattern is to start every write transaction with BEGIN IMMEDIATE and set a busy timeout, so the wait happens at the start of the transaction where it is safe.

Common misunderstanding: "A big busy_timeout fixes all database is locked errors." Not those caused by a read-to-write upgrade: if your transaction already read a snapshot and the database changed since, waiting cannot help, because upgrading would let you write on stale data. SQLite returns SQLITE_BUSY (extended code SQLITE_BUSY_SNAPSHOT in WAL mode) immediately and the whole transaction must be retried.

Definition: SQLITE_BUSY (result code 5, "database is locked") means another connection holds a lock that conflicts with the one you need. SQLITE_LOCKED (6, "database table is locked") is a conflict inside one connection or a shared cache. Extended codes: SQLITE_BUSY_RECOVERY (261, another process is recovering a WAL), SQLITE_BUSY_SNAPSHOT (517, a read transaction cannot be upgraded to write because the database changed), SQLITE_BUSY_TIMEOUT (773, a blocking POSIX lock request in the VFS timed out; only with a special compile option). The busy handler is only consulted while the connection holds no lock yet; an upgrade from a held read lock is refused at once because waiting could deadlock. The busy handler is installed per connection with sqlite3_busy_handler or, usually, PRAGMA busy_timeout = ms / sqlite3_busy_timeout; the default is 0 (fail immediately). BEGIN takes three forms (Transaction page): BEGIN DEFERRED (the default: no lock until the first statement; a read starts a read transaction, a later write tries to upgrade and can fail with SQLITE_BUSY), BEGIN IMMEDIATE (take the write lock now; may fail with SQLITE_BUSY at BEGIN, where the busy handler can wait), and BEGIN EXCLUSIVE (like IMMEDIATE, and in rollback mode also blocks readers; in WAL mode it is the same as IMMEDIATE).

 1  -- WAL mode, default BEGIN DEFERRED, two connections, both read-then-write
 2  A: BEGIN;  SELECT balance FROM acc WHERE id=1;   -- read snapshot at commit 10
 3  B: BEGIN;  SELECT balance FROM acc WHERE id=1;   -- read snapshot at commit 10
 4  A: UPDATE acc SET balance = balance - 5 WHERE id=1;  COMMIT;   -- ok, creates commit 11
 5  B: UPDATE acc SET balance = balance - 5 WHERE id=1;  -- SQLITE_BUSY_SNAPSHOT: B's snapshot is stale
 6  B: ROLLBACK; and retry the whole transaction       -- waiting would not help
 7  -- with BEGIN IMMEDIATE at step 3 B would have waited (busy_timeout) for A at BEGIN, then read fresh data

Real scenarios: a queue worker doing BEGIN, SELECT the next job, UPDATE it to running fails randomly under concurrency until it switches to BEGIN IMMEDIATE; a Go service with a pool of 10 connections all trying to write sees database is locked and is fixed by a one-connection writer pool; a Laravel job queue on SQLite throws SQLSTATE[HY000]: General error: 5 database is locked until busy_timeout and transaction_mode => 'IMMEDIATE' are set.

Error textCodeCauseRetry?
database is lockedSQLITE_BUSY (5)Another connection holds a conflicting lockYes, whole transaction
database is locked (snapshot)SQLITE_BUSY_SNAPSHOT (517)Read-to-write upgrade on a stale snapshotYes, restart transaction
database table is lockedSQLITE_LOCKED (6)Same connection or shared-cache table lockFix the code path
attempt to write a readonly databaseSQLITE_READONLY (8)Read-only open, or directory/-shm not writableNo
database or disk is fullSQLITE_FULL (13)No spaceNo, free space
database disk image is malformedSQLITE_CORRUPT (11)Damaged fileNo, restore

Fix / how to use it: SQL first, then Go and Laravel (full programs are imported in Solving the classic problems).

sql
PRAGMA busy_timeout = 5000;      -- per connection, milliseconds
BEGIN IMMEDIATE;                 -- take the write lock now; waits up to busy_timeout
  UPDATE accounts SET balance = balance - 100 WHERE id = 1 AND balance >= 100;
  UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

Isolation in SQLite Important ​

In plain words: SQLite behaves as if transactions ran one at a time, because writers really do run one at a time. A reader sees one frozen picture of the data for its whole transaction.

Common misunderstanding: "SQLite has no isolation because it is simple." The Isolation In SQLite page states: "Except in the case of shared cache database connections with PRAGMA read_uncommitted turned on, all transactions in SQLite show "serializable" isolation. SQLite implements serializable transactions by actually serializing the writes." There are no dirty reads between separate connections.

Definition: Readers in WAL mode keep an end mark (a snapshot); in rollback mode a writer cannot finish until readers release SHARED, so a reader's data cannot change under it. A transaction that tries to turn a read into a write after the database changed fails instead of overwriting (no lost update). PRAGMA read_uncommitted = 1 is honoured only between connections sharing a cache, and is the only way to see uncommitted data. Within one connection, a statement sees changes made earlier by the same transaction. For the vocabulary (snapshot isolation, serial vs serializable, write skew) see Isolation Levels.

AnomalySQLite (separate connections, no shared cache)
Dirty write, dirty readNot possible
Non-repeatable read, phantomNot possible inside one transaction (snapshot / lock)
Lost updatePrevented: stale read-to-write upgrade returns SQLITE_BUSY
Write skewNot possible: writers are serialized
CostWriters queue; stale upgrades must be retried
ProductDefault isolationStrongest
SQLiteSerializable (single writer)Serializable
PostgreSQLRead CommittedSerializable (SSI)
MySQL InnoDBRepeatable ReadSerializable (locking reads)
SQL ServerRead Committed (locking, or RCSI on Azure SQL)Serializable, Snapshot
OracleRead CommittedSerializable (really snapshot isolation)
MongoDBSnapshot reads in transactions with read concern snapshotSnapshot
CockroachDBSerializableSerializable
RedisSingle-threaded command orderMULTI/EXEC as one step

Fix / how to use it: keep write transactions short and start with BEGIN IMMEDIATE; do not hold a read transaction open across user interaction; retry on SQLITE_BUSY.

Flexible typing, type affinity and STRICT tables Must-know ​

In plain words: In most databases a column of type INTEGER refuses text. In SQLite the value carries the type, and the column type is only a preference: it tries to convert what you insert and, if it cannot, stores it as it came. STRICT tables turn that off and behave like other databases.

Common misunderstanding: "VARCHAR(10) limits length and INTEGER limits type." Neither: length arguments are ignored, and INSERT INTO t(age) VALUES ('abc') into an INTEGER column succeeds unless the table is STRICT. The STRICT Tables page describes the default as "SQLite strives to be flexible regarding the datatype of the content that it stores".

Definition: There are five storage classes: NULL, INTEGER (1 to 8 bytes, signed), REAL (8-byte IEEE float), TEXT (UTF-8, UTF-16LE or UTF-16BE per database) and BLOB. A column has an affinity, derived from the declared type name by these rules in order: contains INT gives INTEGER; contains CHAR, CLOB or TEXT gives TEXT; contains BLOB or has no type gives BLOB (formerly NONE); contains REAL, FLOA or DOUB gives REAL; anything else gives NUMERIC. On insert, an INTEGER or NUMERIC column converts text that looks like a number into a number, a TEXT column converts numbers into text; values that cannot be converted losslessly are stored unchanged. INTEGER PRIMARY KEY (exactly that spelling) makes the column an alias of the rowid; AUTOINCREMENT additionally guarantees ids are never reused (via the sqlite_sequence table) at some cost. There are no boolean, date or decimal types: store booleans as 0/1, dates as ISO-8601 TEXT, Unix INTEGER or Julian REAL, money as integer minor units. STRICT tables (3.37.0, 2021-11-27) are opt-in per table: every column must be declared as one of INT, INTEGER, REAL, TEXT, BLOB or ANY, and a value that cannot be losslessly converted to the declared type is rejected with SQLITE_CONSTRAINT_DATATYPE (3091, message "cannot store TEXT value in INTEGER column t.a"). ANY keeps flexible typing for that column. A PRIMARY KEY column of a normal (non-WITHOUT ROWID, non-INTEGER) table may contain NULLs for historical reasons unless declared NOT NULL; STRICT and WITHOUT ROWID tables enforce it.

 1  CREATE TABLE loose (a INTEGER);
 2  INSERT INTO loose VALUES ('12'), ('abc'), (3.0), (X'ff');
 3  SELECT a, typeof(a) FROM loose;      -- 12 integer | abc text | 3 integer | blob  (no error)
 4  CREATE TABLE strict_t (a INTEGER) STRICT;
 5  INSERT INTO strict_t VALUES ('12');   -- ok: lossless conversion, stored as integer 12
 6  INSERT INTO strict_t VALUES ('abc');  -- Error: cannot store TEXT value in INTEGER column strict_t.a
 -- the same column, two behaviours: affinity coerces and tolerates, STRICT enforces

Real scenarios: a Laravel app on SQLite and production MySQL hides a bug where a string lands in an integer column; sorting a column that holds mixed integers and text orders by storage class first (NULL, then numbers, then text, then blobs); comparing '10' < '9' as text but 10 < 9 as numbers depending on affinity; a date column storing both '2025-01-02' and 1735776000 and failing a range query; money stored as REAL accumulating floating-point error.

ProductTyping
SQLiteDynamic; affinity; STRICT per table (3.37+)
PostgreSQLStatic, strict, rich (numeric, timestamptz, uuid, jsonb, arrays)
MySQL InnoDBStatic; in non-strict sql_mode silently truncates, in strict mode (default 8.x) errors
SQL ServerStatic, strict
OracleStatic, strict (NUMBER, VARCHAR2)
MongoDBDynamic per document (BSON types); optional JSON Schema validation
DuckDBStatic, strict, rich

See Schema Design for money, timestamps and key choice in general.

Fix / how to use it:

sql
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,                    -- rowid alias
  user_id     INTEGER NOT NULL REFERENCES users(id),
  total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
  status      TEXT    NOT NULL CHECK (status IN ('new', 'paid', 'shipped')),
  created_at  TEXT    NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
) STRICT;

In Go, database/sql scans by the Go destination type, so a stray TEXT in an integer column surfaces as a scan error at read time rather than a write error: another argument for STRICT. In Laravel migrations the column helpers generate affinity names and no STRICT, so add it with DB::statement('CREATE TABLE ... STRICT') or an ALTER-free rebuild, and rely on Eloquent casts for types.

PRAGMAs: journal_mode, synchronous, foreign_keys, cache_size, mmap_size, temp_store Must-know ​

In plain words: PRAGMAs are SQLite's configuration switches, set with SQL, and most of them apply to one connection only. A few (journal mode, page size) are stored in the file.

Common misunderstanding: "I ran PRAGMA foreign_keys = ON once at deploy time, so it is on." It is per connection and off by default in the library; each new pooled connection must set it again. Laravel does that for you (foreign_key_constraints), a raw Go database/sql pool does not unless the DSN carries it.

Definition: PRAGMAs read and write settings (PRAGMA name; reads, PRAGMA name = value; writes). The ones every service meets:

PRAGMADefaultWhat it doesPersisted in file?
journal_modedeleteDELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFFOnly WAL
synchronous2 (FULL)OFF (0), NORMAL (1), FULL (2), EXTRA (3): how often to fsyncNo
foreign_keys0 (off)Enforce REFERENCES constraintsNo
busy_timeout0Milliseconds to wait for a lockNo
cache_size-2000Negative = KiB (about 2 MiB), positive = pagesNo
mmap_size0Bytes of the file to access through mmapNo
temp_store0 (compile-time, usually file)DEFAULT 0, FILE 1, MEMORY 2 for temp tables and sort spillNo
page_size4096Page size; change before data or with VACUUM (not in WAL)Yes
wal_autocheckpoint1000Pages in WAL before an automatic checkpointNo
journal_size_limit-1 (none)Truncate WAL/journal to this size when finishedNo
locking_modeNORMALEXCLUSIVE keeps locks after a transactionNo
auto_vacuum0 (none)NONE, FULL, INCREMENTAL; must be set before tables existYes
user_version032-bit integer for your own schema versionYes
application_id0Identifies the file format of an applicationYes
query_only0Reject all writes on this connectionNo
read_uncommitted0Shared-cache only: see uncommitted rowsNo
secure_deletebuild-dependentOverwrite deleted content with zerosNo
recursive_triggers0Allow triggers to fire themselvesNo
case_sensitive_like0LIKE case sensitivity for ASCIINo
defer_foreign_keys0Postpone FK checks to commitNo
trusted_schema1Allow functions in views/triggers/checks to run unsafe code (set 0 for untrusted DBs)No
analysis_limit, optimizen/aPRAGMA optimize refreshes planner statistics; run before closingNo
integrity_check, quick_check, foreign_key_checkn/aVerify the file, quickly, or the FK constraintsNo
table_info, table_xinfo, index_list, index_info, compile_options, database_listn/aIntrospectionNo

synchronous in plain terms: FULL fsyncs the journal/WAL at every commit; in WAL mode NORMAL fsyncs only at checkpoint, so after a power loss (not an application crash) the most recent commits may be lost but the file is never corrupt; OFF hands everything to the OS and can corrupt on power loss; EXTRA also syncs the directory.

 1  PRAGMA synchronous = FULL;    COMMIT -> fsync(wal)            ~ one disk flush per commit
 2  PRAGMA synchronous = NORMAL;  COMMIT -> write(wal) only       ~ no flush; flush at checkpoint
 3  power cut after commit #42, WAL mode:
 4    FULL   -> commit #42 survives
 5    NORMAL -> commits since the last checkpoint may be gone; the database is consistent, just older
 6  application crash (kill -9) at any time -> committed data always survives in both (it is in the OS cache)

Real scenarios: a service with foreign_keys off in one code path accumulates orphan rows; cache_size left at 2 MiB makes a 5 GB database slow on a 16 GB machine; mmap_size accelerates read-heavy workloads on local SSD but a failing disk or truncated file can crash the process with SIGBUS instead of returning an I/O error; temp_store=MEMORY makes a big ORDER BY fast and a small container run out of memory.

Fix / how to use it:

sql
-- the server preset, executed on every new connection
PRAGMA journal_mode = WAL;
PRAGMA synchronous = NORMAL;
PRAGMA foreign_keys = ON;
PRAGMA busy_timeout = 5000;
PRAGMA cache_size = -65536;       -- 64 MiB
PRAGMA temp_store = MEMORY;
PRAGMA mmap_size = 268435456;     -- 256 MiB, local disks only
PRAGMA journal_size_limit = 67108864;
-- before closing a long-lived connection
PRAGMA optimize;

Modern SQL: upsert, RETURNING, window functions, CTEs, generated columns Important ​

In plain words: SQLite's SQL is far richer than its reputation: it has upsert, RETURNING, window functions, recursive queries, generated columns, partial and expression indexes, and transactional DDL.

Common misunderstanding: "SQLite has no ALTER TABLE and no real SQL." It supports RENAME, ADD COLUMN, RENAME COLUMN and, since 3.35.0, DROP COLUMN; changing a column's type or constraints needs the documented rebuild (create new table, copy, drop, rename) inside a transaction. DDL is transactional.

Definition: INSERT ... ON CONFLICT (cols) DO UPDATE SET ... (3.24.0) is the upsert, with excluded.col for the proposed row and DO NOTHING for ignore. RETURNING (3.35.0, 2021-03-12) on INSERT, UPDATE and DELETE returns the changed rows (including generated ids). Window functions (3.25.0): row_number(), rank(), dense_rank(), ntile(), lag(), lead(), first_value(), sum() OVER (PARTITION BY ... ORDER BY ... ROWS BETWEEN ...). CTEs with WITH and WITH RECURSIVE. Generated columns (3.31.0) AS (expr) VIRTUAL or STORED. Partial indexes (CREATE INDEX ... WHERE), expression indexes, RIGHT and FULL OUTER JOIN (3.39.0), ATTACH DATABASE to query several files, EXPLAIN QUERY PLAN to see the plan, ANALYZE and PRAGMA optimize for statistics in sqlite_stat1. The planner uses nested-loop joins (it may build a temporary automatic index for a join) and is described in The SQLite Query Planner; see Query Planning for the general plan-reading skills.

 1  INSERT INTO counters(name, n) VALUES ('hits', 1)
 2    ON CONFLICT(name) DO UPDATE SET n = n + 1 RETURNING n;      -- 1
 3  -- run again                                                   -- 2   (atomic: no select-then-update race)
 4  SELECT name, n FROM counters;                                  -- hits | 2

Real scenarios: idempotent consumers (INSERT ... ON CONFLICT DO NOTHING RETURNING), per-key counters, "latest row per group" with row_number(), running balance with sum() OVER, tree walks with WITH RECURSIVE, soft-delete uniqueness with a partial unique index, searching on lower(email) with an expression index.

FeatureSQLitePostgreSQLMySQL InnoDB
UpsertON CONFLICT DO UPDATEON CONFLICT DO UPDATEON DUPLICATE KEY UPDATE
RETURNINGYes (3.35+)YesNo (MariaDB yes)
Window functionsYes (3.25+)YesYes (8.0+)
Transactional DDLYesYesNo (implicit commit)
Partial indexYesYesNo
DROP COLUMNYes (3.35+)YesYes
Stored proceduresNoYesYes

Fix / how to use it:

sql
-- latest order per user, with a running total
WITH ranked AS (
  SELECT user_id, id, total_cents,
         row_number() OVER (PARTITION BY user_id ORDER BY id DESC) AS rn,
         sum(total_cents) OVER (PARTITION BY user_id ORDER BY id) AS running_cents
  FROM orders
)
SELECT * FROM ranked WHERE rn = 1;
-- soft delete + unique email only among live rows
CREATE UNIQUE INDEX users_email_live ON users(lower(email)) WHERE deleted_at IS NULL;
-- generated column
ALTER TABLE orders ADD COLUMN total_eur REAL GENERATED ALWAYS AS (total_cents / 100.0) VIRTUAL;

JSON and JSONB Important ​

In plain words: SQLite can store JSON in an ordinary TEXT column and has built-in functions to read and edit it. Since 3.45 it can also keep a faster binary form called JSONB.

Common misunderstanding: "There is a JSON type." There is no JSON column type; JSON is TEXT (or BLOB for JSONB) plus functions, and nothing validates it unless you add CHECK (json_valid(col)).

Definition: The functions were the optional JSON1 extension (added to the source tree in 3.9.0, enabled with -DSQLITE_ENABLE_JSON1) and are built in since 3.38.0 (2022-02-22): json(), json_valid(), json_extract(), the operators -> (returns JSON) and ->> (returns an SQL value), json_set, json_insert, json_replace, json_remove, json_patch, json_array, json_object, json_type, the aggregates json_group_array and json_group_object, and the table-valued functions json_each and json_tree. JSONB (3.45.0, 2024-01-15) is a binary encoding produced by jsonb() and the jsonb_* functions; it is stored as a BLOB, skips repeated text parsing, and is internal (not a stable interchange format). Index JSON with a generated column or an expression index.

 1  CREATE TABLE events (id INTEGER PRIMARY KEY, body TEXT NOT NULL CHECK (json_valid(body)));
 2  INSERT INTO events(body) VALUES ('{"user":{"id":7,"plan":"pro"},"tags":["a","b"]}');
 3  SELECT body ->> '$.user.plan' FROM events;           -- pro
 4  SELECT j.value FROM events, json_each(events.body, '$.tags') AS j;   -- a | b
 5  CREATE INDEX events_plan ON events (body ->> '$.user.plan');       -- expression index
 6  EXPLAIN QUERY PLAN SELECT id FROM events WHERE body ->> '$.user.plan' = 'pro';  -- SEARCH ... USING INDEX events_plan

Real scenarios: storing webhook payloads and querying a few fields, flexible per-tenant settings, event logs with a generated column on the event type, storing Laravel json or array casts.

ProductJSON support
SQLiteFunctions on TEXT; JSONB blob (3.45+); expression/generated-column indexes
PostgreSQLjson and jsonb types, GIN indexes, @>, SQL/JSON path
MySQL InnoDBJSON type with functional and multi-valued indexes
MongoDBNative BSON documents
SQL ServerJSON functions on NVARCHAR (and a native type in recent versions)
OracleJSON type and SQL/JSON

Fix / how to use it: keep hot, filterable fields as real columns; use JSON for the long tail; add CHECK (json_valid(...)); index the extracted expression. In Laravel $casts = ['settings' => 'array'] works on SQLite because Laravel serializes to a JSON string; where('settings->plan', 'pro') compiles to json_extract(...) and whereJsonContains to an exists (select 1 from json_each(...) where ...) subquery, per the Laravel 13 SQLiteGrammar. In Go scan into []byte or string and json.Unmarshal.

FTS5 full-text search Important ​

In plain words: FTS5 is a built-in search engine: you create a special virtual table, insert text, and ask MATCH for words, phrases or prefixes, ranked by relevance.

Common misunderstanding: "Full-text search needs Elasticsearch." For a corpus that fits on one node, FTS5 with bm25 ranking is fast and has no extra service; the cost is no stemming in other languages out of the box, no fuzzy matching and no clustering.

Definition: CREATE VIRTUAL TABLE docs USING fts5(title, body, tokenize = 'porter unicode61', prefix = '2 3'). Tokenizers: unicode61 (default), ascii, porter (stemming wrapper), trigram (substring and LIKE/GLOB acceleration, 3.34.0). Query with docs MATCH 'text'; syntax supports phrases "write ahead", AND/OR/NOT, prefix writ*, NEAR(a b, 5), column filters title:wal, and the initial-token anchor ^. Ranking with bm25(docs, w_title, w_body) (lower is better) or the hidden rank column; highlight() and snippet() format results. Variants: normal (content stored in the index), external content (content='posts' with triggers keeping it in sync), contentless (content='', index only). Maintenance commands via INSERT INTO docs(docs) VALUES('optimize' | 'rebuild' | 'integrity-check'). fts5vocab exposes term statistics. detail=none or column shrinks the index. Compile with ENABLE_FTS5 (most distributions include it; check PRAGMA compile_options). The conceptual comparison with PostgreSQL full-text and Elasticsearch is in Full-Text Search.

 1  CREATE VIRTUAL TABLE docs USING fts5(title, body, tokenize='porter unicode61');
 2  INSERT INTO docs VALUES ('WAL mode', 'Readers do not block writers in write-ahead logging'),
 3                         ('Rollback', 'The rollback journal is deleted at commit');
 4  SELECT title, bm25(docs) AS score FROM docs WHERE docs MATCH 'writer* OR journal' ORDER BY score;
 5  -- Rollback  | -1.07e-06
 6  -- WAL mode  | -9.39e-07      (negative: smaller = better match; tiny corpus, tiny numbers)
 7  SELECT snippet(docs, 1, '[', ']', '...', 8) FROM docs WHERE docs MATCH 'journal';
 8  -- The rollback [journal] is deleted at commit

Real scenarios: in-app search over notes, tickets or documentation; a changelog search in a desktop app; typeahead with a prefix index; a product catalogue search kept in sync with triggers.

ProductFull-text
SQLiteFTS5 virtual tables, bm25, tokenizers, single node
PostgreSQLtsvector/tsquery, GIN, ts_rank (also pg_trgm)
MySQL InnoDBFULLTEXT indexes, MATCH ... AGAINST
ElasticsearchDistributed Lucene index (not a database in this table's sense)
MongoDBText indexes and Atlas Search

Fix / how to use it:

sql
-- external-content table kept in sync with triggers
CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL) STRICT;
CREATE VIRTUAL TABLE posts_fts USING fts5(title, body, content='posts', content_rowid='id');
CREATE TRIGGER posts_ai AFTER INSERT ON posts BEGIN
  INSERT INTO posts_fts(rowid, title, body) VALUES (new.id, new.title, new.body);
END;
CREATE TRIGGER posts_ad AFTER DELETE ON posts BEGIN
  INSERT INTO posts_fts(posts_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);
END;
CREATE TRIGGER posts_au AFTER UPDATE ON posts BEGIN
  INSERT INTO posts_fts(posts_fts, rowid, title, body) VALUES ('delete', old.id, old.title, old.body);
  INSERT INTO posts_fts(rowid, title, body) VALUES (new.id, new.title, new.body);
END;
SELECT p.id, p.title FROM posts_fts f JOIN posts p ON p.id = f.rowid
WHERE posts_fts MATCH 'wal NEAR checkpoint' ORDER BY bm25(posts_fts) LIMIT 20;

The schema builder in Laravel has no FTS5 helper; create the virtual table with DB::statement in a migration and query with DB::select, as in the example imported under Laravel (not executed here: PHP is not installed on the authoring machine).

In-memory databases and shared cache Important ​

In plain words: A database named :memory: lives only in RAM and disappears when the connection closes. Every connection that opens :memory: gets its own, separate empty database.

Common misunderstanding: "Two connections to :memory: see the same data." The In-Memory Databases page: "Every :memory: database is distinct from every other. So, opening two database connections each with the filename ":memory:" will create two independent in-memory databases." With a connection pool, the migration you ran on connection 1 is invisible to connection 2.

Definition: Options: :memory: (private to one connection); an empty filename (private temporary on-disk database that SQLite may keep in cache); file::memory:?cache=shared or file:name?mode=memory&cache=shared (one in-memory database shared by all connections in the same process, which also needs URI filenames enabled and survives only while at least one connection is open); ATTACH ':memory:' AS aux. Shared-cache mode lets several connections in one process share one page cache and uses table-level locks (and SQLITE_LOCKED_SHAREDCACHE, 262, on conflict); the docs state: "Shared-cache mode is an obsolete feature. The use of shared-cache mode is discouraged. Most use cases for shared-cache are better served by WAL mode." Its only unique ability is PRAGMA read_uncommitted.

 1  Go: db, _ := sql.Open("sqlite", ":memory:")           -- pool may open connection #1
 2  db.Exec("CREATE TABLE t(a)")                          -- runs on connection #1
 3  db.Query("SELECT * FROM t")                           -- pool hands out connection #2 (#1 busy)
 4  -- Error: no such table: t      (connection #2 has its own empty database)
 5  fix A: db.SetMaxOpenConns(1)
 6  fix B: sql.Open("sqlite", "file:test?mode=memory&cache=shared")
 7  fix C: use a temp file (t.TempDir()) and the real WAL path, as production does

Real scenarios: unit tests, Laravel's default test configuration, throw-away analysis of a CSV, an in-process cache table, ATTACH an in-memory scratch database during a data migration.

ProductIn-memory mode
SQLite:memory:, shared-cache memory DB, temp_store=MEMORY
PostgreSQLNone built in (use UNLOGGED, tmpfs, or a test container)
MySQLMEMORY engine tables
RedisThe whole dataset is in memory
DuckDB:memory: default

Fix / how to use it: see Go for the pool settings and Laravel for DB_DATABASE=:memory:.

Limits Good to know ​

In plain words: SQLite has generous but real limits; almost none matter before write concurrency does.

Common misunderstanding: "SQLite cannot hold more than a few GB." The documented maximum database size is about 281 TB (at the 65536-byte page size); the site says the limit is "untested since the developers do not have access to hardware capable of reaching this limit". Practical limits are the single writer, backup time and the size of your disk.

Definition: from Limits In SQLite.

LimitDefaultCan changeNotes
Database sizeabout 281 TB (4294967294 pages × 65536 B); 17.5 TB at the 4096 B defaultPRAGMA max_page_countRows ≈ 2e13 at most
String or BLOB length1,000,000,000 bytes (SQLITE_MAX_LENGTH)Lower at runtime, raise to 2^31-1 at compile timeMax row size is the same
Columns per table2000 (SQLITE_MAX_COLUMN)Up to 32767 at compile timeSome code paths are O(N²) in columns
SQL statement length1,000,000,000 bytes by defaultsqlite3_limit
Tables in a join64NoBitmap in the planner
Attached databases10 (SQLITE_MAX_ATTACHED)Up to 125ATTACH
Bound parameters32766 (since 3.32.0), 999 beforesqlite3_limitBatch inserts with many ?
Page size4096512 to 65536, power of two
Trigger recursion depthLimited (SQLITE_MAX_TRIGGER_DEPTH)Compile timePrevents unbounded memory use

Fix / how to use it: batch inserts by transactions (not by thousands of ?), keep rows narrow, put big blobs in files or a separate database, and remember the 32766 parameter ceiling when building WHERE id IN (?, ?, ...) lists.

Backup and copy: .backup, VACUUM INTO, sqlite3_backup, sqlite3_rsync Must-know ​

In plain words: Do not copy the live file with cp. Ask SQLite to produce a consistent copy, which it can do while the app keeps running.

Common misunderstanding: "It is one file, so cp app.db backup.db is a backup." If a write is in progress, or the real state is partly in app.db-wal, you get a torn or stale copy. How To Corrupt An SQLite Database File lists "Backup or restore while a transaction is active" as a cause of corruption. A raw file copy is safe only when no connection is open (or the copy is an atomic filesystem snapshot that includes app.db and app.db-wal together).

Definition: Four safe tools. (1) The CLI .backup FILE (and the C online backup API sqlite3_backup_init, sqlite3_backup_step, sqlite3_backup_finish) copies pages incrementally; if another connection or process writes to the source during the copy, the copy is restarted (and may never finish if writes keep coming). (2) VACUUM INTO 'file' (3.27.0) writes a compacted copy that is a consistent snapshot of the original; the target must not exist (or must be an empty file), and if the machine loses power while it runs the output can be incomplete, so verify it. (3) sqlite3_rsync copies a live database to or from a remote system over SSH, transferring only changed pages. (4) Continuous replication of the WAL with Litestream (see Replication). .dump produces SQL text, portable but slow to restore. After a restore run PRAGMA integrity_check. The general strategy (RPO/RTO, PITR, test restores) is in Backup, PITR & Disaster Recovery.

 1  sqlite3 app.db ".backup 'backup-2025-01-02.db'"             -- online backup (backup API)
 2  sqlite3 app.db "VACUUM INTO 'backup-2025-01-02.db'"         -- compacted copy, WAL readers not blocked
 3  sqlite3 backup-2025-01-02.db "PRAGMA integrity_check"       -- ok
 4  -- WRONG:  cp app.db backup.db   (while the app is running)
 5  -- WRONG:  rsync app.db to another host while writers are active, without sqlite3_rsync

Real scenarios: a nightly cron running VACUUM INTO followed by upload to object storage; a pre-migration safety copy; a read-only reporting copy refreshed by sqlite3_rsync; a restore drill proving integrity_check passes.

MethodConsistent while live?OutputCost
cp / rsync of the filesNoSame filesCheapest, unsafe
.backup / backup APIYesSame pagesRestarts if other connections write meanwhile
VACUUM INTOYesCompacted copyReads whole DB, extra disk
sqlite3_rsyncYesReplica file (over SSH)Transfers only changed pages
LitestreamYesLTX files in object storageContinuous, small RPO
.dumpYesSQL textSlow restore
Filesystem snapshot (LVM, ZFS, EBS)If atomic for all filesWhole volumeNeeds journal/WAL included

Fix / how to use it: the Go program imported under Solving the classic problems runs VACUUM INTO and verifies the copy with PRAGMA integrity_check.

How a SQLite file gets corrupted Important ​

In plain words: SQLite is very hard to corrupt on its own. Almost all damage comes from outside: someone else writing to the file, locks that do not work, disks that lie about fsync, or hand-deleting the side files.

Common misunderstanding: "A crash or power failure corrupts SQLite." That is exactly what the journal and WAL prevent, provided the disk honours fsync and synchronous is not OFF. The documented causes are about the environment.

Definition: the headings of the How To Corrupt page, grouped:

CauseWhat happensPrevention
File overwrite by a rogue thread or process, including using a file descriptor after close()Random bytes in the fileDo not write to the file yourself; fix fd bugs
Backup or restore while a transaction is activeTorn copy.backup, VACUUM INTO, Litestream
Deleting a hot journal, or mispairing a database with a journalHalf-applied transactionNever delete -journal/-wal; move all files together
Filesystems with broken or missing locks (NFS, SMB, some Docker/VM mounts)Two writers at onceLocal disk only; one host
Two libraries with different locking protocols, multiple copies of SQLite linked inOne breaks the other's locksOne SQLite per process
Unlinking, renaming or hard-linking a database file in useJournal pairs with the wrong fileDo not move open files
fork() with an open connectionShared file descriptors and locksOpen after fork
Disks that do not honour fsync, synchronous=OFF, non-powersafe flashLost ordering after power lossKeep FULL or NORMAL in WAL on honest storage
Memory corruption in the host programBad pages writtenFix the program
WAL-mode bugs fixed in specific versions (the WAL-reset bug in 3.7.0 through 3.51.2, fixed in 3.51.3 on 2026-03-13)Rare raceUpgrade

Fix / how to use it: detect with PRAGMA integrity_check (full) or PRAGMA quick_check, and PRAGMA foreign_key_check; recover with the CLI .recover command (best effort) or restore from backup; never run two replicas of a service against one file on shared network storage.

The testing culture behind SQLite Good to know ​

In plain words: SQLite is trusted because it is tested more than almost any database: the test code is hundreds of times larger than the library.

Common misunderstanding: "100% coverage means no bugs." The project does not claim that; it claims every branch is exercised and then adds fuzzing, crash, I/O-error and out-of-memory tests to find what coverage cannot.

Definition: from How SQLite Is Tested: "100% branch test coverage in an as-deployed configuration", plus 100% MC/DC (modified condition/decision coverage), four independently developed harnesses (the TCL tests, the proprietary TH3 harness, SQL Logic Test, and the fuzzers dbsqlfuzz and jfuzz with OSS-Fuzz), out-of-memory tests, I/O-error tests, crash and power-loss tests, and as of 3.42.0 (2023-05-16) roughly 155.8 KSLOC of library code against 92053.1 KSLOC of test code (590 times as much). That culture is why it can be used in aviation software, and why a bug in SQLite is a rare event compared with a bug in the application around it.

Test layerWhat it catches
TCL testsBehaviour and regressions
TH3 (branch/MC/DC)Coverage on the as-deployed binary
SQL Logic TestSame answers as other engines
Fuzzers (dbsqlfuzz, jfuzz, OSS-Fuzz)Malformed SQL and malformed database files
Crash/power-loss simulationAtomic commit correctness

For your own application the equivalent is to test against the real engine, in WAL mode, with the real PRAGMAs, not only a mock.

Per-product behaviour: SQLite against PostgreSQL, MySQL, DuckDB and the rest ​

AxisSQLitePostgreSQLMySQL InnoDBDuckDB
ArchitectureIn-process libraryClient/server, process per connectionClient/server, thread per connectionIn-process library
WorkloadOLTP-lite, embeddedGeneral OLTP, strong SQLWeb OLTPOLAP, columnar scans
Concurrent writersOne (database lock)Many (row locks, MVCC)Many (row locks)One writer process, multi-threaded queries
Readers vs writerWAL: no blockingNo blocking (MVCC)No blocking (consistent reads)Snapshot-based
Default isolationSerializableRead CommittedRepeatable ReadSnapshot isolation (MVCC, optimistic)
Network accessNone (file)Wire protocolWire protocolNone (file)
Auth and rolesNone (file permissions)Roles, RLS, SCRAMUsers and grantsNone
TypesDynamic, STRICT optionalRich, strictStrict-ishRich, strict
ReplicationExternal (Litestream, LiteFS, rqlite)Streaming and logicalBinlogNone
Online schema changeALTER limited, rebuildMostly onlineOnline DDL/gh-ostn/a
Max size281 TB nominalEffectively diskEffectively diskDisk, memory-aware
Ops costNear zeroReal (vacuum, backups, HA)RealNear zero
Best useEmbedded, edge, single-node appSystem of recordWeb appsAnalytics on files and local data
DimensionSQL ServerOracleMongoDBCockroachDBRedis
Where SQLite differsServer, T-SQL, locking by defaultServer, PL/SQL, enterpriseDocument model, serverDistributed SQL, serializableIn-memory structures, server
When to pick it insteadMicrosoft stack, enterprise BIExisting enterprise estatesFlexible documents at scaleMulti-region SQLCache, queues, counters

DuckDB's own positioning page says it adopted "the ideas of simplicity and in-process operation" from SQLite but targets analytical workloads: use SQLite for transactions inside an app and DuckDB when you scan and aggregate millions of rows (OLTP vs OLAP). A common pairing is SQLite as the transactional store and DuckDB reading the same data for reports.

Replication and scale-out: Litestream, LiteFS, rqlite, libSQL/Turso ​

SQLite has no replication of its own, and the file cannot be shared over a network filesystem for writing. Four projects add the missing layer; they differ in what they replicate, who may write, and what a failure costs. Verify each one's current status in its own docs before adopting it: the Fly.io page says LiteFS is "stable and running in production environments" but "still pre-1.0 so APIs may change", and the libSQL README says new features are now developed in the separate Turso database.

ToolMechanismWritersFailoverTypical use
LitestreamTakes over checkpointing, streams new WAL pages as LTX files to object storage (S3, GCS, Azure, SFTP, NATS and others); restore rebuilds the fileOne (the app)None automatic; you restore elsewhereContinuous backup, point-in-time restore, disaster recovery
LiteFS (Fly.io)A FUSE file system that intercepts writes and ships transactions to replicasOne primary chosen by a lease (Consul), others read-onlyLease moves the primaryRead replicas close to users on Fly.io or Docker
rqliteRaft consensus over SQLite, HTTP/JSON API, clustering via Kubernetes, Consul, etcd or DNSOne leaderAutomatic leader electionA small, highly available relational store, "think etcd, but with relational modeling available"
libSQL / TursoA fork of SQLite with embedded replicas and a remote server; the Turso database is a Rust rewrite aiming at concurrent writeslibSQL keeps the single-writer modelHosted servicePer-tenant databases, edge reads

Litestream, step by step (from How it works): Litestream "works by effectively taking over the checkpointing process. It starts a long-running read transaction to prevent any other process from checkpointing and restarting the WAL file. Instead, it continually reads new WAL pages and manually calls out to SQLite to perform checkpoints as necessary." New pages are packaged into LTX files named by the transaction-id range they cover, then compacted into levels (the docs list merges every 30 seconds, 5 minutes, and so on) and uploaded; a restore downloads a snapshot and replays the LTX files up to the requested point.

 1  app (WAL mode)  ->  COMMIT #101..#107 appended to app.db-wal
 2  litestream replicate:   read new WAL pages -> LTX file 0000000000000101-0000000000000107.ltx
 3  upload LTX to s3://bucket/app/ltx/0/   (small, frequent); background compaction merges levels
 4  disk lost at 12:00:03
 5  new host: litestream restore -o app.db s3://bucket/app    -- snapshot + replay LTX files in order
 6  start the app on the restored file
 -- replication is asynchronous: commits not yet uploaded at step 4 (seconds worth) are lost, the database is consistent

What each tool does not do: Litestream is a backup and restore tool, not a failover or read-scaling tool (its separate VFS extension can serve read-only queries from object storage). LiteFS replicas are read-only and write requests must reach the primary (an HTTP proxy can forward them), so read-your-writes needs care (see In architecture). rqlite changes the interface: you talk HTTP and SQL strings, not a library and a file, and it offers tunable read consistency (none, weak, strong, linearizable, auto per its read-consistency docs) at the cost of Raft's write latency. libSQL, per its README, "inherits SQLite's fundamental limitations such as the single-writer model". All of them leave you with one logical writer: they scale reads and durability, not write throughput. The consensus theory behind rqlite is in Distributed SQL, Consensus & 2PC, and replication lag and failover patterns in Replication & Failover.

Go: modernc.org/sqlite, mattn/go-sqlite3 and the pool ​

Go reaches SQLite through database/sql and one of two drivers.

modernc.org/sqlitegithub.com/mattn/go-sqlite3
ImplementationPure Go (C source transpiled), no cgocgo wrapper around the C amalgamation
Driver name"sqlite""sqlite3"
BuildCross-compiles with plain go buildNeeds CGO_ENABLED=1 and a C compiler
DSN options?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL), _txlock=immediate, _time_format?_busy_timeout=5000&_journal_mode=WAL&_txlock=immediate&_foreign_keys=1
NotesA _pragma value is run as SQL text, so build it from trusted input onlyMature, the long-time default

The pool is the trap. database/sql opens as many physical SQLite connections as it needs, and everything that is per connection (PRAGMAs, temp tables, :memory: databases, the busy timeout) applies to each of them separately. With a file database in WAL mode that is exactly what you want for readers, and exactly what you do not want for writers, because ten connections racing for the one write lock produce SQLITE_BUSY. The recommended layout, in the snippet below, is two *sql.DB handles over the same file: a writer with SetMaxOpenConns(1) and _txlock=immediate, and a reader pool with query_only.

QuestionAnswer
Single connection or a pool?One connection for writes; a pool (4 to 16) of read connections
Where do PRAGMAs go?In the DSN, so every new physical connection gets them
Which BEGIN?_txlock=immediate for the writer pool, so the lock wait happens at BEGIN
:memory: in tests?Use SetMaxOpenConns(1), or file::memory:?cache=shared, or a file under t.TempDir()
Context cancellation?The drivers interrupt the running statement (sqlite3_interrupt); the write transaction rolls back
Idle connection lifetimeKeep them (SetConnMaxLifetime(0)): closing the last connection checkpoints the WAL, reopening costs a schema read
go
// Package pool shows the recommended Go layout: one writer connection and a
// separate pool of readers, both on the same WAL-mode file.
package pool

import (
	"database/sql"
	"fmt"
	"net/url"

	_ "modernc.org/sqlite"
)

// Store keeps two *sql.DB handles over one database file.
type Store struct {
	W *sql.DB // exactly one connection: serialises writers inside the process
	R *sql.DB // many connections: readers never block in WAL mode
}

func dsn(path string, extra ...string) string {
	q := url.Values{}
	q.Add("_pragma", "busy_timeout(5000)") // first, so the next PRAGMAs can wait for a lock
	q.Add("_pragma", "journal_mode(WAL)")
	q.Add("_pragma", "synchronous(NORMAL)")
	q.Add("_pragma", "foreign_keys(1)")
	q.Add("_pragma", "temp_store(MEMORY)")
	for _, e := range extra {
		q.Add("_pragma", e)
	}
	return "file:" + path + "?" + q.Encode()
}

// Open creates both pools. Each new physical connection runs the _pragma list,
// because PRAGMAs such as foreign_keys and busy_timeout are per connection.
func Open(path string) (*Store, error) {
	w, err := sql.Open("sqlite", dsn(path)+"&_txlock=immediate")
	if err != nil {
		return nil, err
	}
	w.SetMaxOpenConns(1) // one writer at a time, no SQLITE_BUSY between our own goroutines
	w.SetMaxIdleConns(1)

	r, err := sql.Open("sqlite", dsn(path, "query_only(1)"))
	if err != nil {
		return nil, err
	}
	r.SetMaxOpenConns(8)

	s := &Store{W: w, R: r}
	if _, err := w.Exec(`CREATE TABLE IF NOT EXISTS accounts (
		id      INTEGER PRIMARY KEY,
		owner   TEXT NOT NULL,
		balance INTEGER NOT NULL CHECK (balance >= 0)
	) STRICT`); err != nil {
		return nil, fmt.Errorf("migrate: %w", err)
	}
	return s, nil
}

// Close releases both pools.
func (s *Store) Close() error {
	werr := s.W.Close()
	if err := s.R.Close(); err != nil {
		return err
	}
	return werr
}

// Withdraw is a read-modify-write that is safe because the transaction starts
// with BEGIN IMMEDIATE (_txlock=immediate) and the update is atomic anyway.
func (s *Store) Withdraw(id, amount int64) error {
	res, err := s.W.Exec(`UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?`, amount, id, amount)
	if err != nil {
		return err
	}
	n, err := res.RowsAffected()
	if err != nil {
		return err
	}
	if n == 0 {
		return fmt.Errorf("insufficient funds or unknown account %d", id)
	}
	return nil
}

The same policy for the cgo driver:

go
// The same connection policy with github.com/mattn/go-sqlite3 (cgo driver).
// DSN keys use the form _journal_mode, _busy_timeout, _txlock, _foreign_keys.
package main

import (
	"database/sql"
	"fmt"
	"log"

	_ "github.com/mattn/go-sqlite3"
)

func main() {
	dsn := "file:app.db?_journal_mode=WAL&_busy_timeout=5000&_synchronous=NORMAL&_foreign_keys=1&_txlock=immediate"
	db, err := sql.Open("sqlite3", dsn) // the driver name is "sqlite3", not "sqlite"
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	db.SetMaxOpenConns(1) // writer pool

	var mode string
	if err := db.QueryRow(`PRAGMA journal_mode`).Scan(&mode); err != nil {
		log.Fatal(err)
	}
	fmt.Println("journal_mode:", mode)
}

Laravel: the sqlite driver, config keys and tests ​

Laravel's sqlite connection uses PHP's pdo_sqlite (SQLite 3.26.0 or newer per the Laravel 13 database docs). You point DB_DATABASE at an absolute path to a file; foreign key constraints are enabled by default for SQLite connections (DB_FOREIGN_KEYS=false turns that off). The Laravel 13 application skeleton's config/database.php also ships four SQLite keys, busy_timeout, journal_mode, synchronous and transaction_mode (default DEFERRED), which map directly to the PRAGMAs and the BEGIN flavour on this page.

php
<?php

// config/database.php (excerpt). Laravel 13's application skeleton ships these
// four SQLite keys; the defaults keep SQLite's own behaviour (null = not set).
return [
    'connections' => [
        'sqlite' => [
            'driver' => 'sqlite',
            'url' => env('DB_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
            // Wait up to 5 s for a lock instead of failing with SQLITE_BUSY.
            'busy_timeout' => 5000,
            // WAL: readers do not block the writer and vice versa.
            'journal_mode' => 'WAL',
            // NORMAL is safe against application crashes in WAL mode.
            'synchronous' => 'NORMAL',
            // BEGIN IMMEDIATE takes the write lock up front, so a
            // read-then-write transaction cannot hit SQLITE_BUSY halfway.
            'transaction_mode' => 'IMMEDIATE',
        ],
    ],
];

Things that differ from MySQL or PostgreSQL in a Laravel app:

TopicOn SQLite
lockForUpdate() and sharedLock()SQLiteGrammar::compileLock returns an empty string: no row lock is emitted. The protection is the database write lock, which you obtain with transaction_mode => 'IMMEDIATE'
DB::transaction($cb, $attempts)The attempts argument retries when ConcurrencyErrorDetector recognises the message; its list includes database is locked and database table is locked, so SQLite busy errors are retried (immediately, with no sleep in ManagesTransactions; add your own backoff outside if you need one)
Database queue, cache and session driversThey write often; set busy_timeout and WAL, and prefer the Redis or file driver at higher concurrency
php artisan test --parallelEach worker process needs its own database file; :memory: is already private per process
Schema:: builderTypes become affinities; STRICT, WITHOUT ROWID and FTS5 need DB::statement
JSON where clausesSupported on SQLite 3.39.0 or newer per the Laravel 13 queries docs
RefreshDatabaseRuns each test inside a transaction; with :memory: the connection must be the same PDO, which Laravel keeps

Testing with :memory:. The Laravel 13 skeleton's phpunit.xml sets DB_CONNECTION to sqlite and DB_DATABASE to :memory:, so each test run gets a private, throw-away database that is fast and needs no setup; the RefreshDatabase trait migrates once and wraps each test in a transaction. The trade-off is that you test against SQLite's typing and DDL rules, not your production engine's. If production is PostgreSQL or MySQL, run the integration suite against the real engine in CI as well and keep SQLite for fast feedback.

php
<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;

// phpunit.xml in the Laravel 13 skeleton sets DB_CONNECTION=sqlite and
// DB_DATABASE=:memory:, so every test process gets a private, throw-away database.
class FtsSearchTest extends TestCase
{
    use RefreshDatabase;

    public function test_fts5_match_returns_ranked_rows(): void
    {
        // Raw DDL: the schema builder has no FTS5 virtual tables.
        DB::statement("CREATE VIRTUAL TABLE docs USING fts5(title, body, tokenize = 'porter unicode61')");
        DB::table('docs')->insert([
            ['title' => 'WAL', 'body' => 'Readers do not block writers'],
            ['title' => 'Rollback', 'body' => 'The journal is deleted at commit'],
        ]);

        $rows = DB::select('SELECT title FROM docs WHERE docs MATCH ? ORDER BY bm25(docs)', ['writer*']);

        $this->assertSame('WAL', $rows[0]->title);
        $this->assertTrue(Schema::hasTable('docs'));
    }

    public function test_strict_table_rejects_wrong_type(): void
    {
        DB::statement('CREATE TABLE strict_t (a INTEGER) STRICT');

        $this->expectException(\Illuminate\Database\QueryException::class);
        DB::insert('INSERT INTO strict_t (a) VALUES (?)', ['abc']);
    }
}

Mechanics ​

Files on disk, sidecar files and URI parameters ​

FileWhen it existsMeaningSafe to delete?
app.dbAlwaysMain databaseNo
app.db-journalRollback mode during a write, or after a crashOriginal pages for rollback; hot journal = pending recoveryNever while a hot journal exists
app.db-walWAL mode while open, or after a crashCommitted frames not yet checkpointedNever: it holds committed data
app.db-shmWAL mode while openwal-index in shared memory (rebuilt from the WAL)Only when no process has the database open
Temporary files (named etilqs_...)Large sorts, VACUUM, temp_store=FILETemporary spillHandled by SQLite

URI filenames (file:app.db?mode=ro&immutable=1, enabled by SQLITE_OPEN_URI or the file: prefix in the drivers): mode=ro / rw / rwc / memory, cache=shared / private, immutable=1 (file will never change: no locking, for read-only media), nolock=1 (skip locking: only if nothing else writes), vfs=name (choose a VFS), psow=1. Threading mode is a compile/start-up choice: single-thread, multi-thread (a connection must not be used by two threads at once; THREADSAFE=2), serialized (THREADSAFE=1, a mutex per connection). The Go and PHP drivers already cope with this.

OffsetSizeFieldPractical use
016SQLite format 3\0file app.db detects it; file is not a database (SQLITE_NOTADB, 26) otherwise
162Page sizeFixed at creation (or VACUUM)
18, 191, 1Write and read format version (1 legacy, 2 WAL)2 means WAL mode is persistent
244File change counterOther connections invalidate caches when it changes
284Size in pagesTruncated files are detected
32, 364, 4Freelist trunk page, freelist countFree space reusable inside the file
404Schema cookieBumped on DDL; prepared statements re-prepare
564Text encoding (1 UTF-8, 2 UTF-16le, 3 UTF-16be)Chosen at creation
604user_versionYour own migration number (PRAGMA user_version)
684application_idIdentify your file format

Result codes you meet ​

CodeNameMeaningAction
5SQLITE_BUSYLock held by another connectionRetry transaction with backoff
261SQLITE_BUSY_RECOVERYAnother process is recovering the WALRetry
517SQLITE_BUSY_SNAPSHOTStale snapshot cannot upgrade to writeRestart transaction
773SQLITE_BUSY_TIMEOUTA blocking POSIX lock request in the VFS timed out (needs SQLITE_ENABLE_SETLK_TIMEOUT; not the ordinary busy_timeout expiry, which returns plain 5)Retry or fail
6SQLITE_LOCKEDConflict inside one connection or shared cacheFix code (finalize statements)
262SQLITE_LOCKED_SHAREDCACHEShared-cache table lockDrop shared cache, use WAL
8SQLITE_READONLYCannot writeCheck permissions, -shm, directory
10SQLITE_IOERRDisk I/O failureTreat as fatal, check storage
11SQLITE_CORRUPTMalformed databaseRestore from backup
13SQLITE_FULLDisk full or max page countFree space
14SQLITE_CANTOPENCannot open filePath, permissions, directory
19SQLITE_CONSTRAINTConstraint failedSubcodes below
2067 / 1555..._UNIQUE / ..._PRIMARYKEYDuplicate keyUpsert or report conflict
787 / 1299 / 275..._FOREIGNKEY / ..._NOTNULL / ..._CHECKConstraint violationFix data
3091SQLITE_CONSTRAINT_DATATYPESTRICT type mismatchFix the type

Solving the classic problems ​

Problem 1: "database is locked" under concurrent writers ​

SolutionHowAdvantageCost or limit
WAL + busy_timeoutjournal_mode=WAL, busy_timeout=5000Readers stop colliding with the writer; short waits succeedWriters still queue
BEGIN IMMEDIATETake the write lock at BEGINNo stale-snapshot upgrade failuresRead-only work should use plain BEGIN
One writer connectionSetMaxOpenConns(1) or a single writer queueContention happens in memory, not on file locksOne in-process write at a time
Short transactionsNo network calls or user waits inside a write transactionLock held for microsecondsNeeds discipline
BatchingOne transaction for many rowsOne fsync, one lockLarger rollback on failure
Retry with backoffRe-run on SQLITE_BUSYAbsorbs burstsMust be idempotent

The Go program below shows the failure and the cure: with busy_timeout(0) the second writer fails at once with database is locked (5) (SQLITE_BUSY); with a 2 s timeout it waits about 300 ms for the first to commit and succeeds.

go
// Two connections write at the same time. With the default DEFERRED
// transaction and no busy timeout the loser gets SQLITE_BUSY at once.
package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	_ "modernc.org/sqlite"
)

func open(dsn string) *sql.DB {
	db, err := sql.Open("sqlite", dsn)
	if err != nil {
		log.Fatal(err)
	}
	return db
}

func main() {
	dir, err := os.MkdirTemp("", "sqlite-busy")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "app.db")

	// busy_timeout=0 means: fail immediately instead of waiting for the lock.
	a := open("file:" + path + "?_pragma=journal_mode(WAL)&_pragma=busy_timeout(0)")
	b := open("file:" + path + "?_pragma=journal_mode(WAL)&_pragma=busy_timeout(0)")
	defer a.Close()
	defer b.Close()

	if _, err := a.Exec(`CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)`); err != nil {
		log.Fatal(err)
	}

	// Writer A takes the write lock and keeps it for 300 ms.
	txA, err := a.Begin()
	if err != nil {
		log.Fatal(err)
	}
	if _, err := txA.Exec(`INSERT INTO t (v) VALUES ('from A')`); err != nil {
		log.Fatal(err)
	}

	// Writer B tries while A holds the lock.
	_, err = b.Exec(`INSERT INTO t (v) VALUES ('from B')`)
	fmt.Println("B without timeout:", err, "retryable:", isBusy(err)) // database is locked (5) (SQLITE_BUSY)

	time.AfterFunc(300*time.Millisecond, func() { _ = txA.Commit() })

	// Now B waits up to 2 s for the lock before giving up.
	if _, err := b.Exec(`PRAGMA busy_timeout = 2000`); err != nil {
		log.Fatal(err)
	}
	start := time.Now()
	_, err = b.Exec(`INSERT INTO t (v) VALUES ('from B')`)
	fmt.Printf("B with 2s timeout: err=%v waited=%s\n", err, time.Since(start).Round(50*time.Millisecond))

	var n int
	if err := b.QueryRow(`SELECT count(*) FROM t`).Scan(&n); err != nil {
		log.Fatal(err)
	}
	fmt.Println("rows:", n)
}

// isBusy reports whether err is SQLITE_BUSY or SQLITE_LOCKED: the caller may
// retry the whole transaction. modernc.org/sqlite puts the code name in the text.
func isBusy(err error) bool {
	return err != nil && (strings.Contains(err.Error(), "SQLITE_BUSY") || strings.Contains(err.Error(), "SQLITE_LOCKED"))
}

Laravel equivalent: the transaction_mode => 'IMMEDIATE' and busy_timeout keys shown above, plus the service below, where the $attempts argument of DB::transaction re-runs the closure when Laravel's concurrency-error detector sees database is locked.

php
<?php

namespace App\Services;

use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

class Transfer
{
    /**
     * Move money between two accounts on a SQLite connection configured with
     * 'transaction_mode' => 'IMMEDIATE'. The conditional UPDATE is atomic;
     * IMMEDIATE makes DB::transaction() acquire the write lock at BEGIN.
     *
     * The second argument of DB::transaction() is the number of attempts.
     * Laravel's ConcurrencyErrorDetector treats "database is locked" as a
     * concurrency error, so the closure is run again (immediately, no sleep).
     */
    public function run(int $from, int $to, int $amount): void
    {
        DB::transaction(function () use ($from, $to, $amount) {
            $moved = DB::update(
                'UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?',
                [$amount, $from, $amount]
            );

            if ($moved === 0) {
                throw new \DomainException('Insufficient funds');
            }

            DB::update('UPDATE accounts SET balance = balance + ? WHERE id = ?', [$amount, $to]);
        }, 3);
    }

    /** Use this when you want a pause between attempts (backoff with jitter). */
    public function runWithBackoff(int $from, int $to, int $amount, int $attempts = 3): void
    {
        for ($i = 1; ; $i++) {
            try {
                $this->run($from, $to, $amount);

                return;
            } catch (QueryException $e) {
                $busy = str_contains($e->getMessage(), 'database is locked');
                if (! $busy || $i >= $attempts) {
                    throw $e;
                }
                usleep(random_int(20_000, 80_000) * $i);
            }
        }
    }
}

Problem 2: slow commits ​

Each commit costs fsyncs. WAL plus synchronous=NORMAL removes most of them, and wrapping many inserts in one transaction removes the rest.

go
// Compares rollback-journal (DELETE) and WAL for many small commits.
package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"

	_ "modernc.org/sqlite"
)

func run(mode string, n int) time.Duration {
	dir, err := os.MkdirTemp("", "sqlite-bench")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)
	dsn := fmt.Sprintf("file:%s?_pragma=journal_mode(%s)&_pragma=synchronous(FULL)", filepath.Join(dir, "b.db"), mode)
	db, err := sql.Open("sqlite", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	db.SetMaxOpenConns(1)
	if _, err := db.Exec(`CREATE TABLE x (id INTEGER PRIMARY KEY, v TEXT)`); err != nil {
		log.Fatal(err)
	}
	start := time.Now()
	for i := 0; i < n; i++ { // one implicit transaction (one fsync round) per insert
		if _, err := db.Exec(`INSERT INTO x (v) VALUES (?)`, fmt.Sprintf("row %d", i)); err != nil {
			log.Fatal(err)
		}
	}
	return time.Since(start)
}

func main() {
	const n = 2000
	for _, m := range []string{"DELETE", "WAL"} {
		d := run(m, n)
		fmt.Printf("%-6s %d commits in %s (%.0f commits/s)\n", m, n, d.Round(time.Millisecond), float64(n)/d.Seconds())
	}
}

Problem 3: backup of a live database ​

go
// Online backup of a live database with VACUUM INTO, plus an integrity check.
package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"path/filepath"

	_ "modernc.org/sqlite"
)

func main() {
	dir, err := os.MkdirTemp("", "sqlite-backup")
	if err != nil {
		log.Fatal(err)
	}
	defer os.RemoveAll(dir)

	src, err := sql.Open("sqlite", "file:"+filepath.Join(dir, "live.db")+"?_pragma=journal_mode(WAL)")
	if err != nil {
		log.Fatal(err)
	}
	defer src.Close()
	if _, err := src.Exec(`CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT); INSERT INTO t (v) VALUES ('a'), ('b')`); err != nil {
		log.Fatal(err)
	}

	// VACUUM INTO writes a compacted, consistent copy while readers and the
	// writer keep working. The target file must not exist yet.
	dst := filepath.Join(dir, "backup.db")
	if _, err := src.Exec(`VACUUM INTO ?`, dst); err != nil {
		log.Fatal(err)
	}

	bk, err := sql.Open("sqlite", "file:"+dst+"?mode=ro")
	if err != nil {
		log.Fatal(err)
	}
	defer bk.Close()
	var check string
	var n int
	if err := bk.QueryRow(`PRAGMA integrity_check`).Scan(&check); err != nil {
		log.Fatal(err)
	}
	if err := bk.QueryRow(`SELECT count(*) FROM t`).Scan(&n); err != nil {
		log.Fatal(err)
	}
	fmt.Println("integrity_check:", check, "rows:", n) // ok, 2
}

Problem 4: types that are wrong in production ​

Create tables as STRICT, add CHECK constraints for enumerations and CHECK (json_valid(col)), turn foreign_keys on in every connection, and run PRAGMA foreign_key_check and PRAGMA integrity_check in CI against a copy of production.

Retry and failure handling ​

ErrorMeaningRetry?Rule
SQLITE_BUSY at BEGIN IMMEDIATELock heldYesBackoff with jitter; the busy handler already waited busy_timeout
SQLITE_BUSY mid-transaction (deferred upgrade)Stale snapshot or deadlock avoidanceYes, the whole transactionSwitch to BEGIN IMMEDIATE so it stops happening
SQLITE_BUSY_RECOVERYAnother process replaying WALYesShort wait
SQLITE_LOCKEDSame-connection conflictNoFix code
SQLITE_FULL, SQLITE_IOERR, SQLITE_CORRUPTEnvironmentNoAlert, restore
SQLITE_CONSTRAINT_*Data ruleNoReport to caller

Rules: retry the whole transaction, never a single statement inside it; make the transaction idempotent (use INSERT ... ON CONFLICT, idempotency keys, conditional UPDATE); cap attempts; use exponential backoff with jitter; put the wait before the work by taking the lock at BEGIN IMMEDIATE. The Go classifier is isBusy in the busy-demo snippet; in Laravel pass the attempts argument to DB::transaction (see Transfer::run above), and use runWithBackoff only when you want backoff between attempts. The general retry design is in Deadlocks and Optimistic vs Pessimistic Locking.

Choosing: when SQLite is the right production database ​

Data lives next toone app process?yesWrites are short andfit one node?yesSQLite + WALthen add what you needLitestreambackup to S3, restoreLiteFS / libSQLread replicas, 1 primaryrqliteRaft, HTTP, failoverno: many app servers share itno: many concurrent writersPostgreSQL / MySQL (client/server)network access, many writers, roles, replicasDuckDBembedded too, but columnar: big scans and aggregatesanalytics?The left branch is the design limit, not a bug: one file, one writer at a time, no network protocol.
WorkloadRecommendationExtra techniqueReason
Mobile and desktop apps, browsers, IoTSQLiteuser_version migrationsNo server possible; it is the default everywhere
Application file formatSQLiteapplication_idOne file, atomic saves, queryable
Unit and integration testsSQLite :memory: (or temp file)Also run CI on the real engineFast and private
Single-server web app, read-heavy, writes under a few hundred per secondSQLite in WAL modeLitestream backupOne less component, microsecond reads
Per-tenant databasesSQLite, one file per tenantATTACH for admin queries, Litestream per fileIsolation, easy export and delete
Edge or multi-region read-mostlySQLite plus LiteFS or libSQL replicasWrite forwarding to the primaryLocal reads
Small HA store with automatic failoverrqliteOdd node count (3 or 5)Raft failover
Many app servers writing one datasetPostgreSQL or MySQLConnection poolerNetwork, row locks, roles
High write concurrency or long write transactionsPostgreSQL or MySQLPartitioningOne-writer rule is the limit
Heavy analytics over very large dataDuckDB or a warehouseExport from SQLiteColumnar scans
Need roles, RLS, audit, online schema changePostgreSQLpgAudit, RLSNot in SQLite
Financial ledger with strict multi-service guaranteesPostgreSQL or CockroachDBOutbox, idempotencyReplication and HA are first-class

When it is NOT the right choice: when more than one machine must write the same data; when you need a network protocol and permissions inside the database; when write transactions are long and numerous; when the file would live on NFS, SMB or a shared volume mounted by several hosts; when you need online, zero-downtime schema changes at scale. See Storage & Data Scaling for the general ladder.

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

A Laravel or Go monolith on one VPS or container with a persistent volume: database.sqlite on local SSD, WAL on, busy_timeout, one process or a few workers on the same host, Litestream sending the WAL to S3. Sessions, cache and queue can use the same file at low volume. Deploys are a file-level concern: run migrations at start, keep the volume across releases, never mount the same volume in two replicas. This is the simplest correct use and is how many small production sites run.

Modular monolith / multiple databases ​

Split by file, not by server: one SQLite file per module or per tenant, opened by the same process, with ATTACH DATABASE for the occasional cross-database report. A transaction across attached databases is atomic per file but, in WAL mode, not atomic across them as a set (the WAL page states this), so design module boundaries so no business rule needs a cross-file atomic write; use an outbox row inside each module's own file instead. Per-tenant files make export, deletion and backup per customer trivial (Multi-Tenancy).

Microservices ​

Each service owns its own SQLite file; nothing else opens it. Cross-service consistency is not SQLite's job: use sagas and the outbox pattern (write the event in the same local transaction, relay it to the broker), and idempotent consumers keyed by message id (INSERT ... ON CONFLICT DO NOTHING). Example: an orders service appends order_created to its local outbox table in the same BEGIN IMMEDIATE transaction as the order row; a relay goroutine polls rows with RETURNING, publishes to the broker, and deletes them. The broker side is covered in the messaging section. With a container orchestrator, one replica per SQLite file (a StatefulSet with one pod and a local volume, not a Deployment with replicas: 3 on a shared volume).

Distributed data (replicas, caches, multi-region) ​

Reads can be local everywhere (LiteFS, libSQL embedded replicas, Litestream-restored read-only copies); writes go to one primary. That introduces replica lag and the usual read-your-writes problem: a user writes through the primary and the next request hits a replica that has not applied the transaction yet. Cures are routing the user's next reads to the primary for a short window, passing a transaction id or position token, or writing then reading from the primary. rqlite trades latency for consensus: each write is replicated by Raft to a majority before it is acknowledged, and read consistency (none to linearizable) decides whether a read may be stale. Caches in front of SQLite are rarely needed for latency (it is already in-process) but still need invalidation if shared across processes. A cross-region write-heavy design should use a distributed SQL database (Distributed SQL & Consensus).

Scaling path ​

LoadDesign
1x: one app, hundreds of requests per secondOne SQLite file, WAL, one writer connection, reader pool, Litestream
10x: more CPUs and traffic, still one machineTune cache_size, mmap_size, indexes; batch writes; move queue/session/cache to Redis; scale vertically
100x: several app servers or regionsLiteFS or libSQL read replicas with write forwarding, or move the system of record to PostgreSQL and keep SQLite for per-device or per-tenant data
Beyond: global write throughputPostgreSQL/MySQL with replicas and sharding, or CockroachDB; SQLite stays at the edges

Lab ​

Needs the sqlite3 CLI (3.37.0 or newer for STRICT, 3.45.0 or newer for JSONB; check sqlite3 --version) and, for the Go steps, Go 1.24 or newer with the snippets above. Use two terminals for experiments 1 and 2.

sql
-- setup (terminal 1)
-- sqlite3 lab.db
PRAGMA journal_mode = WAL;            -- wal
CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT);
INSERT INTO t (v) VALUES ('seed');

Experiment 1: two writers and SQLITE_BUSY.

 1  T1: sqlite3 lab.db                              T2: sqlite3 lab.db
 2  T1: BEGIN IMMEDIATE; INSERT INTO t(v) VALUES('A');   -- T1 now holds the write lock
 3  T2: BEGIN IMMEDIATE;                                 -- error: database is locked (SQLITE_BUSY)
 4  T2: PRAGMA busy_timeout = 10000; BEGIN IMMEDIATE;    -- blocks (waiting)
 5  T1: COMMIT;                                          -- T2's BEGIN now returns
 6  T2: INSERT INTO t(v) VALUES('B'); COMMIT;            -- ok
 7  T2: SELECT count(*) FROM t;                          -- 3  (seed, A, B)
 -- reads in a third terminal never block during steps 2-5 (WAL); try it
 -- the CLI words the error "Runtime error: ..." interactively or "Error near line N: ..." from a script, by version

Experiment 2: the stale-snapshot upgrade (BUSY_SNAPSHOT).

 1  T1: BEGIN;  SELECT count(*) FROM t;                  -- deferred read, snapshot taken
 2  T2: INSERT INTO t(v) VALUES('C');                    -- autocommit write succeeds, T1 not blocked
 3  T1: INSERT INTO t(v) VALUES('D');                    -- error: database is locked, at once, no waiting (stale snapshot)
 4  T1: ROLLBACK;  BEGIN IMMEDIATE;  INSERT ...;  COMMIT;  -- works: the write lock first, then fresh data
 -- the C API reports this as SQLITE_BUSY_SNAPSHOT (517); the CLI prints only the message

Experiment 3: WAL against rollback journal timing. Run go run ./bench from docs/snippets/database/sqlite/go. On the author's laptop (macOS, local SSD) it printed:

DELETE 2000 commits in 975ms (2051 commits/s)
WAL    2000 commits in 166ms (12084 commits/s)
-- three consecutive runs on the author's laptop: DELETE 391 ms to 1.29 s, WAL 166 to 657 ms

Your numbers will differ (macOS fsync does not force a full disk flush by default, so on Linux with a real flush the gap is usually larger). Repeat with PRAGMA synchronous=NORMAL in WAL mode and with all inserts inside one BEGIN ... COMMIT to see the cost of per-commit flushes disappear.

Experiment 4: STRICT table.

sql
CREATE TABLE loose (a INTEGER);
INSERT INTO loose VALUES ('abc'), ('12');
SELECT a, typeof(a) FROM loose;          -- abc | text ; 12 | integer
CREATE TABLE strict_t (a INTEGER) STRICT;
INSERT INTO strict_t VALUES ('12');      -- ok, stored as integer
INSERT INTO strict_t VALUES ('abc');     -- error: cannot store TEXT value in INTEGER column strict_t.a

Experiment 5: an FTS5 query.

sql
CREATE VIRTUAL TABLE docs USING fts5(title, body, tokenize = 'porter unicode61');
INSERT INTO docs VALUES ('WAL mode', 'Readers do not block writers in write-ahead logging'),
                        ('Rollback', 'The rollback journal is deleted at commit');
SELECT title, bm25(docs) AS score, snippet(docs, 1, '[', ']', '...', 8)
FROM docs WHERE docs MATCH 'writer* OR journal' ORDER BY score;
-- Rollback  | -1.07e-06 | The rollback [journal] is deleted at commit
-- WAL mode  | -9.39e-07 | Readers do not block [writers] in write-ahead...

Experiment 6: checkpoint and the growing WAL. In terminal 1 run BEGIN; SELECT * FROM t; and leave it open. In terminal 2 insert 100000 rows then PRAGMA wal_checkpoint(TRUNCATE); and note the returned row 1|1|0 (busy flag 1, one frame in the log, none checkpointed) and the non-zero -wal size (ls -l lab.db-wal showed 4152 bytes in the author's run). COMMIT in terminal 1 and repeat: it returns 0|0|0 and the WAL file is 0 bytes.

Common misconceptions ​

BeliefReality
SQLite is only for prototypes and testsMost widely deployed database; many single-node production systems run on it
It is not ACIDFully ACID: atomic commit via journal or WAL, serializable isolation
WAL means multiple writersOne writer; WAL stops readers and the writer blocking each other
A bigger busy_timeout fixes every "database is locked"Not stale-snapshot upgrades; use BEGIN IMMEDIATE and retry
Column types are enforcedOnly in STRICT tables; otherwise they are affinities
PRAGMA foreign_keys persists in the fileIt is per connection and off by default
cp app.db backup.db is a backupNot for a live database; use .backup, VACUUM INTO or Litestream
Two connections to :memory: share dataEach :memory: is separate; use shared cache or one connection
Putting the file on NFS or a shared volume scales itLocks and shared memory break; it can corrupt
synchronous=OFF is safe if the app is stableAn OS crash or power cut can corrupt; use NORMAL in WAL
A deleted-row table shrinks the filePages go to the freelist; run VACUUM or use auto_vacuum
Litestream gives high availabilityIt gives continuous backup and restore, not automatic failover
Row locks exist, so lockForUpdate protects a row in LaravelSQLite has none; the whole database write lock is what protects you

Cheat sheet ​

TopicWhat to remember
ModelIn-process library, one file, no server, no network
ConcurrencyMany readers, one writer; lock granularity is the whole database
WALPRAGMA journal_mode=WAL; readers do not block the writer; same host only
Server presetWAL, synchronous=NORMAL, foreign_keys=ON, busy_timeout=5000, cache_size=-65536, temp_store=MEMORY
WritesBEGIN IMMEDIATE, short transactions, retry on SQLITE_BUSY
CheckpointAuto at 1000 pages; long readers stall it; wal_checkpoint(TRUNCATE) to reset
TypesAffinity coerces; use STRICT for enforcement
Backup.backup, VACUUM INTO, sqlite3_rsync, Litestream; never cp a live file
FTS5Virtual table, MATCH, bm25(), snippet(), external content with triggers
JSONJSON1 built in since 3.38; ->, ->>, json_each, JSONB 3.45+, index expressions
GoWriter SetMaxOpenConns(1) + _txlock=immediate; PRAGMAs in DSN; :memory: needs one connection
LaravelDB_CONNECTION=sqlite; busy_timeout, journal_mode, synchronous, transaction_mode keys; :memory: in tests
ScaleLitestream for backup, LiteFS/libSQL for read replicas, rqlite for Raft failover
Leave whenMany writers, many app servers, need roles and online DDL

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why is SQLite called serverless, and who coordinates two processes that open the same file? Must-know ​

Answer

Answer: There is no server process; each process links the library and coordinates through operating-system file locks on the database file (and, in WAL mode, a shared-memory wal-index in -shm). That is also why the files must be on one host.

2 — In rollback-journal mode, what is the commit point, and what is a hot journal? Good to know ​

Answer

Answer: The commit point is deleting (or zeroing) the journal after the changed pages are written and flushed. A hot journal is one left behind by a crash: the next connection finds it, takes the locks and copies the original pages back, so the transaction is rolled back.

3 — What does WAL change about concurrency, and what does it not change? Must-know ​

Answer

Answer: Readers and the writer no longer block each other because readers use an end mark and read the WAL up to it. There is still exactly one writer, because there is one WAL file.

4 — Why can a long-running read transaction make the -wal file grow without bound? Important ​

Answer

Answer: A checkpoint cannot copy frames past the end mark of the oldest reader, and the WAL can only be reset when no reader needs it, so with a permanent reader checkpoints stall and the WAL keeps growing.

5 — Order the lock states and say what PENDING is for. Good to know ​

Answer

Answer: UNLOCKED, SHARED, RESERVED, PENDING, EXCLUSIVE. PENDING stops new SHARED locks while existing readers finish, so a waiting writer is not starved.

6 — Why does BEGIN DEFERRED followed by a read and then a write sometimes fail with SQLITE_BUSY even with a large busy timeout? Important ​

Answer

Answer: The upgrade from a read snapshot to a write is impossible if the database changed since the snapshot (SQLITE_BUSY_SNAPSHOT), and waiting cannot make the snapshot fresh. Use BEGIN IMMEDIATE so the lock is taken before reading, and retry the whole transaction otherwise.

7 — What isolation does SQLite give, and how? Must-know ​

Answer

Answer: Serializable, by actually serializing writers (one at a time); readers see one snapshot (WAL end mark or held SHARED lock). Only shared-cache connections with read_uncommitted can see uncommitted data.

8 — What do type affinity and STRICT do differently when you insert 'abc' into an INTEGER column? Important ​

Answer

Answer: With affinity the text is stored as TEXT because it cannot be converted losslessly; with STRICT the insert fails with SQLITE_CONSTRAINT_DATATYPE.

9 — Name three PRAGMAs that are per connection and must be set for every pooled connection. Important ​

Answer

Answer: foreign_keys, busy_timeout, synchronous (also cache_size, temp_store, mmap_size). journal_mode=WAL is the notable one that persists in the file.

10 — Why does a Go test using :memory: fail with "no such table" intermittently? Must-know ​

Answer

Answer: The database/sql pool opens several connections and each :memory: connection is a separate database. Limit the pool to one connection, use a shared-cache in-memory URI, or use a temporary file.

11 — Give three safe ways to back up a live database and one unsafe way. Important ​

Answer

Answer: .backup / backup API, VACUUM INTO, Litestream (also sqlite3_rsync). Unsafe: copying the files with cp while writers are active.

12 — What does Litestream replicate and what does it not give you? Good to know ​

Answer

Answer: It streams the WAL as LTX files to object storage after taking over checkpointing, enabling point-in-time restore. It is asynchronous, has one writer, and provides no automatic failover or read scaling.

Glossary ​

TermOne line
Embedded databaseA database engine linked into the application as a library
Serverless (SQLite sense)No separate database server process
PageFixed-size block (512 to 65536 bytes) that the file is made of
B-treeTree of pages used for every table and index
rowid64-bit integer key of an ordinary SQLite table row
INTEGER PRIMARY KEYColumn that aliases the rowid
WITHOUT ROWIDTable whose B-tree is keyed by its primary key
sqlite_schemaTable (page 1 root) listing all schema objects, also sqlite_master
Overflow pagePage holding the tail of a row too large for its leaf
FreelistPages freed by deletes, reused before the file grows
VarintVariable-length integer encoding (1 to 9 bytes)
Rollback journalSide file with original pages used to undo an unfinished transaction
Hot journalJournal left after a crash that must be replayed on next open
WALWrite-ahead log: appended frames instead of in-place page writes
FrameOne page image plus header in the WAL
wal-indexShared-memory map from page to newest WAL frame (-shm file)
End markLast commit frame a reader may see; fixes its snapshot
CheckpointCopying committed WAL frames back into the main file
PASSIVE, FULL, RESTART, TRUNCATECheckpoint modes, increasing in how much they wait and reset
SHARED, RESERVED, PENDING, EXCLUSIVEThe lock states of a connection
SQLITE_BUSYResult code 5: a needed lock is held elsewhere
SQLITE_BUSY_SNAPSHOTRead-to-write upgrade on a stale snapshot
SQLITE_LOCKEDConflict inside a connection or shared cache
Busy handler / busy_timeoutCallback or milliseconds to wait for a lock
BEGIN DEFERRED / IMMEDIATE / EXCLUSIVEWhen a transaction takes its locks
Type affinityColumn preference that coerces stored values
Storage classNULL, INTEGER, REAL, TEXT or BLOB
STRICT tableTable with enforced column types (3.37.0+)
synchronousHow aggressively commits are fsynced (OFF, NORMAL, FULL, EXTRA)
foreign_keysPRAGMA enabling FK enforcement, per connection
mmap_sizeBytes of the file read through memory mapping
temp_storeWhere temp tables and sort spill live
FTS5Full-text search virtual table module
bm25Relevance ranking function used by FTS5
JSON1The JSON extension (3.9.0), built into SQLite since 3.38.0
JSONBBinary JSON encoding stored in a BLOB (3.45.0+)
UpsertINSERT ... ON CONFLICT DO UPDATE
RETURNINGClause returning rows changed by DML
Shared cacheObsolete mode where connections in a process share a page cache
VACUUM INTOWrites a compacted consistent copy of the database to a new file
Online backup APIsqlite3_backup_* incremental live copy
LitestreamStreams SQLite WAL to object storage for backup and restore
LiteFSFUSE-based replication of SQLite across nodes (Fly.io)
rqliteRaft-replicated distributed database built on SQLite
libSQLOpen-contribution fork of SQLite by Turso
MC/DCModified condition/decision coverage, achieved by SQLite's tests

References ​

All pages below were fetched and read; the texts are saved under the session's sources/sqlite/ folder.

Related pages: ACID & Transactions, Isolation Levels, Locks & Concurrency, Durability, WAL & Crash Recovery, Storage Engines, Indexing, Connection Pooling, PostgreSQL & Database Fundamentals, MySQL Storage Engines.

Built by Morteza Negahi