SQLite Best Practices for Production: When and How to Use It

Today we will see how to run SQLite safely in production, which settings to apply and where it stops being the right choice. SQLite is an embedded, serverless SQL engine that reads and writes a single file inside your application process. This guide is for engineers, architects and DBAs who want to follow SQLite best practices production teams can rely on, without guessing.

We will cover a fit check, WAL mode and PRAGMA settings, schema design, concurrency and connection handling, backups, security and upgrades. Each section explains the reason behind the rule, so you can decide when a rule does not apply to your case.

Before we start, check the version. The latest release is SQLite 3.54.1, dated 2026-10-16, a patch release that fixes a few problems in 3.54.0 (2026-10-09). SQLite follows a latest-version model, so there is no LTS line and no fixed end-of-life date. STRICT tables need SQLite 3.37 or later. The examples use the sqlite3 shell, C# (Microsoft.Data.Sqlite) and Python.

Version note: This guide targets SQLite 3.54.1 (released 2026-10-16), with notes on the 3.53 line (latest 3.53.4) and a 3.37 minimum for STRICT tables.

 

In this guide

 

 

SQLite Best Practices for Production at a Glance

 

Yes, SQLite is production-ready when the application and the database file live on the same machine and your write volume fits a single-writer model. A single-writer model means only one write transaction runs at a time, while any number of readers can run alongside it. If your writes can be batched and queued through one connection, SQLite in production works well.

Note: SQLite is a library that opens one file inside your own process, not a server you connect to. Think of a notebook you carry with you versus a records office you phone. The notebook is instant and needs no staff, but only the person holding it can write in it. The analogy stops fitting in one place: several readers can look at the same SQLite file at once.

Which SQLite Production Practices Matter Most?

The table below lists the rules this guide covers, with the practice to follow and the mistake to avoid for each area.

Area Do this Avoid this
Fit Use it for same-machine access with a serialized writer Many networked clients writing to one file
Journal mode Enable WAL (write-ahead log) mode Default rollback journal under mixed read/write load
Per-connection PRAGMAs Set synchronous, busy_timeout, foreign_keys and cache_size on every connection Assuming settings carry over from other connections
Schema types Use STRICT tables Relying on type affinity to reject bad values
Transactions Use BEGIN IMMEDIATE for writes and batch inserts One commit per row, or deferred transactions that write
Connections One writer plus several readers Many connections competing to write
Backups Use .backup or VACUUM INTO, then test restores Copying only the .db file
Storage Local disk or a single-attached block volume NFS or CIFS network shares
Upgrades Track patch releases and check the driver’s bundled version Pinning an old version forever
Security Restrict file permissions, encrypt, use bound parameters World-readable files and string-built SQL

When Should You Use SQLite?

Use SQLite when simple administration and maintenance matter more than enterprise features. The official guidance names embedded and IoT devices, local data files, data analysis and caches of enterprise data as good fits.

Choose a client/server database when many client programs send SQL to the same database over a network. SQLite still works when the application server and the file sit on the same machine, even if end users are another network hop away. The animated diagram below walks a new workload through three questions to reach a decision.

Decision tree: three questions on networked writers, local disk and a single serialized writer lead to SQLite with WAL or PostgreSQL/MySQL.
Any failing answer routes to a client/server database; passing all three questions makes SQLite with WAL a good fit.

SQLite vs PostgreSQL vs MySQL

This table compares the three engines on the points that most often decide the choice.

Concern SQLite PostgreSQL MySQL
Process model Library inside your process Separate server Separate server
Concurrent writers One at a time Many Many
Network access None built in Built in Built in
Administration Minimal, one file Users, tuning, upgrades Users, tuning, upgrades
Replication None built in; use backup streaming tools Built-in streaming replication Built-in replication
Typing Flexible affinity; STRICT is opt-in Strictly typed columns Typed columns, enforcement set by SQL mode

When Should You Move from SQLite to PostgreSQL?

