Python's SQLite bindings spend most of each call outside SQLite: building cursors, converting rows through generic paths, and, for asyncio, hopping to a thread and back for every statement. turbosqlite removes that overhead. SQLite 3.53.1 is compiled into the extension with tuned flags, rows are built directly through the CPython API, prepared statements are cached per connection, and the asyncio API runs cheap statements on the event loop thread instead of a worker.
Highlights
- 3–5× faster than
sqlite3, about 2× faster than apsw on point reads, 1000-row scans and bulk inserts, with the same pragmas on both sides (benchmarks).
- asyncio without a thread hop per call: a read that finishes within 50 µs runs inline on the loop thread. Point reads take 0.94 µs against aiosqlite's 83 µs.
- RAM-first mode: the database lives in memory, a commit returns in under 1 µs, and
await db.durable() resolves once a background thread has written the commit to disk. Commits that arrive together share one sync.
- Crash-tested recovery: the page log is checksummed, a torn tail is cut off, and a test kills the process with SIGKILL during log writes and checkpoints, then checks that every commit acknowledged by
durable() is still there.
close() waits for the disk: it commits a transaction left open and returns only after every commit is on disk, in both modes. with and async with blocks roll back instead when they exit on an exception.
- Cancellation interrupts the statement: cancelling the awaiting task stops SQLite within a thousand VM instructions; the worker does not keep running the query.
- SQLite compiled in: same version everywhere, FTS5 and math functions enabled, no dependency on the system library.
- Vector search built in: sqlite-vector is compiled into every connection. With
vector_preload() a top-10 search over 100k 384-dim vectors takes 1.43 ms, against 21.7 ms for the same extension loaded into sqlite3 (vector search).
Install
pip install turbosqlite # import turbosqlite
Wheels cover CPython 3.12–3.14 on Linux (glibc and musl, x86_64 and aarch64) and macOS (arm64 and x86_64). Windows is not supported. To build from source you need uv and a Rust toolchain:
git clone https://github.com/4thel00z/turbosqlite && cd turbosqlite
make sync # venv plus dev tools
make develop # build the extension into the venv
Usage
import turbosqlite
with turbosqlite.connect("app.db") as db:
db.execute("create table if not exists users(id integer primary key, name text)")
db.run("insert into users(name) values (?)", ("ada",)) # 1, the changed-row count
db.many("insert into users(name) values (?)", [("grace",), ("linus",)])
by_id = db.prepare("select id, name from users where id = ?")
by_id.one((1,)) # (1, 'ada'), or None when there is no row
by_id.value((1,)) # 1, the first column only
db.all("select * from users where name like :p", {"p": "a%"}) # [(1, 'ada')]
Every query method takes the SQL and optional parameters, a sequence for ? or a mapping for :name, and returns plain Python values:
| Method |
Returns |
one(sql, params) |
the first row as a tuple, or None |
value(sql, params) |
the first column of the first row, or None |
all(sql, params) |
every row, as a list of tuples |
run(sql, params) |
the number of changed rows |
many(sql, rows) |
runs once per parameter set, returns the total changed rows |
execute(script) |
runs one or more statements without parameters |
prepare(sql) |
a Statement with the same methods, minus the SQL argument |
durable() |
waits until every commit so far is on disk |
close() |
commits an open transaction, then closes once every commit is on disk |
Methods that take SQL text reuse a cached prepared statement, so db.one(sql, ...) in a loop costs about the same as a Statement. Connections also expose last_rowid, total_changes and in_transaction. Errors are SqliteError and its subclasses IntegrityError, BusyError and InterruptedError.
connect(path, *, exclusive=True, timeout=5.0, ram=False, commit_on_close=True) opens file databases in WAL mode with synchronous=normal, exclusive locking, a large page cache and memory-mapped reads. Pass exclusive=False to share the file with other processes; a locked database is retried for timeout seconds before BusyError.
asyncio
async with turbosqlite.connect_async("app.db") as db:
row = await db.one("select * from users where id = ?", (1,))
rows = await asyncio.gather(*(db.one("select name from users where id = ?", (i,)) for i in range(100)))
AsyncConnection has the same methods as Connection; each returns an awaitable future.
- A read-only statement runs on the event loop thread when the connection is idle and finishes within 50 µs. A statement that exceeds the budget is stopped, moved to the worker, and stays there.
- Writes to a file database and slower statements run on the connection's own worker thread, in submission order.
- Finished results wake the loop through one pipe write per batch of completions, not one per future.
- Cancelling the awaiting task interrupts the running statement.
connect_async(path, *, exclusive=True, timeout=5.0, inline=True, ram=False, commit_on_close=True); inline=False sends every statement to the worker.
RAM-first mode
async with turbosqlite.connect_async("app.db", ram=True) as db:
await db.run("insert into users(name) values (?)", ("ada",)) # returns once in RAM
await db.durable() # returns once on disk
The database file is loaded into memory. A commit returns as soon as it is in RAM. A background thread appends the pages each commit wrote to app.db-ramlog, batching commits that arrive within 10 ms into one write and one sync. durable() waits until every commit made so far is on disk; calling it once after many commits makes them durable for the cost of a single sync. In asyncio, autocommit writes also run inline on the loop thread, because a commit no longer waits for the disk.
Opening the database replays the log. Closing it, or letting the log pass 64 MiB, writes the log back into app.db, which stays an ordinary SQLite database that any other tool can open.
How the log stays safe:
- Every record carries a CRC-32 and a sequence number. Replay stops at the first torn or out-of-order record and cuts the log back to the last valid one.
- The log header records the database file's length and a checksum of its first 100 bytes. If the file was changed by something else since the log was written, opening it fails instead of replaying the log over newer data.
- A checkpoint appends and syncs a marker before it writes the database file, so recovery can finish a checkpoint that was interrupted.
- An
flock on the log keeps a second process from opening the same database in RAM-first mode.
Limits:
- The whole database lives in RAM. While it grows, the copy can briefly take twice its size.
- One process owns the database while it is open. The
exclusive option has no effect.
- Commits not yet covered by
durable() can be lost in a crash: up to 10 ms of them, plus the time a sync takes.
- Every commit logs whole 4 KiB pages, even for a one-row change.
- Nothing slows commits down when they outpace the disk.
- Recovery and checkpoints read the whole log into memory.
Durability and closing
durable() uses F_FULLFSYNC on macOS, which flushes the drive's own cache, and fdatasync elsewhere. On a database that is not RAM-first it runs a WAL checkpoint synced the same way.
close() commits a transaction left open, then returns once every commit is on disk, as if durable() ran first. With commit_on_close=False it rolls that transaction back instead. If the commit fails, for example on a deferred foreign key, close() raises (IntegrityError), rolls back, and closes the connection anyway. The async close also waits for writes still queued on the worker.
with connect(...) as db: and async with connect_async(...) as db: close on exit. Leaving the block normally commits an open transaction according to commit_on_close; leaving it because of an exception always rolls it back, as sqlite3's context manager does. A connection that is garbage collected without close() behaves like close(), but any error is lost.
Vector search
Every connection has the functions of sqlite-vector 1.2.0 (API); there is no extension to load. Vectors are BLOBs in an ordinary column.
db = turbosqlite.connect("app.db")
db.execute("create table docs(id integer primary key, embedding blob)")
db.run("insert into docs(embedding) values (vector_as_f32(?))", ("[0.1, 0.2, 0.3]",))
db.execute("select vector_init('docs', 'embedding', 'type=FLOAT32,dimension=3,distance=COSINE')")
nearest = db.prepare("select rowid, distance from vector_full_scan('docs', 'embedding', ?, 10)")
nearest.all((query_blob,))
turbosqlite adds two functions:
vector_preload(table, column) keeps a copy of the column in memory, in the column's own type, and vector_full_scan with a k argument reads it instead of the table. The first scan after any write rebuilds the copy (15 ms at 100k × 384, more than a table scan because SQLite copies each blob out of its page before the copy is made). Inside an open transaction with uncommitted writes, scans read the table, so rows that are later rolled back never enter the copy. The copy uses as much RAM as the column.
vector_preload_cleanup(table, column) drops it.
Scans over preloaded data, from vector_preload() or vector_quantize_preload(), are split across threads once there is more than 1 MB of vectors. TURBOSQLITE_VECTOR_THREADS caps the thread count; the default is the number of cores, at most 16. A scan reads about 150 MB per query at 100k × 384 float32, so it is limited by memory bandwidth from about 4 threads on.
With connect_async, statements that call vector_full_scan, vector_quantize* or vector_preload* always run on the worker thread: these scans run as C loops that SQLite's progress handler cannot interrupt, so they would overrun the inline budget, and cancelling one takes effect only once its scan finishes.
100,000 vectors of 384 float32, top 10, ms per query (benchmarks/bench_vector.py; the sqlite3 row loads the upstream extension built with its own Makefile):
| setup |
table scan |
preloaded scan |
quantized scan, default settings |
| sqlite3 3.47.1 + sqlite-vector |
21.7 |
|
1.36 |
| turbosqlite, 1 thread |
11.6 |
2.54 |
1.36 |
| turbosqlite, 4 threads |
11.7 |
1.38 |
0.41 |
| turbosqlite, default (12 threads on this machine) |
11.7 |
1.43 |
0.40 |
A table scan is mostly SQLite stepping through rows and copying each 1.5 KB blob out of its page; the distance arithmetic is about 1.3 ms of it. The quantized scan is approximate, so its results can differ from the exact ones.
FLOAT16 columns are converted to float32 eight or sixteen values per instruction (F16C or AVX-512 on x86, FCVTL on AArch64) instead of one value at a time as upstream does, and summed in float32. Vectors containing a NaN or an infinity fall back to upstream's code, which defines their distances. At 10,000 × 1024 FLOAT16 with cosine distance, a preloaded scan takes 1.33 ms on 1 thread (upstream: 4.07 ms) and 0.30 ms with threads, against 0.34 ms for the same data as FLOAT32.
Benchmarks
Apple M3 Pro, macOS 27.2, CPython 3.12. Each number is the best of several runs, in µs per operation; lower is better. Every comparison uses the same pragmas on both sides unless a row says otherwise. Reproduce with make bench.
Sync, file database in WAL mode (benchmarks/bench.py)
| library |
point read |
scan 1000 rows |
insert, per row |
| sqlite3, stock settings |
4.19 |
390.1 |
0.646 |
| sqlite3, matched |
1.98 |
381.7 |
0.661 |
| apsw, matched |
1.06 |
185.1 |
0.341 |
| turbosqlite |
0.59 |
84.8 |
0.163 |
asyncio, file database in WAL mode (benchmarks/bench_async.py)
| library |
point read |
1000 gathered reads, per read |
scan 1000 rows |
insert + commit |
| aiosqlite |
83.04 |
49.00 |
437.2 |
63.95 |
| turbosqlite |
0.94 |
1.21 |
117.3 |
27.99 |
Commits (benchmarks/bench_ram.py)
| setup |
sync commit |
asyncio commit |
sqlite3, synchronous=off, journal in memory |
4.11 |
|
apsw, synchronous=off, journal in memory |
3.26 |
|
aiosqlite, synchronous=off, journal in memory |
|
31.41 |
turbosqlite ram=True |
0.92 |
1.27 |
Commits on disk, flushed with F_FULLFSYNC
| setup |
µs per commit |
sqlite3, synchronous=full, each commit synced |
2168 |
turbosqlite ram=True, durable() after each commit |
2807 |
turbosqlite ram=True, 10,000 commits then one durable() |
2.06 |
A commit that must be on disk before the next one starts is bound by the drive's flush, and turbosqlite is no faster there. The gain comes from many commits sharing one sync.
How it works