Skip to content
Derar Sattouf

SQLite in Production: WAL Mode, Litestream, and When It Beats Postgres

Updated Backend & databases

SQLite in Production: WAL Mode, Litestream, and When It Beats Postgres

SQLite is the most deployed database in the world, living in every phone and browser. For years, the received wisdom was "great for prototypes, never for production web apps." That advice has aged badly. Modern hardware has fast NVMe disks and many cores, a single-node server can handle a surprising amount of traffic, and a database that is a file removes entire categories of operational complexity: no network hop, no connection pool tuning, no separate server to patch.

But SQLite in production is not free of rules. Its defaults are conservative, its concurrency model is unusual, and its durability story depends on how you back it up.

SQLite supports many concurrent readers and one writer. With WAL mode, readers don't block the writer and vice versa. Set sensible pragmas (journal_mode=WAL, synchronous=NORMAL, busy_timeout, foreign_keys=ON), keep write transactions short, and use BEGIN IMMEDIATE for transactions that will write, to avoid lock-upgrade deadlocks.

For backups, use Litestream (continuous streaming replication to object storage) or an equivalent, and test your restores. Choose SQLite when you have a single-server deployment, a read-heavy workload, and modest write concurrency. Choose Postgres when you need multiple writers, horizontal app servers sharing one database, or heavy concurrent writes.

Why SQLite works for servers now

PropertyEffect
In-processQueries are function calls: microseconds, no network round trip
Single fileSimple deploys, trivial dev/prod parity, easy per-tenant databases
Fast local SSDsFsync and random reads are cheap compared to a decade ago
Zero opsNo server process, users, or connection limits
Rock-solidExtensively tested, ACID transactions, backward compatible file format

The N+1 query problem, a performance killer with networked databases, is far less painful when each query costs a few microseconds. The tradeoff is that your database lives on one machine's disk.

Configure it for production

SQLite's defaults favor compatibility. Apply these on every new connection:

PRAGMA journal_mode = WAL;        -- readers and writer don't block each other
PRAGMA synchronous = NORMAL;      -- safe with WAL; fsync on checkpoint, not every commit
PRAGMA busy_timeout = 5000;       -- wait up to 5s for a lock instead of failing instantly
PRAGMA foreign_keys = ON;         -- OFF by default for legacy reasons!
PRAGMA cache_size = -64000;       -- ~64 MB page cache (negative = KiB)
PRAGMA temp_store = MEMORY;
PRAGMA mmap_size = 268435456;     -- 256 MB memory-mapped I/O (tune to your data)
PRAGMA wal_autocheckpoint = 1000; -- pages; default is fine for most workloads

Key points:

  • journal_mode=WAL persists in the database file, but setting it on each connection is harmless.
  • synchronous=NORMAL in WAL mode can lose the last few transactions on an OS crash or power loss, but cannot corrupt the database. If you need every committed transaction to survive power loss, use FULL at some throughput cost.
  • busy_timeout is critical. Without it, a second writer immediately gets SQLITE_BUSY.
  • foreign_keys must be enabled per connection; forgetting it silently disables constraints.

Example setup in Node.js (better-sqlite3)

import Database from "better-sqlite3";

export const db = new Database("/data/app.db");
db.pragma("journal_mode = WAL");
db.pragma("synchronous = NORMAL");
db.pragma("busy_timeout = 5000");
db.pragma("foreign_keys = ON");

// Prepared statements are cached and fast
const getUser = db.prepare("SELECT id, email FROM users WHERE id = ?");
const insertPost = db.prepare("INSERT INTO posts (user_id, title) VALUES (?, ?)");

const createPost = db.transaction((userId: number, title: string) => {
  return insertPost.run(userId, title).lastInsertRowid;
});

Example in Go (using modernc.org/sqlite or mattn/go-sqlite3)

db, err := sql.Open("sqlite", "file:/data/app.db?_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=foreign_keys(1)&_pragma=synchronous(NORMAL)")
if err != nil { log.Fatal(err) }

// Pattern: one writer pool, many readers
writer, _ := sql.Open("sqlite", dsn)
writer.SetMaxOpenConns(1)

reader, _ := sql.Open("sqlite", dsn+"&mode=ro")
reader.SetMaxOpenConns(runtime.NumCPU())