Move when one of these triggers appears, and not before. Each one means the single-writer, same-machine model no longer holds.

  • Shared data: several app servers need the same data at the same time.
  • Write queueing: writes keep queueing even after batching and short transactions.
  • Missing features: your workload needs features SQLite does not offer.
  • Replication and roles: you need built-in streaming replication or fine-grained roles.
  • Network storage: the file must live on network storage you cannot avoid.

SQLite WAL Mode and PRAGMA Settings for Production

For SQLite in production, enable WAL, set synchronous=NORMAL, busy_timeout, foreign_keys=ON and a larger cache on every connection. WAL (write-ahead log) is a journal mode where changes are appended to a separate -wal file instead of overwriting pages in the main database file.

Note: Think of a shop ledger with a separate logbook beside it. New entries go into the logbook first and are merged into the main ledger later. Readers keep reading the old ledger pages while one writer adds to the logbook. The analogy stops at one point: SQLite still allows only one writer at a time.

Which SQLite PRAGMA settings should you use?

The table below shows each setting, where it is stored, a common production value and the reason. Only journal_mode survives in the file, so the rest belong in your connection factory.

Setting Persistence Recommended value Why
journal_mode Stored in the database file WAL Readers don’t block the writer, and the writer doesn’t block readers.
synchronous Per connection NORMAL Fewer disk syncs in WAL. A power loss can drop the latest commits, but the file stays consistent.
busy_timeout Per connection 5000 (ms) Waits for a lock instead of failing at once with SQLITE_BUSY.
foreign_keys Per connection ON Enforcement is off by default, so constraints are ignored without it.
cache_size Per connection -64000 A negative number means KB, so this is about 64 MB of page cache.

Run this block in the sqlite3 shell, or issue the same statements from your driver on every new connection:

SQL

-- Persistent: stored in the database file
PRAGMA journal_mode = WAL;

-- Per connection: repeat on every open
PRAGMA synchronous = NORMAL;   -- fewer fsyncs than FULL, safe with WAL
PRAGMA busy_timeout = 5000;    -- wait up to 5 seconds for a lock
PRAGMA foreign_keys = ON;      -- off by default
PRAGMA cache_size = -64000;    -- negative value = KB (about 64 MB)

Setting journal_mode needs a lock, so it can fail with “database is locked” when the file is busy. Run it once at startup or in a migration step, not on every request.

What are the WAL mode limits you must know?

  • One writer, many readers: a second writer waits until the first commits or rolls back.
  • Library version: SQLite before 3.7.0 can’t read a WAL database and reports “file is encrypted or is not a database”. Every tool and driver that opens the file must be recent enough.
  • Shared memory file: WAL uses a -shm file, so keep the database on a local disk.
  • Exclusive locking mode: if one connection opens the file in exclusive mode, others can get SQLITE_BUSY. If you set EXCLUSIVE before the first WAL access, no wal-index is created, and the mode stays exclusive until you leave WAL.

How do you stop the WAL file from growing?

The -wal file grows until a checkpoint copies its content back into the main file. A long-running reader can block that copy (checkpoint starvation), and the WAL keeps growing.

  1. Keep read transactions short: close cursors and transactions as soon as the work is done.
  2. Monitor the file size: alert when the -wal file keeps growing across several checks.
  3. Force a checkpoint if needed: run it in a quiet period, as shown below.

This statement copies the WAL back and resets the file. It returns three numbers: a busy flag, pages in the log and pages checkpointed.

SQL

PRAGMA wal_checkpoint(TRUNCATE);

Schema Design, Indexing and Query Optimization

Use STRICT tables, an INTEGER PRIMARY KEY, indexes that match your filters, and bound parameters. Without STRICT, SQLite’s type affinity (its loose rules for converting values to a column’s declared type) silently accepts a value of the wrong type, such as text in an integer column. STRICT needs SQLite 3.37 or later and is painful to retrofit, so add it when you create the table.

Note: A normal SQLite column is like a form field with a hint label: the hint says “number”, but the clerk accepts whatever you write. A STRICT column is a field that rejects the wrong kind of entry at the counter.

How do you define a production-ready table?

