Skip to content

Concurrent read/write against a SQLite-backed endpoint fails with 500s ('database is locked') #116

Closed

Description

@jrosskopf

Summary

Concurrent GET + POST traffic against a SQLite-backed endpoint makes flAPI return
500 for every request, including the reads. Found while un-parking the load
suite (the old xfail reason — "server performance degrades under high
concurrent load"
— turns out to be neither a performance problem nor general).

Reproduce

cd test/integration
FLAPI_BUILD_TYPE=release uv run pytest \
  "test_load_testing.py::TestConcurrentRequests::test_mixed_read_write_operations" -v

50 interleaved requests (25 GET, 25 POST) against /northwind/products/,
which is backed by the northwind-sqlite connection.

Result: 0 of 50 succeed. Fails standalone in ~11 s.

Each test passes individually — 200 concurrent GETs pass in 3 s, 50 concurrent
POSTs pass in 9 s. Only the mix fails.

Cause

SQLite permits a single writer. Under mixed load the server logs 50 errors:

[ERROR] Error handling write request: Query execution failed during write operation
        statement 1: Invalid Error: Failed to prepare query
        "SELECT type FROM sqlite_master WHERE lower(name)=lower('Products');": database is locked
[ERROR] Error handling request: Query execution failed: Invalid Error: database is locked

Breakdown from one run: 23 write failures, 21 read failures, 4 bare "database is
locked", 1 failed commit — and one further bug:

[ERROR] Failed to rollback transaction: Query execution failed during rollback
        transaction: TransactionContext Error: cannot rollback - no transaction is active

The rollback path runs when no transaction is active, so the real error is
compounded by a spurious one.

Why it matters

  1. Reads fail too. A writer's lock takes down concurrent readers, which is
    worse than serialising writes.
  2. Wrong status code. Lock contention is transient and retryable — it should
    be 503 with Retry-After, not 500.
  3. No retry or backoff. SQLite's busy-timeout is not configured, so flAPI
    gives up immediately instead of waiting out a contended write.
  4. The rollback bug produces misleading log noise on every failure.
  5. Undocumented limitation. examples/sqls/northwind/ ships write endpoints
    over SQLite with no note that the backend cannot serve concurrent writes.

Suggested fixes

  • Set SQLite's busy_timeout on the connection, and/or serialise writes per
    connection so readers are not collateral damage.
  • Map lock contention to 503 + Retry-After instead of 500.
  • Only roll back when a transaction is actually active.
  • Document the constraint on the northwind example.

Scope

Pre-existing; not introduced by any current branch. Found during issue 0 of the
observability epic (feat/otel-observability), which required a working load
suite. Filed rather than fixed so that epic does not absorb an unrelated
backend concurrency fix.

The concurrency tests in test/integration/test_load_testing.py are marked
xfail referencing this issue — a precise, measured reason, unlike the
unexplained marker they replace.