(DSN parameter names differ between drivers; consult your driver's documentation.)

Understand the concurrency model

SQLite allows one write transaction at a time across the entire database. In WAL mode, readers continue to see a consistent snapshot while a write is in progress.

Rules that prevent production pain:

  1. Keep write transactions short. Do not make network calls or wait for user input inside a transaction.
  2. Use BEGIN IMMEDIATE for write transactions. A default (deferred) transaction starts as a reader and upgrades to a writer later; if another writer got in first, the upgrade fails with SQLITE_BUSY immediately, ignoring busy_timeout.
BEGIN IMMEDIATE;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
  1. Serialize writes in the application with a single writer connection or queue. This is often faster than letting many connections fight over the lock.
  2. Avoid long-running read transactions that hold old snapshots; they prevent WAL checkpointing and the WAL file can grow without bound.
  3. Do not put the database on a network filesystem (NFS, SMB, many container volume drivers). File locking is unreliable and corruption can result. Use a local disk or a block volume attached to one machine.

Throughput expectations

A well-tuned SQLite on a modern SSD can commonly do tens of thousands of small write transactions per second when batched sensibly, and far more reads. Batch writes inside one transaction when you can; the commit (fsync) is the expensive part, not each statement.

Backups: Litestream and friends

A single file on a single disk is a single point of failure. Never rely on the disk alone.

Why not just cp?

Copying a live database file while it is being written can produce a corrupt copy. Use one of:

# Online backup API via the CLI (consistent snapshot)
sqlite3 /data/app.db ".backup '/backups/app-$(date +%F).db'"

# Or VACUUM INTO, which also compacts
sqlite3 /data/app.db "VACUUM INTO '/backups/app-compact.db'"

Periodic snapshots mean you can lose everything since the last one. For near-zero data loss, stream changes continuously.

Litestream

Litestream runs as a sidecar process, tails the WAL, and continuously replicates to S3-compatible object storage (S3, R2, GCS, Backblaze B2, Azure Blob), with typical lag of about a second.

# /etc/litestream.yml (Litestream 0.5.x style; verify against the config reference for your version)
dbs:
  - path: /data/app.db
    replica:
      url: s3://my-app-backups/prod/app.db
      # or the explicit form: type: s3, bucket: my-app-backups, path: prod/app.db, region: eu-west-1

snapshot:
  interval: 24h     # how often a full snapshot is taken
  retention: 168h   # how long snapshots and the LTX files they cover are kept (7 days)

Litestream 0.5 changed the config and storage format compared with 0.3: each database now has a single replica block (the old replicas list is deprecated), per-replica retention and snapshot-interval keys moved to a global snapshot block, and replication data is stored in the LTX format. If you copy a configuration from an older tutorial, it may fail or behave differently, so read the configuration reference and the upgrade notes first. Credentials come from the usual environment variables or instance roles (for example AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY for S3-compatible stores).

Run your app under Litestream so it restores on startup if the disk is empty:

# Restore if the DB doesn't exist, then run the app with replication
litestream restore -if-db-not-exists -if-replica-exists /data/app.db
exec litestream replicate -exec "node server.js"

Docker sketch:

FROM litestream/litestream:latest AS litestream
FROM node:24-slim
COPY --from=litestream /usr/local/bin/litestream /usr/local/bin/litestream
COPY litestream.yml /etc/litestream.yml
COPY . /app
WORKDIR /app
CMD ["sh", "-c", "litestream restore -if-db-not-exists -if-replica-exists /data/app.db && exec litestream replicate -exec 'node server.js'"]

Check the Litestream documentation for the current configuration schema and any project changes; the ecosystem (including LiteFS and managed options) evolves.

The rule everyone learns the hard way

An untested backup is not a backup. Schedule a job that restores the latest replica into a scratch location, runs PRAGMA integrity_check, and compares row counts or a checksum on key tables. Alert if it fails.

litestream restore -o /tmp/verify.db s3://my-app-backups/prod/app.db
sqlite3 /tmp/verify.db "PRAGMA integrity_check; SELECT count(*) FROM users;"

What Litestream does not do

  • It replicates one writer. Running two app instances against copies of the same database is not supported; it is a backup and restore tool, not multi-primary replication.
  • Replication is asynchronous, so a sudden machine loss can lose the last second or so of writes. That is the recovery point objective you accept.
  • It is a disaster recovery tool, not a read replica; use LiteFS or another approach if you need replicas serving reads.
  • Do not run VACUUM, change journal_mode, or checkpoint manually in ways that fight the replicator; let Litestream manage checkpointing. Check the "tips and caveats" section of its docs for the current list.

Restore drill: a 5-step exercise

# 1. Simulate disaster on a scratch machine or container
rm -f /data/app.db /data/app.db-wal /data/app.db-shm

# 2. Restore the latest state
litestream restore -if-replica-exists -o /data/app.db s3://my-app-backups/prod/app.db

# 3. Verify structural integrity
sqlite3 /data/app.db "PRAGMA integrity_check;"

# 4. Verify business data
sqlite3 /data/app.db "SELECT count(*), max(created_at) FROM orders;"

# 5. Record how long it took: that is your real recovery time objective

Restore to a point in time is also supported (check litestream restore options in the docs), which helps recover from an accidental DELETE: restore to just before the mistake into a new file and copy the rows back.

Schema migrations

SQLite supports ALTER TABLE ADD COLUMN, RENAME COLUMN, and DROP COLUMN (since 3.35) but not arbitrary alterations. For bigger changes use the 12-step table rebuild: create a new table, copy data, drop the old one, rename, recreate indexes, all inside a transaction.

PRAGMA foreign_keys = OFF;
BEGIN IMMEDIATE;
CREATE TABLE users_new (
  id INTEGER PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  plan TEXT NOT NULL DEFAULT 'free'
) STRICT;
INSERT INTO users_new (id, email, created_at) SELECT id, email, created_at FROM users;
DROP TABLE users;
ALTER TABLE users_new RENAME TO users;
PRAGMA foreign_key_check;
COMMIT;
PRAGMA foreign_keys = ON;

Tips:

  • Use STRICT tables (3.37+) so column types are enforced; SQLite's default flexible typing allows storing text in an integer column.
  • Track versions with PRAGMA user_version or a migrations table; use a migration tool (Atlas, goose, dbmate, Drizzle Kit, Prisma Migrate).
  • Run migrations at deploy start, before serving traffic, in a single process.

Features worth using

  • JSON functions: json_extract, ->, ->>, and indexes on expressions.
  • FTS5: built-in full-text search with ranking (bm25).
  • Generated columns for indexed derived values.
  • Window functions, CTEs, UPSERT (ON CONFLICT), and RETURNING.
  • Extensions such as sqlite-vec for vector search in small to mid-size AI features.
CREATE VIRTUAL TABLE docs USING fts5(title, body, tokenize = 'porter unicode61');
INSERT INTO docs (title, body) VALUES ('WAL mode', 'Write-ahead logging allows concurrent readers');
SELECT title, bm25(docs) AS score FROM docs WHERE docs MATCH 'concurrent readers' ORDER BY score LIMIT 10;

Reading and writing from different runtimes

  • Node.js: better-sqlite3 is the long-standing synchronous driver; recent Node versions also ship a built-in node:sqlite module (check its stability status for your Node version). Because the driver is synchronous, a slow query blocks the event loop, so keep queries fast, index well, and consider worker threads for heavy reads.
  • Bun and Deno: both have built-in SQLite APIs.
  • Python: the standard sqlite3 module; set isolation_level=None and issue BEGIN IMMEDIATE yourself for predictable write transactions.
  • Rails: Rails 8 made SQLite a first-class production option and uses it for Solid Cache, Solid Queue and Solid Cable defaults; see the Rails guides for the recommended pragmas it sets for you.
  • Go and Rust: modernc.org/sqlite (pure Go), mattn/go-sqlite3 (cgo), rusqlite, sqlx, and libsql clients.

Maintenance pragmas and housekeeping

PRAGMA optimize;                    -- run on connection close, or periodically on long-lived connections
PRAGMA journal_size_limit = 67108864; -- trim the WAL file back to ~64 MB after checkpoints
PRAGMA wal_checkpoint(TRUNCATE);    -- manual: checkpoint and reset the WAL (only if you manage checkpoints yourself)
PRAGMA integrity_check;             -- slow on large databases; run on restored copies, not hot paths

Run ANALYZE (or rely on PRAGMA optimize) after bulk loads so the query planner has statistics. For plan analysis use EXPLAIN QUERY PLAN, which is the SQLite counterpart to the techniques in Postgres query performance with EXPLAIN ANALYZE.

EXPLAIN QUERY PLAN
SELECT id, title FROM posts WHERE user_id = ? ORDER BY created_at DESC LIMIT 20;
-- Want: SEARCH posts USING INDEX idx_posts_user_created (user_id=?)
-- Avoid: SCAN posts (full table scan) or USE TEMP B-TREE FOR ORDER BY on big sets

Monitoring what matters

SignalHow to checkWhy
WAL file sizeFile size of app.db-walGrowing WAL means a long reader is blocking checkpoints
SQLITE_BUSY rateApplication error countersWriters are queueing; shorten transactions or serialize writes
Write transaction durationApplication timingThe single-writer throughput budget
Database size and free pagesPRAGMA page_count, PRAGMA freelist_countCapacity and fragmentation
Replication lagLitestream logs and metricsYour actual data-loss window
Last successful restore testCI job resultWhether backups work at all

Scaling patterns

Vertical first. A bigger machine with faster NVMe takes SQLite a long way.

Read replicas. LiteFS or similar tools replicate to read-only copies on other nodes, with writes routed to a primary. This adds complexity; weigh it against simply moving to Postgres.

Database per tenant. Because databases are cheap files, giving each customer their own SQLite file gives strong isolation, per-tenant backup/restore, and easy data deletion. It works well for B2B SaaS with many small tenants, but needs tooling for migrations across thousands of files.

Managed distributed SQLite (Turso/libSQL, Cloudflare D1) offers edge-friendly replication with a hosted control plane; semantics and limits differ from local SQLite, so read their docs carefully.

SQLite or Postgres? A decision guide

Choose SQLite when:

  • One application server (or one primary) owns the database.
  • Reads dominate, and write rates are moderate (hundreds to low thousands per second).
  • You value simple operations, fast local queries, and low cost.
  • Data size fits comfortably on one disk (hundreds of GB is fine; many terabytes becomes awkward).
  • You can accept a brief outage during failover or restore.

Choose Postgres when:

  • Multiple app servers must write concurrently to the same database.
  • You need rich features: advanced indexing (GIN/GiST), row-level security, logical replication, extensions like PostGIS, mature role management.
  • You need high availability with automatic failover and point-in-time recovery managed for you.
  • Write concurrency is high or long-running writes are unavoidable.
  • Compliance or organizational standards require a managed networked database.

Both are valid; the mistake is choosing by fashion rather than by workload.

Production checklist

  1. WAL mode, synchronous=NORMAL (or FULL), busy_timeout, foreign_keys=ON on every connection.
  2. Writes go through short BEGIN IMMEDIATE transactions, ideally via a single writer.
  3. Database file on a local or block volume, never NFS.
  4. Continuous replication (Litestream) plus periodic verified restores.
  5. STRICT tables and a migration tool.
  6. Monitor: WAL size, checkpoint lag, SQLITE_BUSY errors, database size, replication lag.
  7. Plan for growth: know the trigger (write contention, size, multi-node) that would make you migrate.

Where this usually goes wrong

  • Forgetting to apply pragmas on every new connection (especially foreign_keys and busy_timeout).
  • Using deferred transactions for writes and getting immediate SQLITE_BUSY errors.
  • Putting the database on NFS, a network share or an unsuitable container volume.
  • Copying the .db file with cp while the app is running, and forgetting the -wal and -shm companions.
  • Holding a read transaction open (for example while streaming a huge response), which stops WAL checkpointing.
  • Running multiple app replicas against one file on different machines.
  • Skipping restore tests.
  • Storing large blobs in hot tables; keep big files in object storage and store references.
  • Assuming type safety without STRICT tables.
  • Running a heavy analytics query on the same database connection that serves user writes; use a separate read connection or a replica copy.

Troubleshooting

SymptomLikely cause and fix
database is locked / SQLITE_BUSYMissing busy_timeout, long write transactions, or deferred-to-write upgrade. Use BEGIN IMMEDIATE, shorten writes, serialize them.
WAL file keeps growingLong-running reader or no checkpoint progress. Find and shorten the reader; check wal_autocheckpoint.
Slow queries after a data loadMissing statistics or index. Run ANALYZE, check EXPLAIN QUERY PLAN.
Corruption after a crashUsually the database was on a network filesystem or copied unsafely, or fsync was disabled. Restore from replica and fix the cause.
Litestream cannot restoreWrong replica path or credentials, or an old config format after an upgrade; check logs and run litestream restore manually with the same URL.
Disk fullWAL, snapshots and temp files; set journal_size_limit, monitor free space, and verify retention cleanup.
App slows during backupsVACUUM INTO or .backup on a huge database; schedule off-peak or rely on Litestream's incremental replication.

Questions that come up

Can SQLite handle my traffic? For many apps, yes. A single node serving thousands of requests per second is realistic when reads dominate and writes are batched. Measure with your own workload and load test before deciding. SQLite's page cache plus OS cache often removes the need for an external cache; if you still need one, see Redis and Valkey caching strategies.

What about high availability? A single-node SQLite has downtime during failure and restore. If you need automatic failover, use Postgres or a distributed SQLite service, or accept a short recovery window and automate it with infrastructure as code.

Can I run SQLite on serverless platforms? Usually not with local files, since instances have ephemeral or shared disks. Use hosted options (Turso, D1) or a persistent-volume service.

Does it work with Docker and Kubernetes? Yes with a persistent volume attached to exactly one pod (a StatefulSet with one replica), plus Litestream as a sidecar or wrapper. Avoid rolling updates that briefly run two writers.

How do I do zero-downtime deploys? A short stop and start is the simple answer; for zero downtime you need a proxy that holds requests during restart, or a design where a single process is upgraded in place by handing over the listening socket. Many teams accept a few seconds of downtime. For Postgres-style techniques see zero-downtime Postgres migrations.

Is it OK for local-first apps? Yes: SQLite compiled to WebAssembly in browsers, plus a sync layer, is a common local-first design; see local-first architecture.

Sources and docs