/writing/two-ways-sqlite-transactions-arent-what-you-think

Two Ways SQLite Transactions Aren't What You Think

I have a small side project built the way a lot of side projects are built now: FastAPI, SQLAlchemy, a single SQLite file, and a background worker that sends uploaded documents to an LLM and writes back what it extracts. Within a week of each other it taught me two things about SQLite transactions that I thought I already knew. Neither showed up in tests, and both produce very confident wrong behaviour.

Trap one: the transaction you didn’t know you opened

The symptom was simple. Upload a document while another one was being read, and the upload failed with sqlite3.OperationalError: database is locked. Not every time, only while the worker was busy.

The worker looked innocent. Roughly:

def process(db, doc_id):
    doc = db.get(Document, doc_id)
    run = ParseRun(document_id=doc.id, started_at=now())
    db.add(run)
    db.flush()                         # need run.id for the log lines

    result = llm.extract(doc.path)     # 6 to 30 seconds

    run.status = "ok"
    store_results(db, run, result)
    db.commit()

No explicit BEGIN, no long-held lock anywhere in the code. But the flush() to get an ID wrote a row, and a write inside SQLAlchemy’s session opens a transaction that stays open until commit(). So the worker took SQLite’s write lock and then went off to wait for an LLM for up to half a minute.

SQLite has exactly one writer per database file. While that transaction was open, every other connection that tried to write queued behind it, waited out the busy timeout (five seconds by default in Python’s driver), and gave up. The upload handler was just the first thing that happened to need a write.

Two details make this easy to miss:

  • The ORM opens transactions for you. A flush(), an insert to get a primary key, even a lazy-loaded relationship can start one. Nothing in the code says “transaction”.
  • Even a read can do it. In SQLite a deferred transaction takes a shared lock on its first read. If the session is still inside that transaction when another connection wants to commit, the writer waits. Reads-then-slow-call has the same shape as writes-then-slow-call.

WAL mode doesn’t save you here. It lets readers and one writer run at the same time, but there is still only one writer, and the worker was the writer.

The fix is to never hold a transaction across the slow call. Gather what you need, commit, make the call outside any transaction, then write the results in a fresh short one:

def process(db, doc_id):
    doc = db.get(Document, doc_id)
    path, started = doc.path, now()
    db.commit()                        # release everything before the slow part

    result = llm.extract(path)

    run = ParseRun(document_id=doc_id, started_at=started, status="ok")
    db.add(run)
    store_results(db, run, result)
    db.commit()

The run record still carries the real start time. It just gets inserted afterwards.

The part I’d push hardest on is the regression test, because request-scoped tests never catch this: nothing else is writing while a single test request runs. So the test fakes the slow call and, inside it, commits a write from a second session with a short busy timeout:

def test_uploads_can_write_while_a_document_is_being_read(monkeypatch):
    db = SessionLocal()
    doc = add_doc(db, "slow.pdf")
    db.commit()

    def slow_read(path, **kw):
        other = SessionLocal()
        other.connection().exec_driver_sql("PRAGMA busy_timeout = 200")
        add_doc(other, "uploaded-meanwhile.pdf")
        other.commit()                 # fails with "database is locked" on the old code
        other.close()
        return fake_result()

    monkeypatch.setattr(llm, "extract", slow_read)
    assert process(db, doc.id).status == "ok"

On the old code that test fails in 200 ms. On the new code it passes. Now the bug can’t come back quietly.

Trap two: the migration that wasn’t atomic

The second one I caught while first setting up migrations, before it had a chance to bite.

SQLite supports transactional DDL. CREATE TABLE, ALTER TABLE and friends can be rolled back like anything else. So if your migration tool wraps each migration in a transaction and logs a rollback on failure, you’d assume a failed migration leaves the schema exactly as it was.

Through Python’s standard sqlite3 driver, in its default mode, it doesn’t. The driver opens transactions implicitly, and only before data-changing statements: INSERT, UPDATE, DELETE. Schema statements run in autocommit. The ORM’s “begin” is a no-op that defers to the driver, so a migration that does this:

  1. create a new table
  2. copy data into it
  3. drop the old table and rename the new one

and fails during step 2 (a type error on one bad row, a constraint violation) has already committed step 1. The framework logs a rollback, the version marker still says the old revision, and the next run tries to create a table that already exists. It collides with its own half-finished work.

That’s the nasty part. In review the code looks atomic, the logs say it rolled back, and the failure only appears when a migration fails on real data, which is exactly when you most need the rollback to be real.

With SQLAlchemy the fix is two event hooks that take transaction control away from the driver and give it to the ORM:

from sqlalchemy import create_engine, event

def make_engine(url):
    eng = create_engine(url)

    @event.listens_for(eng, "connect")
    def _on_connect(dbapi_conn, _):
        # pysqlite would otherwise autocommit DDL; let SQLAlchemy own BEGIN/COMMIT
        dbapi_conn.isolation_level = None

    @event.listens_for(eng, "begin")
    def _on_begin(conn):
        conn.exec_driver_sql("BEGIN")

    return eng

isolation_level = None stops the driver from managing transactions at all, and the begin hook emits a real BEGIN whenever SQLAlchemy starts one. Now DDL is inside the transaction and a rollback undoes it.

Don’t take that on trust either. Prove it with a test that creates a table inside engine.begin(), raises, and asserts the table doesn’t exist afterwards. That’s a five-line test that pins down behaviour you’d otherwise only discover in production.

And whatever the engine, back up the database file before applying pending migrations, as an automatic step, not a habit. With SQLite that’s one file copy. It covers the failure case and also the “migration ran correctly but I didn’t want it” case, which no amount of transaction handling helps with.

If you’re on MySQL or Oracle, DDL commits implicitly at the server and there is no driver setting that fixes it. There, write each migration so a rerun skips steps that already completed. PostgreSQL’s DDL is properly transactional.

What the two have in common

Both bugs come from the same gap: the transaction boundary you see in the code is not the one the database sees. In the first case a transaction existed that the code never mentioned. In the second, a transaction the code clearly asked for didn’t cover what it appeared to cover.

A few habits that would have caught both earlier:

  • Treat any slow external call (LLM, HTTP, subprocess) as a point where no transaction may be open. Commit before it, open a new one after it.
  • Test concurrency on purpose. One request at a time will never show lock contention. Inject the second writer inside the slow section and give it a short busy timeout so it fails fast.
  • Test that rollback actually rolls back. Especially for schema changes, and especially on SQLite through Python.
  • Back up before migrating, automatically. It’s the cheapest insurance you’ll ever buy for a single-file database.

SQLite is a great default for small projects. It just has one writer and a driver with opinions, and the moment you add a slow call or a schema change, both start to matter.