Here is a simplified retail orders table with a foreign key, a CHECK constraint and a composite index:

SQL

CREATE TABLE customers (
  id    INTEGER PRIMARY KEY,
  email TEXT NOT NULL UNIQUE
) STRICT;

CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES customers(id),
  status      TEXT    NOT NULL CHECK (status IN ('new','paid','shipped','cancelled')),
  total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
  created_at  TEXT    NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
) STRICT;

CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at);

INTEGER PRIMARY KEY becomes an alias for the internal rowid, so lookups by id go straight to the row. Keep rows narrow and store large blobs elsewhere, because wide rows mean fewer rows per page and more disk reads.

How do you confirm a query uses an index?

Run EXPLAIN QUERY PLAN and look for SEARCH instead of SCAN:

SQL

EXPLAIN QUERY PLAN
SELECT id, total_cents FROM orders
WHERE customer_id = ? AND created_at >= ?;
-- Expected: SEARCH orders USING INDEX idx_orders_customer_created (...)

A SCAN on a large table means a full read, so add or reorder an index.

How do you write safe and fast inserts?

Pass values as bound parameters (?), never through string formatting. This stops SQL injection and lets SQLite reuse the prepared statement. Batch rows in one transaction, because every commit costs a sync to disk.

Python

import sqlite3

conn = sqlite3.connect("shop.db")
conn.execute("PRAGMA foreign_keys = ON")

rows = [(1, "new", 2599), (1, "paid", 1200), (2, "new", 899)]

with conn:  # one transaction, one commit
    conn.executemany(
        "INSERT INTO orders (customer_id, status, total_cents) VALUES (?, ?, ?)",
        rows,
    )

Which SQLite 3.53 changes affect your schema?

  • Constraint changes: ALTER TABLE can add and remove NOT NULL and CHECK constraints, which removes the need for a table rebuild in some migrations.
  • Expression indexes: 3.53.0 dealt with stale expression indexes. If you index expressions, upgrade to 3.53.4 or later and run REINDEX EXPRESSIONS.
  • JSON helpers: json_array_insert() and jsonb_array_insert() were added.

Fix SQLite ‘database is locked’ Errors: Concurrency and Connection Pooling

The SQLITE_BUSY error (shown as “database is locked”) happens because SQLite runs only one write transaction at a time, even in WAL mode. To fix it, serialize writes, start write transactions with BEGIN IMMEDIATE and keep them short.

Why does a deferred transaction fail even with busy_timeout?

A plain BEGIN is deferred. It starts as a reader and tries to become a writer only when it runs its first write. If another connection has written in between, that upgrade fails with SQLITE_BUSY straight away, and busy_timeout does not help. BEGIN IMMEDIATE takes the write lock at the start, so busy_timeout can wait for it.

The animated diagram below shows both cases, first the failing deferred transaction and then the fixed version.

Note: A deferred transaction is like queueing at a counter to look at a file, then asking to edit it after someone else has taken the only edit slot. BEGIN IMMEDIATE takes a ticket for the edit slot before you start, so you simply wait your turn.

What is the right connection pooling pattern?

Use one writer connection, or one mutex or write queue in the app, plus several reader connections. In WAL mode readers do not block the writer. Guides suggest moving to PostgreSQL only when this model is outgrown, not before.

C# example with Microsoft.Data.Sqlite

This simplified helper applies the PRAGMAs on each connection and runs writes inside an immediate transaction, guarded by a SemaphoreSlim:

C#

using Microsoft.Data.Sqlite;

public sealed class SqliteStore
{
    private static readonly SemaphoreSlim WriteGate = new(1, 1);
    private readonly string _cs;

    public SqliteStore(string path) =>
        _cs = new SqliteConnectionStringBuilder { DataSource = path }.ToString();

    public async Task<SqliteConnection> OpenAsync()
    {
        var conn = new SqliteConnection(_cs);
        await conn.OpenAsync();
        using var cmd = conn.CreateCommand();
        cmd.CommandText = @"PRAGMA busy_timeout = 5000;
                            PRAGMA synchronous = NORMAL;
                            PRAGMA foreign_keys = ON;
                            PRAGMA cache_size = -64000;";
        await cmd.ExecuteNonQueryAsync();
        return conn;
    }