Activity

  1. added
    bug
    on Sep 15, 2026
  2. jrosskopf commented on Sep 15, 2026

    @jrosskopf
    ContributorAuthor

    Additional data point from the observability epic branch (feat/otel-observability).

    test_concurrent_post_requests — 50 concurrent POSTs to /northwind/products/ — passes in isolation (~10s) but fails intermittently under full-suite contention. Server log for a reproducing run shows 49 occurrences of:

    Invalid Error: Failed to prepare query "SELECT type FROM sqlite_master WHERE lower(name)=lower('Products');": database is locked
    

    Same root cause as the original report, so it is now marked with the same opt-in skip (FLAPI_RUN_BLOCKED_CONCURRENCY=1) rather than left flaky. That brings the count of tests blocked on this issue to 7.

    Worth noting for whoever picks this up: the failures are not limited to writers. Concurrent readers fail too, because SQLite's writer lock takes them down as collateral damage — which is why a fix probably needs a busy-timeout plus serialising writes per connection, not just retrying the write.

  3. jrosskopf commented on Sep 18, 2026

    @jrosskopf
    ContributorAuthor

    Root cause located: an orphaned SQLite write transaction

    Investigated on v26.09.18 + the retry/503 fixes. The wedge is now characterised precisely.

    Minimum trigger

    8 concurrent mixed GET/POST requests. Not 50 — measured by bisection:

    Concurrency Result Recovery probe
    2 1× 200, 1× 201, instant 200
    4 2× 200, 2× 201, ~1 s (retries firing) 200
    8 1× 201, 7× timeout hangs — permanently

    Evidence

    With the server wedged:

    • A northwind.sqlite-journal file exists and never goes away (8720 bytes, frozen). A SQLite rollback journal is deleted on commit or rollback, so its persistence means a write transaction began and completed neither.
    • 13 file descriptors on the database are held open by the process, and the count is stable — so this is not an unbounded descriptor leak, it is one attachment frozen mid-transaction.
    • An unrelated process cannot read the database: sqlite3.connect(...).execute('select count(*) ...') → database is locked. The lock is real and at the file level.
    • Meanwhile /health/live returns 200 and a parquet-backed endpoint returns instantly. Only the SQLite attachment is affected.

    Why retries do not help

    The failing requests hang rather than erroring. My retry loop only fires when DuckDB returns "database is locked"; here the call blocks inside the driver indefinitely, so there is nothing to catch and nothing to retry. That is why the 503 mapping never triggers in the wedged state — the request never gets far enough to fail.

    It is an availability problem, not a data-integrity one

    After killing the server:

    • The journal survives shutdown — flAPI does not roll back or clean up the orphaned transaction on the way out.
    • But SQLite recovers correctly on the next open: 82 rows, pragma integrity_check → ok.

    So a restart clears it and no data is lost. The cost is that a running instance serves nothing from SQLite until restarted, while passing every health check.

    Where the fix likely belongs

    QueryExecutor opens a DuckDB connection per query and disconnects in its destructor — but the SQLite ATTACH is database-scoped, not connection-scoped. Disconnecting the DuckDB connection therefore does not end a transaction the sqlite extension has open on the attachment. Once a write transaction is orphaned that way, nothing in flAPI's lifecycle ever ends it.

    Candidate directions, in the order I would try them:

    1. Serialise writes per attachment. One writer at a time removes the race that orphans the transaction in the first place. Cheapest, and matches what the backend can actually do.
    2. Ensure the transaction is always terminated. The in_transaction guard now added covers the error path within a request; it does not cover a request whose thread is torn down, or a BEGIN whose owning connection goes away. Worth confirming whether duckdb_disconnect is even expected to roll back an attachment-level transaction.
    3. Make readiness exercise the connection, so a wedged attachment stops passing health checks instead of silently absorbing traffic.

    (1) and (3) are independently valuable: (1) prevents it, (3) contains it.

  4. jrosskopf commented on Sep 18, 2026

    @jrosskopf
    ContributorAuthor

    Write serialisation: tried and falsified

    Serialising writes per connection (one writer at a time on a single-writer backend) seemed like the obvious prevention. It is not — measured against a control on the same tree:

    Wedge threshold
    Per-connection write serialisation n=5
    Control (no serialisation) n=6
    Earlier run, same control n=8

    The threshold is noisy in the 5–8 range, so serialisation made no measurable difference in either direction. It does not prevent the wedge, so it is not being shipped — recording it here so nobody spends the afternoon on it again.

    That also rules out the hypothesis: the orphaned transaction is not caused by writer-vs-writer contention.

    Containment shipped separately: #119

    Since the wedge cannot currently be prevented, #119 makes it visible instead. Readiness now fails when a request has been in flight longer than stall-timeout-s (default 60, 0 disables), so a wedged instance is taken out of rotation rather than handed more traffic.

    Worth noting why the obvious approach was rejected: a readiness probe that runs a query does not detect this. A generic SELECT 1 passes, because DuckDB is entirely healthy — and a probe against the wedged connection blocks forever, leaking a thread per health check. Measuring the symptom (oldest in-flight request age) costs nothing and catches any stall.

    What is still open

    The wedge itself. Recapping the evidence for whoever picks it up:

    • A -journal file appears and never goes away — a write transaction that completed neither commit nor rollback.
    • 13 descriptors held on the database, stable, so one frozen attachment rather than a leak.
    • An external process cannot read the file: database is locked.
    • Survives SIGTERM — flAPI does not clean up the orphaned transaction on the way out — but SQLite recovers it correctly on the next open (integrity_check → ok). Availability, not data loss.
    • Requests hang rather than erroring, which is why retry and the 503 mapping do not help.

    The remaining lead is that the SQLite ATTACH is database-scoped while QueryExecutor opens a connection per query, so duckdb_disconnect is not expected to end a transaction the sqlite extension holds on the attachment. Confirming that against duckdb's sqlite_scanner is the next step.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions