DEV Community

Libme
Libme

Posted on

SQLite vs Postgres for a Small SaaS: Fixing "database is locked" and Deciding Whether to Stay

If you are seeing database is locked and wondering whether SQLite was the wrong choice, usually it wasn't: the default settings were. SQLite with WAL mode, a busy timeout, and short write transactions handles a surprising amount of traffic for a single-server app. Move to Postgres when you need more than one app server writing, a managed failover story, or concurrent long-running writes, not just because you hit that error once.

Why does SQLite say "database is locked"?

The error looks like this in Python:

sqlite3.OperationalError: database is locked
Enter fullscreen mode Exit fullscreen mode

SQLite allows many readers but only one writer at a time. In the default rollback-journal mode, a writer also blocks readers. With default settings, a second connection that tries to write while another holds the lock fails right away, because Python's sqlite3 module gives you a 5-second timeout but many other drivers give you effectively none.

The dead ends I see most often: wrapping the call in a retry loop, bumping the timeout to 60 seconds, or deciding SQLite "can't do concurrency." None of these touch the usual cause, which is a transaction that starts as a read and later tries to upgrade to a write. If another connection wrote in between, SQLite returns SQLITE_BUSY immediately instead of waiting, because waiting could deadlock. The busy timeout does not help in that case.

The fix is two parts: configure the connection once, and begin write transactions as writes.

import sqlite3

def connect(path: str) -> sqlite3.Connection:
    # isolation_level=None -> we control BEGIN ourselves
    conn = sqlite3.connect(path, timeout=10, isolation_level=None)
    conn.execute("PRAGMA journal_mode = WAL")      # readers don't block the writer
    conn.execute("PRAGMA synchronous = NORMAL")    # common pairing with WAL
    conn.execute("PRAGMA busy_timeout = 10000")    # wait up to 10s for the lock
    conn.execute("PRAGMA foreign_keys = ON")       # off by default, per connection
    return conn

def credit_account(conn: sqlite3.Connection, account_id: int, cents: int) -> None:
    conn.execute("BEGIN IMMEDIATE")  # take the write lock up front
    try:
        conn.execute(
            "UPDATE accounts SET balance_cents = balance_cents + ? WHERE id = ?",
            (cents, account_id),
        )
        conn.execute("COMMIT")
    except Exception:
        conn.execute("ROLLBACK")
        raise
Enter fullscreen mode Exit fullscreen mode

BEGIN IMMEDIATE is the line that eliminated this error class in my own small apps: the transaction waits at the start, where the busy timeout works, instead of failing halfway through.

Takeaway: most database is locked errors come from read-then-write transactions and missing WAL, not from SQLite being unable to handle your traffic.

What does SQLite still not do well?

Be honest about the limits, because they are the real decision criteria:

  • One writer at a time, one machine. WAL needs shared memory on a local filesystem. Don't put the database file on a network share, and don't run two app servers against it.
  • No network protocol. Your app process is the database. Ad hoc access means SSH into the box, and your BI tool or a teammate's laptop can't just connect.
  • Fewer operational conveniences. Typing is looser by default (columns are more advisory than enforced unless you use STRICT tables), and schema changes are more limited than in Postgres, so some migrations mean rebuilding a table.
  • You own the backups. Copying the file while it's being written is not a backup. Use the .backup command, VACUUM INTO, or continuous replication.

Takeaway: SQLite's constraints are about topology (one box, one writer), so they bite when your deployment changes, not when your row count grows.

SQLite vs Postgres: how do they compare for a small SaaS?

Question SQLite (WAL) Postgres (managed or self-hosted)
Concurrent writers One at a time, fast and short Many, row-level locking
App servers One machine Any number
Connection overhead In-process, none Network + pooling to think about
Backups Your job: Litestream or snapshots Built-in on most managed offerings (verify restores)
Extensions, JSONB, rich types Limited Strong ecosystem
Ops surface Almost none Upgrades, vacuum, pooling, failover
Zero-downtime deploys Awkward: old and new process share one file Standard

That last row catches people. A rolling deploy where two processes briefly overlap works in WAL mode on one host, but a blue/green setup on separate machines does not.

Takeaway: if your app runs as one process on one server, SQLite removes a whole category of infrastructure; if it can't, the table decides for you.

How do you back up SQLite and avoid the "single server" trap?

Two tools cover most small-app needs, as of late 2026:

Litestream streams WAL changes to S3-compatible object storage, giving you point-in-time-ish restore without stopping the app. Its limitation is that it's disaster recovery, not high availability: if the server dies, you restore onto a new one and accept some downtime and a small window of lost writes. If you want continuous replication of a SQLite file to object storage without changing your app, Litestream is the tool that does exactly that and nothing more.

Turso, built on the libSQL fork of SQLite, gives you a hosted, network-accessible SQLite-compatible database, which removes the one-machine restriction. The tradeoff is that you are now on a network database with a vendor, and you should check its current limits and pricing model yourself before committing. If you want SQLite's query model but need multiple app servers or edge deployments, Turso is the managed option built for that.

Whichever you choose, run a restore drill. A replica you have never restored is a hope, not a backup.

Takeaway: SQLite plus continuous replication covers the "disaster recovery" need, but not the "survive a server loss without downtime" need.

When should you move to Postgres?

Move when any of these is true, in rough order of how often I see them:

  1. You need a second app server, or a separate worker box that writes.
  2. You have long write transactions (batch imports, report rebuilds) that make the single writer queue visible to users.
  3. You need extensions, full-featured JSONB, or logical replication into analytics.
  4. Compliance or customers require a managed database with defined failover.

If you plan to migrate eventually, avoid SQLite-only tricks (loose typing, rowid reliance) and keep SQL in a thin data layer so the move is a driver swap plus a data load. If you want the managed, multi-writer option with the largest ecosystem, Postgres is the default answer, and you'll pay for it in connection pooling and operational attention.

Takeaway: migrate on a topology or workload trigger you can name, not on a vague feeling that SQLite is "not production."

FAQ

Why does SQLite say database is locked even with a timeout?
A transaction that starts with a read and then writes can fail with SQLITE_BUSY immediately, ignoring the timeout. Start write transactions with BEGIN IMMEDIATE and enable WAL mode.

Is SQLite good enough for production?
Yes, for apps that run on a single server with short write transactions, provided you enable WAL, set a busy timeout, and have tested backups. It is the wrong fit when several servers must write to the same database.

Can multiple processes write to the same SQLite database?
Yes, on the same machine, but writes are serialized: one at a time, with others waiting up to the busy timeout. It does not work reliably across machines or over network filesystems.

Bottom line

If you run one server, have modest write volume, and can tolerate restoring from a replica after a hardware failure, start with SQLite in WAL mode and use Litestream for backups. If you need several app servers, long concurrent writes, or managed failover, start on Postgres and accept the operational cost. Turso sits in between for teams that want SQLite semantics with network access. Whatever you pick, name the trigger that would make you switch.

Related reading

Top comments (0)