    public async Task WriteAsync(Action<SqliteConnection, SqliteTransaction> work)
    {
        await WriteGate.WaitAsync();
        try
        {
            await using var conn = await OpenAsync();
            using var tx = conn.BeginTransaction(deferred: false); // BEGIN IMMEDIATE
            work(conn, tx);
            tx.Commit();
        }
        finally { WriteGate.Release(); }
    }
}

Passing deferred: false makes the provider issue BEGIN IMMEDIATE. Add your own retry logic if needed.

Python example with sqlite3

Here isolation_level=None stops the module from opening transactions on its own, so you control BEGIN IMMEDIATE yourself:

Python

import sqlite3
from contextlib import contextmanager

def connect(path, readonly=False):
    mode = "ro" if readonly else "rw"
    conn = sqlite3.connect(f"file:{path}?mode={mode}", uri=True,
                           isolation_level=None, timeout=5)
    conn.execute("PRAGMA busy_timeout = 5000")
    conn.execute("PRAGMA foreign_keys = ON")
    conn.execute("PRAGMA synchronous = NORMAL")
    return conn

@contextmanager
def write_tx(conn):
    conn.execute("BEGIN IMMEDIATE")
    try:
        yield conn
        conn.execute("COMMIT")
    except Exception:
        conn.execute("ROLLBACK")
        raise

writer = connect("app.db")
reader = connect("app.db", readonly=True)

with write_tx(writer) as db:
    db.execute("UPDATE orders SET status = ? WHERE id = ?", ("shipped", 42))

The reader opens with mode=ro, so it cannot write by accident.

Troubleshooting checklist for SQLite database is locked

Check these causes in order:

  1. Long read transactions: a reader that stays open holds a snapshot and delays checkpoints. Close it quickly.
  2. Missing busy_timeout: without it, a blocked connection fails at once instead of waiting.
  3. Forgotten open cursor: an unfinished SELECT keeps a read transaction alive. Fetch all rows or close the cursor.
  4. Exclusive locking mode: another process that set locking_mode=EXCLUSIVE can make other connections get SQLITE_BUSY.
  5. Network share: NFS or CIFS locking is unreliable. Move the file to local storage.

Backups, Replication, Security, Containers and Upgrades

Back up a live SQLite database with the backup API (.backup) or VACUUM INTO, never by copying only the .db file of a WAL database, and test every restore. The rest of this section covers replication, storage, security, upgrades and monitoring.

How Do You Back Up a Live SQLite Database?

Both methods produce one consistent file while the app keeps serving traffic. Here are the two options in the sqlite3 shell:

SQL (sqlite3 shell)

.backup 'backup.db'

VACUUM INTO 'backup.db';

-- SQLite 3.53+: URI target with reserve=N (0 to 255)
VACUUM INTO 'file:backup_reserved.db?reserve=32';

✅ .backup uses the backup API. VACUUM INTO also writes a compacted copy, which is handy for archives.

Here is the same backup from Python, using Connection.backup():

Python

import sqlite3

src = sqlite3.connect("app.db")
dst = sqlite3.connect("backup.db")
try:
    src.backup(dst)
finally:
    dst.close()
    src.close()

Note: The backup API is like asking a clerk to photocopy a ledger together with the loose pages not yet filed into it. Copying only the .db file photocopies the bound book and ignores those pages.

Why Does Copying Only the .db File Fail?

In WAL mode, the -wal and -shm files can hold committed data that is not yet in the main file. A copy of only app.db can therefore be stale or broken.

The animated diagram below shows a safe backup and restore test next to the unsafe file copy.

Pipeline: app with app.db, -wal and -shm feeds a backup job, then backup.db, object storage and a restore test. A red cp app.db path is stale.
Back up with the backup API or VACUUM INTO and verify each restore; copying only app.db in WAL mode can miss committed data.

How Do You Test a Restore?

