SQLite does its work synchronously on the thread that executes a statement. A writer worker moves the writes off the application's event loop, while Sirannon goes on serving reads through the reader connections. SQLite can therefore spend a long time on one write without blocking the event loop.
Enable the worker
Set writerWorker: true, or pass an options object, when you open a database. The Node better-sqlite3 and node:sqlite drivers support workers. On a driver without a worker entry, Sirannon fails the open with WRITER_WORKER_UNSUPPORTED. Sirannon starts no writer worker for a read-only database.
The complete process-orders.ts program below gives each order an explicit ID and inserts it with an idempotent statement. When Sirannon refuses the write as overloaded, the program waits for the delay in the error's retryAfterMs and tries once more. It passes a timeout, whose outcome is uncertain, back to the caller to reconcile.
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', 'customer-1', 12950)
console.log(await db.queryOne('SELECT id, customer, total FROM orders WHERE id = ?', ['order-42']))
} finally {
await sirannon.shutdown()
}With a worker, execute, executeBatch, transaction, and bulkLoad take the same arguments and return the same results. Sirannon applies a writerWorker value on the registry to every database whose options leave writerWorker out.
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, and zero turns the deadline off. |
maxRestarts | 5 | The value must be a non-negative integer. |
Sirannon refuses an invalid setting with INVALID_WRITER_WORKER. Choose a queue bound that suits the request rate and the latency budget of your application.
When a worker crashes, Sirannon rejects the work in flight and starts another worker. Sirannon resets the fault count after each successful request. Once the faults exceed maxRestarts, Sirannon fails every later write with WRITER_WORKER_FATAL.
When a worker crashes inside a transaction callback, SQLite rolls the transaction back. Sirannon fails the later statements in that callback and its commit with WRITER_WORKER_EXIT, so that the restarted worker commits none of the callback's later statements outside the lost transaction.
Handle back-pressure
Once maxPendingWrites writes are pending, Sirannon refuses a new write with WRITE_OVERLOADED before the worker receives it, so you can retry that write safely.
WriteOverloadError.retryAfterMs contains a suggested delay in milliseconds. The server returns HTTP 503 and a Retry-After header for the same refusal. Limit the retries in your application and back off between them, so that the worker can work through its queue.
What the deadline means
At the writeTimeoutMs deadline, Sirannon interrupts no statement, so it asks the worker to cancel the work without terminating a worker that can be in the middle of a SQLite call.
- The worker can skip work that has not started and return
WRITE_OVERLOADED. - Sirannon returns the normal result of work that completes within one further deadline.
- Sirannon fails work that is in progress at the end of that grace period with
WRITER_WORKER_TIMEOUT.
For a statement, that last case comes after twice writeTimeoutMs. During an open or a close, Sirannon fails the call at the deadline, without that grace period.
After WRITER_WORKER_TIMEOUT, the outcome of the write is unknown, because SQLite can commit the statement before the timeout, commit it after the timeout, or fail it. If you retry a non-idempotent increment, SQLite can therefore apply it twice.
When you can retry a write, give it a stable operation ID and an idempotent statement. A read straight after a timeout returns only the rows at that moment, because SQLite can commit the timed-out write later. Check the operation's durable record before you repeat a non-idempotent action.
SQLite creates at most one order for each ID through the insert in the example. When your application can receive an existing ID with a different payload, compare that payload and report the conflict, because with ON CONFLICT DO NOTHING, SQLite discards the new payload without comparing it.
To stop a statement inside the worker, set executionTimeoutMs on the call, on a database that you open through betterSqlite3({ executionTimeouts: true }). Sirannon applies that limit to each statement that the worker executes for the call, so SQLite stops the statement once the limit passes. Sirannon then fails the call with EXECUTION_TIMEOUT, which is a definite outcome, because SQLite rolls back every write of the call.
Keep large DDL in maintenance windows
Each database has one writer with or without a worker, so while SQLite executes a long DROP TABLE, table rewrite, or index build, every write behind it waits, until Sirannon starts to refuse writes as overloaded.
Schedule schema work by the measured duration of its statements and the write capacity of your application. Watch for queue refusals during that work, and apply the same retry limits that you use for ordinary overload. The worker frees the event loop, although SQLite executes one write at a time on the writer.
What else the writer worker does
Sirannon takes a backup through the writer's stepped copy interface, so on a database with a writer worker, Sirannon copies inside the worker. After each completed step, the worker reports progress to the calling thread.
After each step of progress, Sirannon resets the stall deadline of the copy, which is stallTimeoutMs. When the worker copies no page before that deadline, Sirannon fails the copy with BACKUP_STALLED and removes the incomplete output file once the copy stops.
The worker records the loaded extensions and loads them into a replacement connection before it accepts new work. Sirannon calls the key loader of an encrypted database again when it restarts the worker.
With row metering, the worker can report counters in a late reply after the caller receives a timeout. When the worker crashes before it replies, the counters are absent, so treat a missing measurement in your billing collector as different from zero work.