A small site gets shared in a big chat group on a Tuesday evening. The pages
stay fast. Then the error log fills up with database is locked, and a couple
of form submissions vanish.
The database is SQLite, running on its default settings. The fix is about five lines of setup and one habit. SQLite does not need replacing. It needs to be used the way it expects. For anything that moves money I would pick Postgres, but for a read-heavy site on one server, SQLite is a strong first choice.
Short version:
- SQLite is fast on a busy site because there is no network hop. A page that runs 200 queries makes 200 function calls, not 200 round trips.
- Turn on WAL mode, set a busy timeout, use one write connection and a pool of read connections, and keep write transactions short.
- Never copy a live database file with
cp. Use the backup API,VACUUM INTO, or Litestream, and test a restore. - It stops being the right choice when you need more than one app server, a network drive, or many writers at once.
Why SQLite can serve a busy site
A client/server database sits across a network. Every SQL statement is a message there and back. SQLite is a library inside your app process. A query is a function call that reads a local file.
The SQLite team makes the same point on their page about many small queries. Doing over 200 round trips in a row “can be a serious performance drag” with a database server, while in SQLite a query is only a function call. That is why code that runs a query per row on a page is fine here.
How much traffic is that? The SQLite docs say a site with fewer than 100K hits a day “should work fine”, and call that figure a conservative estimate. They say SQLite has been shown to work with 10 times that. Their own site, as of 2015, handled about 400K to 500K requests a day on one small VM. About 15% to 20% of those were dynamic pages that touched the database.
Treat all of that as a rule of thumb, not a benchmark for your app. It depends on how much of your traffic writes. Reads scale well. Writes are the thing to watch.
The settings I start with
Run these when you open a database. The first one is stored in the file. The rest belong to the connection, so a new connection starts with the defaults again.
PRAGMA journal_mode = WAL; -- stored in the file, set once
PRAGMA synchronous = NORMAL; -- from here down: every new connection
PRAGMA busy_timeout = 5000;
PRAGMA foreign_keys = ON;
PRAGMA cache_size = -64000;
PRAGMA temp_store = MEMORY;
-- optional, measure first:
PRAGMA mmap_size = 268435456;
What each one does:
journal_mode = WAL. The default journal is a rollback journal, where
readers and the writer get in each other’s way. In
WAL mode the writer appends changes to a
separate -wal file, and readers keep reading the main file plus the WAL.
Readers do not block the writer and the writer does not block readers. This is
the one setting I would not skip. It is persistent: once set, the database
comes back in WAL mode every time it is opened. The catch is that every process
using the database must be on the same machine. WAL does not work over a
network filesystem.
synchronous = NORMAL. This is a durability trade, so read it twice. With
FULL, SQLite syncs the WAL to disk on every commit. With NORMAL it skips
that and syncs only at checkpoints. The SQLite docs say that in WAL mode the
database is always consistent, but a transaction committed with NORMAL “might
roll back following a power loss or system crash”. Commits are still safe if
only your app crashes. My rule: if losing the last few commits after a power
cut would cost money or trust, use FULL and accept slower writes. For a blog,
a catalog or a dashboard, NORMAL is the usual choice.
busy_timeout = 5000. Without it, a connection that finds the database
locked fails at once with SQLITE_BUSY. With it, SQLite retries for up to 5000
ms first. Five seconds is also what the Litestream docs recommend. A
connection has only one busy handler, so if your driver sets its own, check
which one wins.
foreign_keys = ON. Foreign keys are off by default, for old-code
compatibility, and must be turned on for each connection. The pragma does
nothing inside a transaction, so run it right after you connect.
cache_size = -64000. A positive number means pages. A negative number
means KiB, so -64000 is about 64 MB. The default is -2000, about 2 MB. The
cache is per connection, so 5 connections at 64 MB can use 320 MB. Size it for
your pool, not for one connection.
temp_store = MEMORY. Temporary tables and indexes stay in RAM instead of
temp files. Fine for most sites. Watch memory if you run large sorts.
mmap_size. Optional. It lets SQLite read the database through memory
mapping instead of read() calls. The limit is in bytes, and 0 turns it off.
I only enable it after measuring on real data, because the gain depends on
your disk and OS.
One more: page_size cannot change after the database enters WAL mode. The
default (4096 bytes since SQLite 3.12) is fine for most sites, so I leave it.
One writer, many readers
WAL allows many readers and one writer at a time. A second writer has to wait. So do not fight that. Build the app around it: one write connection, and a pool of read connections.
Here is the whole idea in Python. It uses only the standard library, and the same shape works in any language.
import sqlite3
import threading
from contextlib import contextmanager
from queue import Queue
DB_PATH = "app.db"
# Per connection. Run these on every new connection.
CONNECTION_PRAGMAS = """
PRAGMA synchronous = NORMAL;
PRAGMA busy_timeout = 5000;
PRAGMA foreign_keys = ON;
PRAGMA cache_size = -64000;
PRAGMA temp_store = MEMORY;
"""
def connect(mode):
# isolation_level=None: we send BEGIN and COMMIT ourselves.
conn = sqlite3.connect(f"file:{DB_PATH}?mode={mode}", uri=True,
isolation_level=None, check_same_thread=False)
conn.executescript(CONNECTION_PRAGMAS)
return conn
# One connection does all the writing, behind a lock.
writer = connect("rwc")
writer.execute("PRAGMA journal_mode = WAL") # stored in the file
write_lock = threading.Lock()
# Create tables here, before the readers open a read-only connection.
writer.execute("CREATE TABLE IF NOT EXISTS hits (id INTEGER PRIMARY KEY, path TEXT NOT NULL)")
# A small pool of read-only connections.
readers = Queue()
for _ in range(4):
readers.put(connect("ro"))
@contextmanager
def write_tx():
with write_lock:
writer.execute("BEGIN IMMEDIATE")
try:
yield writer
writer.execute("COMMIT")
except BaseException:
writer.execute("ROLLBACK")
raise
@contextmanager
def read_conn():
conn = readers.get()
try:
yield conn
finally:
readers.put(conn)
Use it like this:
with write_tx() as db:
db.execute("INSERT INTO hits (path) VALUES (?)", ("/pricing",))
with read_conn() as db:
total = db.execute("SELECT count(*) FROM hits").fetchone()[0]
A few details matter here:
- The lock is the write queue. Threads wait on
write_lockin line, so SQLite never has to decide who goes next. In Go, open a secondsql.DBfor writes and callSetMaxOpenConns(1)on it. - Readers open with
mode=ro. A read-only connection cannot write by mistake. It needs the database file to exist, so create tables with the writer first. BEGIN IMMEDIATEtakes the write lock at the start. The defaultBEGINis deferred. If it starts with aSELECTand writes later, SQLite tries to upgrade it. If another connection changed the database in the meantime, the upgrade fails withSQLITE_BUSY. SQLite may also skip the busy handler there, to avoid a deadlock. Starting withBEGIN IMMEDIATEmeans you wait for the lock once, up front, and never fail halfway through. In WAL modeBEGIN EXCLUSIVEbehaves the same, so useIMMEDIATE. How to turn it on in each driver.
The lock states are in how SQLite locks work.
Keep write transactions short
Writers take turns, so the time each one holds the lock is your write capacity. The SQLite docs describe the healthy picture: writers queue up, each does its work quickly and moves on, and no lock lasts more than a few dozen milliseconds.
The most common mistake is doing slow work inside the transaction:
# Wrong: every other write waits while we call a partner API
with write_tx() as db:
rate = fetch_exchange_rate() # network call, maybe seconds
db.execute("INSERT INTO quotes (rate) VALUES (?)", (rate,))
# Better: slow work first, then a short transaction
rate = fetch_exchange_rate()
with write_tx() as db:
db.execute("INSERT INTO quotes (rate) VALUES (?)", (rate,))
Some other habits:
- Put many small inserts in one transaction instead of committing each one.
- Do not wait on a user, a network call or a sleep while a transaction is open.
- A slow
UPDATEholds the lock for as long as it runs. Fix it with an index first, see SQLite index optimisation. - Long read transactions have a cost too. They keep an old snapshot alive, and that is how checkpoints get stuck, as the next section shows.
WAL checkpoints: the part people forget
In WAL mode, a commit does not touch the main file. It appends pages to the
app.db-wal file. A checkpoint copies those pages back into app.db.
By default SQLite runs a checkpoint on its own when a commit pushes the WAL to
1000 pages or more. With the default 4096 byte page, that is about 4 MB. You
can change the threshold with PRAGMA wal_autocheckpoint. Automatic
checkpoints are always the gentle kind, called PASSIVE: they do as much as
they can without waiting for anyone, and may stop early if readers or writers
are busy.
Checkpoint starvation
The WAL file can only be reset when no connection is still using it. The SQLite docs spell out the bad case. If there are many overlapping readers and “there is always at least one active reader”, no checkpoint can finish and the WAL file “will grow without bound”.
reader A |------------------------|
reader B |------------------------|
reader C |------------------------|
^
there is never a gap with zero readers,
so the WAL cannot be reset and keeps growing
A bigger WAL also makes reads slower. Every reader has to check the WAL, and the time that takes grows with its size. So a runaway WAL hurts twice: disk space and read speed.
What helps:
- Keep reads short. Finish and close cursors. An unfinished statement keeps a read transaction open.
- Leave
wal_autocheckpointon unless you run checkpoints yourself. - Cap the file size with
PRAGMA journal_size_limit = 67108864;(64 MiB). A checkpoint does not normally shrink the WAL file unless this limit is set. - Run a stronger checkpoint at a quiet moment from the write connection:
PRAGMA wal_checkpoint(TRUNCATE);. It waits for readers to finish, then truncates the WAL to zero bytes. The waiting is bounded by your busy timeout. If it was blocked, the first number it returns is1.
To see how the WAL is doing, run a passive checkpoint and read the result:
PRAGMA wal_checkpoint(PASSIVE);
-- returns three numbers, for example: 0 | 807 | 807
-- busy | frames in the WAL | frames already checkpointed
If the second number keeps growing while the third falls behind, something is holding a reader open.
Backups: never cp a live database
This is where people lose data. It feels harmless to run cp app.db backup.db
from a cron job. With WAL it is wrong in two ways. Recent commits may still be
in app.db-wal, so the copy of app.db alone can miss them. And the copy may
land in the middle of a checkpoint. The SQLite docs also note that the -wal
file is part of the database state and should be kept with it when you copy or
move it. The only safe way to remove one is to open the database and close it
again.
You have three safe options.
1. The online backup API
It makes a copy that is a snapshot of the database as it was when the copy started. Most languages wrap it. In Python:
import sqlite3
src = sqlite3.connect("app.db")
dst = sqlite3.connect("backup.db")
src.backup(dst)
dst.close()
src.close()
The sqlite3 command line has .backup backup.db for the same job. One
warning from the docs: if the copy is done in many small steps and another
connection writes between steps, the backup restarts, and on a very busy
database it may never finish. Copying in one step, which is the Python
default, leaves no gap between steps for a write to land in.
2. VACUUM INTO
VACUUM INTO '/backups/app-2026-11-26.db';
One SQL statement. It writes a transactionally consistent, compact copy, with free pages removed. It exists since SQLite 3.27.0 (2019). The target file must not exist, or must be empty. And if the statement is cut short by a power loss, the output may be corrupt. So write to a temporary name and rename the file after it finishes.
3. Litestream: continuous copies
Litestream runs as a separate process next to your app. It watches the WAL and copies changes to object storage, such as S3. It does this by taking over checkpointing, and it holds a long read transaction to keep other processes from checkpointing. To restore, it fetches the latest snapshot and replays the changes after it.
# keep this running next to your app
litestream replicate /var/lib/app/app.db s3://my-bucket/app.db
# restore on a new machine
litestream restore -o /var/lib/app/app.db s3://my-bucket/app.db
Things to know before you rely on it:
- The copy is asynchronous. By default it ships to S3 every second. If the server dies, you lose what was not shipped yet, as with async replication in Postgres or MySQL. It is disaster recovery, not instant failover.
- It needs WAL mode.
- It needs short write locks when it checkpoints, so set
busy_timeout. - Only one app should replicate into one bucket path. Two writers into the same place can make a restore impossible.
- Defaults can change between versions. The Litestream docs for 0.5 describe compaction levels, a daily snapshot and 24 hours of retention by default. Check the docs for the version you run.
My default is Litestream for a continuous copy, plus a nightly VACUUM INTO
file stored somewhere else. The nightly file is a plain database that any
SQLite can open, even if the Litestream setup breaks.
Test the restore
A backup you have never restored is a hope. Once a month, and after every change to the backup setup, do this on another machine:
litestream restore -o /tmp/restored.db s3://my-bucket/app.db
sqlite3 /tmp/restored.db "PRAGMA integrity_check;" # should print: ok
sqlite3 /tmp/restored.db "SELECT count(*) FROM hits;" # does the count look right?
Write down how long the restore took. That number is your real downtime after a disk failure.
Upkeep: PRAGMA optimize
SQLite’s query planner uses statistics about your tables. PRAGMA optimize
refreshes them, but only where it is likely to help. The docs give three
rules:
- With short-lived connections, run
PRAGMA optimize;just before closing. - With long-lived connections, run
PRAGMA optimize=0x10002;when the connection opens, thenPRAGMA optimize;now and then, say every few hours. - Run it after a schema change, especially after
CREATE INDEX.
Advice to run REINDEX and VACUUM on a schedule is not needed for most
sites. A full VACUUM rewrites the whole file and can need up to twice
the database size in free disk space. I only run it after deleting a large
amount of data.
What to monitor
Most of these cost nothing to track.
| Signal | How to check | What it tells you |
|---|---|---|
| WAL file size | ls -l app.db-wal | Growing means a checkpoint is stuck behind a reader |
| Checkpoint result | PRAGMA wal_checkpoint(PASSIVE) | Frames in the WAL vs frames checkpointed |
SQLITE_BUSY errors | Count “database is locked” in the app log | Should be zero. Each one is a bug to fix |
| Write transaction time | Time write_tx in the app | The longest one is your write ceiling |
| Wait for the write lock | Time spent waiting in write_lock | Rising means you are nearing the one-writer limit |
| Free disk space | Disk usage on the data volume | Backups, VACUUM and a big WAL all need room |
| Last good backup, last restore test | Timestamp of each | Backups fail quietly |
Where SQLite stops
SQLite is a good fit until one of these is true. They come from the SQLite team’s own pages on when to use it and on using it over a network.
- One machine. All processes must be on the same host to use WAL. If you need two or more app servers on the same data, SQLite is the wrong tool.
- No network filesystems. NFS and similar drives have buggy file locking in many implementations. The SQLite docs say that has led to database corruption, and that WAL does not work over a network filesystem at all. Check what a “shared volume” in your cloud really is.
- One writer at a time. Writers queue. That is fine while each write takes milliseconds. If writes pile up and users wait, or you need many writers at once, move on. The docs say that if a site is write-intensive or needs multiple servers, use a client/server database.
- Very large data. The limit is 281 terabytes, but long before that the docs suggest looking at a client/server database. Backups and restores also get slower as the file grows.
- No instant failover. Litestream restores a file onto a new machine. You wait as long as the restore takes, and you lose the unshipped tail.
- A disk that disappears. If your containers restart with a fresh disk, you need a persistent volume attached to exactly one instance.
If you do outgrow it, the move is easier than it sounds when you kept to plain SQL. Postgres swaps the one big write lock for locks on single rows. The post on understanding PostgreSQL locks explains how that works. And if the part that hurts is a job queue, see Postgres as a job queue.
A second app server is the end of it. Two processes cannot share the one write lock, and a file on NFS is worse. Money belongs on Postgres for the same reason: one locked writer is a fine way to run a blog and a bad way to take a payment.
Questions people ask
Is SQLite good enough for production? Yes, for the right job. The SQLite docs say it works great for most low to medium traffic websites. It is a good fit when one machine serves the site, reads dominate and writes are short. It is a poor fit when you need several app servers or many concurrent writers.
How many requests can SQLite handle? The docs give a rule of thumb: a site under about 100K hits a day should be fine, and 10 times that has been shown to work. Your real limit depends on how many requests write and how long each write takes. Measure your own write times before you trust a number from someone else.
Does WAL mode fix “database is locked”?
It fixes most of it, because readers and the writer stop blocking each other.
You can still see the error when two connections try to write at once, or when
a read transaction tries to upgrade to a write. Set busy_timeout, use one
write connection, and start writes with BEGIN IMMEDIATE.
Can two servers share one SQLite file? Not safely over a network drive. File locking on network filesystems is unreliable, and WAL needs every process on the same machine. Use Postgres, or put one app in front of the file and have the other servers call it.
Cheat sheet
Further reading
- SQLite docs: Write-Ahead Logging
- SQLite docs: PRAGMA statements
- SQLite docs: appropriate uses for SQLite
- SQLite docs: the online backup API
- SQLite docs: VACUUM and VACUUM INTO
- SQLite docs: SQLite over a network
- SQLite docs: transactions
- Litestream: how it works and tips and caveats
- How SQLite locks work on this site
- SQLite index optimisation on this site
- Postgres as a job queue and understanding PostgreSQL locks on this site