A backup is only proven when it opens and its data matches. Run these steps on a schedule:

  1. Download: Fetch the latest backup into a scratch folder.
  2. Check integrity: Open it and run PRAGMA integrity_check;. The result should be ok.
  3. Compare counts: Check row counts of key tables (e.g. orders, customers) against expected values.
  4. Rehearse: Practice the full recovery, not just the check.

Is Litestream-Style Replication Worth It?

Yes, if losing data since the last snapshot is not acceptable. Tools like Litestream stream WAL changes to object storage, so data loss is limited to the most recent changes. It needs WAL mode.

The trade-off is that this is backup and recovery, not a multi-writer cluster. Reads and writes still go through one primary file.

How Do You Run SQLite in Docker and Kubernetes?

Use a local volume or block storage attached to one pod. WAL relies on shared memory, so it is unreliable on NFS or CIFS.

  • Kubernetes: Use a StatefulSet with one replica and a dedicated persistent volume.
  • Replicas: Never run several replicas that write the same file.
  • Docker: Mount a local volume for the whole directory, so the -wal and -shm files stay with the database.

How Do You Secure a SQLite Database?

Treat the file as the database server’s data directory. Anyone who can read it can read everything.

  • Permissions: Allow only the service account to access the file and the directory holding -wal and -shm.
  • Encryption: Use an extension such as SQLCipher, or disk-level encryption.
  • Queries: Always use bound parameters.

Example: a clinic app stores patient notes in a local SQLite file. Encrypting the file, or the disk under it, means a stolen laptop or backup does not expose records.

How Should You Handle SQLite Upgrades?

Track patch releases. SQLite has no LTS line or fixed end-of-life dates, and only the newest line (3.54, latest 3.54.1 released 2026-10-16) is current. The 3.53.4 notes mention fixes for mostly AI-discovered bugs, so pinning an old version has a real cost.

Check the SQLite version bundled in your language driver, not just the OS package. They are often different.

What Should You Monitor?

  • WAL size: A growing -wal file points to long readers blocking checkpoints.
  • Errors: Count busy and locked errors.
  • Latency: Track query time.
  • Disk: Alert on low free space.
  • Backups: Alert when the last good backup is too old.

Common Anti-Patterns and Production Readiness Checklist

Most SQLite problems in production come from a few habits that work on a laptop and fail under real load. The table below lists the ten most common ones with the symptom you will see and the fix.

Note: An anti-pattern is a habit that looks fine in testing but causes trouble under production load. It is like leaving a kitchen knife loose in a drawer: nothing happens until the day you reach in without looking.

Which SQLite Anti-Patterns Should You Avoid?

Anti-pattern Symptom Fix
Default rollback journal under mixed load Readers and writers block each other Enable SQLite WAL mode once at startup
foreign_keys never enabled Orphan rows, no error on bad deletes Run PRAGMA foreign_keys=ON on every connection
Deferred transactions that write Instant SQLITE_BUSY, busy_timeout ignored Start writes with BEGIN IMMEDIATE
One commit per row Slow bulk inserts Batch rows in one transaction
Database file on NFS Locking errors, unreliable WAL Use a local disk or attached block storage
Copying only the .db file Stale or broken backup Use .backup or VACUUM INTO
Many app replicas sharing one file Frequent “database is locked” errors Run one writer process, or move to PostgreSQL
Non-STRICT tables with mixed types Text stored in integer columns Create tables with STRICT (3.37+)
Unbounded WAL growth from long readers The -wal file keeps growing Keep reads short, run wal_checkpoint(TRUNCATE) when quiet
Pinning an old SQLite version forever Known bugs stay in your build Track patch releases, currently 3.54.1

What Is the SQLite Production Readiness Checklist?

