SQLite performs synchronous work on the thread that executes a statement. A writer worker moves writes off the application's event loop, while reads continue through the reader connections. A long write can therefore occupy the writer without blocking the event loop.
Enable the worker
Set writerWorker: true or pass an options object when opening a database. The Node better-sqlite3 and node:sqlite drivers support workers. A driver without a worker entry fails with WRITER_WORKER_UNSUPPORTED. Read-only databases start no writer worker.
The complete process-orders.ts example uses explicit order IDs and an idempotent insert. It retries a definite overload once after the package's suggested delay. An uncertain timeout reaches the caller for reconciliation.
import { mkdir } from 'node:fs/promises'
import { setTimeout } from 'node:timers/promises'
import { Sirannon, SirannonError, WriteOverloadError } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
await mkdir('./data', { recursive: true })
const sirannon = new Sirannon({ driver: betterSqlite3() })
try {
const db = await sirannon.open('orders', './data/worker-orders.db', {
writerWorker: {
maxPendingWrites: 1024,
writeTimeoutMs: 30_000,
maxRestarts: 5,
},
})
await db.execute('CREATE TABLE IF NOT EXISTS orders (id TEXT PRIMARY KEY, customer TEXT NOT NULL, total INTEGER NOT NULL)')
const insertOrder = async (id: string, customer: string, total: number): Promise<void> => {
const sql = 'INSERT INTO orders (id, customer, total) VALUES (?, ?, ?) ON CONFLICT(id) DO NOTHING'
try {
await db.execute(sql, [id, customer, total])
} catch (error: unknown) {
if (error instanceof WriteOverloadError) {
await setTimeout(error.retryAfterMs)
await db.execute(sql, [id, customer, total])
return
}
if (error instanceof SirannonError && error.code === 'WRITER_WORKER_TIMEOUT') {
console.error('The outcome is uncertain; reconcile order', id)
}
throw error
}
}
await insertOrder('order-42', 'Sara Mitchell', 12950)
console.log(await db.queryOne('SELECT id, customer, total FROM orders WHERE id = ?', ['order-42']))
} finally {
await sirannon.shutdown()
}The worker preserves the signatures of execute, executeBatch, transaction, and bulkLoad. A registry-level writerWorker value supplies a default, which a database-level value overrides.
Bound the queue and set the deadline
| Option | Default | Requirement |
|---|---|---|
maxPendingWrites | 1024 | The value must be an integer of at least 1. |
writeTimeoutMs | 30000 | The value must be a non-negative integer; zero disables the deadline. |
maxRestarts | 5 | The value must be a non-negative integer. |
Invalid settings fail with INVALID_WRITER_WORKER. Choose a queue bound that the application's request rate and latency budget can tolerate.
A worker crash rejects in-flight work and starts another worker until the restart limit is exhausted. A successful request resets the fault count. After too many faults, further writes fail with WRITER_WORKER_FATAL.
When a worker crashes inside a transaction callback, SQLite rolls the transaction back. Later statements in that callback and its commit fail with WRITER_WORKER_EXIT, so the restarted worker cannot commit the callback's remaining statements outside the lost transaction.
Handle back-pressure
When the pending count reaches maxPendingWrites, a new write fails with WRITE_OVERLOADED before reaching the worker. That rejection is definite, so retrying the rejected write is safe.
WriteOverloadError.retryAfterMs supplies a delay hint. The server returns HTTP 503 and a Retry-After header for the same refusal. Bound application retries and use back-off so that an overloaded writer can recover.
What the deadline means
A deadline cannot interrupt a synchronous native SQLite call. Sirannon requests cancellation without terminating a worker that may be executing that call.
- The worker can skip work that has not started and return
WRITE_OVERLOADED. - A completion within one further deadline returns normally.
- Work unresolved after that grace period fails with
WRITER_WORKER_TIMEOUT.
For a statement deadline, the last case occurs after twice writeTimeoutMs. A deadline while opening or closing rejects without that statement grace period.
WRITER_WORKER_TIMEOUT leaves the outcome uncertain. The statement may have committed, may commit later, or may have failed. Repeating a non-idempotent increment can therefore apply it twice.
Use a stable operation ID and an idempotent statement when retries are possible. Reading a row immediately after timeout cannot prove that a timed-out write will never commit later. Reconcile against the operation's durable record before repeating a non-idempotent action.
The example's insert cannot create two orders with the same ID. If an existing ID can arrive with a different payload, compare that payload and report the conflict, because ON CONFLICT DO NOTHING does not validate it.
Keep large DDL in maintenance windows
A worker leaves the database with one writer. A long DROP TABLE, table rewrite, or index build can delay every write behind it until the queue starts refusing work.
Schedule schema work according to measured statement duration and the application's write capacity. Observe queue refusals during that work and retain the same retry limits that ordinary overload uses. The worker removes event-loop blocking; it does not make two writes execute concurrently on one SQLite writer.
What else the writer worker does
A backup uses the writer's stepped copy interface, so a database with a writer worker performs that copy inside the worker. Each completed step reports progress to the calling thread.
Copy progress resets its stall deadline. If progress stops, cancellation can finish with BACKUP_ABORTED, while an unresponsive copy reports BACKUP_STALLED. Sirannon removes the incomplete output file.
The worker records loaded extensions and loads them into a replacement connection before accepting new work. For an encrypted database, the key loader also supplies a fresh key for a worker restart.
With row metering, a late worker reply can report counters after the caller has received a timeout. A crash without a reply leaves those counters absent, so a billing collector must distinguish missing measurements from zero work.