Work through these steps in order before you run SQLite in production.

  1. Confirm fit: the app and file share one machine, and you have written down your PostgreSQL migration triggers.
  2. Check the driver version: find the SQLite version bundled with your language driver, not just the OS package.
  3. Turn on WAL: set journal_mode=WAL in a startup or migration step.
  4. Set PRAGMAs per connection: apply synchronous, busy_timeout, foreign_keys and cache_size in the connection factory.
  5. Use a STRICT schema: add constraints and indexes that match your filters.
  6. Serialize writes: use BEGIN IMMEDIATE with one writer connection or a mutex.
  7. Keep storage local: no NFS or CIFS, and one writer pod in Kubernetes.
  8. Schedule backups: use the backup API and test restores with PRAGMA integrity_check.
  9. Monitor: watch -wal size, busy errors, free disk and backup age.
  10. Patch regularly: set a routine to update to new SQLite releases.

Key takeaways

Here are the main points to remember when you run SQLite in production:

  • Check the fit first: SQLite is production-ready when the app and the database file live on the same machine and writes fit a single-writer model. Move to PostgreSQL when several app servers need the same data or writes keep queueing even after batching.
  • Use WAL and set PRAGMAs on every connection: journal_mode=WAL is saved in the file, but synchronous, busy_timeout, foreign_keys and cache_size must be applied each time you open a connection. Put them in one connection factory.
  • Use BEGIN IMMEDIATE for writes: A deferred transaction that upgrades to a writer can fail with SQLITE_BUSY right away, and busy_timeout will not help. Take the write lock up front, serialize writes in the app, and keep transactions short.
  • Design the schema strictly: Use STRICT tables, INTEGER PRIMARY KEY, indexes that match your filters, bound parameters, and one transaction per batch instead of one commit per row.
  • Back up with the right tools: Use .backup, the backup API or VACUUM INTO. Never copy only the .db file of a WAL database, and test every restore with PRAGMA integrity_check and row counts.
  • Keep the file on local disk: WAL needs shared memory, so avoid NFS and CIFS. In Docker or Kubernetes use a local volume or block storage attached to a single pod, and never run several replicas that write the same file.
  • Track patch releases: SQLite has no LTS line or fixed end-of-life dates, and only the newest line (3.54, latest 3.54.1) is current. Check the SQLite version bundled with your language driver, not just the OS package.

That’s all! Happy coding!

Did this solve the issue you were facing? Please share your questions or experience in the comments below. If you found this guide useful, bookmark it and share it with your team. Subscribe to TheCodeBuzz to get new database best-practice articles in your inbox.

FAQ

Is SQLite good enough for production?

Yes, when the application and the database file are on the same machine and your writes can run through a single serialized writer. Turn on WAL mode, set the per-connection PRAGMAs, and keep write transactions short. If several app servers need the same data over a network, a client/server database is the better choice.

When should I use SQLite instead of PostgreSQL or MySQL?

Use SQLite for embedded and IoT devices, local data files, data analysis, caches of enterprise data, and small to medium sites that run on one server. It works best when simple administration matters more than enterprise features. Choose PostgreSQL or MySQL when many client programs send SQL to the same database over a network, or when you need built-in streaming replication or fine-grained roles.

How many concurrent writers can SQLite handle?

One at a time. In WAL mode, many readers can run alongside that single writer, and a second writer waits until the first commits or rolls back. Real write throughput depends on how well you batch rows into transactions and on how fast your disk syncs, so measure it on your own hardware.

How do I fix ‘database is locked’ (SQLITE_BUSY) errors?

Start by setting busy_timeout on every connection, so a waiting writer retries instead of failing at once. Then use BEGIN IMMEDIATE for any transaction that writes, keep transactions short, and send all writes through one writer connection or a mutex. If errors continue, look for long-running read transactions, open cursors that were never closed, and a database file on a network share.

How do I back up a SQLite database that is in use?

Use the .backup command in the sqlite3 shell (it uses the backup API) or VACUUM INTO 'backup.db'. Both give a consistent copy while the app keeps running. Don’t copy only the .db file of a WAL database, because the -wal and -shm files can hold committed data that isn’t in the main file yet. After each backup, open the copy and run PRAGMA integrity_check to confirm it is usable.

Sources and further reading

Diagrams are original illustrations created for TheCodeBuzz.

Leave a Reply

Your email address will not be published. Required fields are marked *