Menu

Tutorials

SQLite WAL Mode and node:sqlite in Node.js: High-Concurrency Tutorial

Table of contents (7 sections)

SQLite is often misunderstood as a toy database suitable only for local prototypes. In reality, when configured with Write-Ahead Logging (WAL) and sensible concurrency pragmas, SQLite comfortably powers single-server web APIs, background job queues, analytics collectors, and SaaS dashboards with predictable sub-millisecond reads.

Modern Node.js versions remove one of the biggest friction points of using SQLite in JavaScript and TypeScript: native C++ addon compilation headaches. As documented in the Node.js SQLite module documentation, the built-in node:sqlite module provides DatabaseSync, prepared statements, and aggregate helpers directly inside the runtime without external native packages.

In this tutorial, you will learn how SQLite WAL mode improves concurrency, how to initialize node:sqlite cleanly in TypeScript, which pragmas protect you from SQLITE_BUSY errors, and how to run safe online backups. If you are still deciding between embedded and client-server databases for your stack, check our comparison on PostgreSQL vs SQLite vs MySQL: Which Database for Your Web App?.

How Write-Ahead Logging Changes SQLite Read and Write Concurrency

By default, SQLite uses a rollback journal (DELETE mode). When a connection begins writing, it copies original database pages into a separate rollback journal before modifying the main database file. While a write transaction holds its lock, readers are blocked from accessing consistent snapshots, and vice versa.

Enabling Write-Ahead Logging inverts that flow. As explained in the official SQLite Write-Ahead Logging documentation, changes are appended sequentially to a separate -wal file rather than overwriting pages in the main database immediately. Readers examine the database file plus any committed frames in the WAL up to their transaction mark, while a single writer appends new frames concurrently.

BehaviorDefault Rollback JournalWAL Mode (PRAGMA journal_mode = WAL)
Readers during an active writeBlocked until writer commitsProceed concurrently without blocking the writer
Writers during active readsMust wait for readers to finishAppend to WAL file concurrently (one writer at a time)
Write disk I/O patternRandom seeks across main DB and journalSequential appends to the -wal file
Persistence across connectionsDefault mode on new DBPersists in the database header across restarts

One important architectural constraint remains: WAL allows many concurrent readers alongside one active writer, not multiple simultaneous writers. That single-writer model is plenty for most single-node apps when write transactions stay short and fast, because appending sequential pages takes microseconds rather than milliseconds.

Getting Started with Node.js Built-In node:sqlite DatabaseSync

With Node.js’s built-in node:sqlite module, you can open a database synchronously using DatabaseSync without installing better-sqlite3 or debugging node-gyp build toolchains in Docker containers. Synchronous execution inside a single-threaded Node.js event loop actually works in SQLite’s favor: statements complete in microseconds without async promise queue overhead or interleaved transaction state.

Developer writing local-first TypeScript and SQLite code on a laptop
Local-first TypeScript and SQLite development with synchronous prepared statements. Image: Thomas Lefebvre (CC0), via Wikimedia Commons.

Let us create a clean database bootstrap module in TypeScript that opens the SQLite file, configures production pragmas, and creates a STRICT table schema.

typescriptimport { DatabaseSync } from "node:sqlite";
 
export function openDatabase(dbPath: string): DatabaseSync {
  const db = new DatabaseSync(dbPath);
 
  // Enable WAL mode (persists in DB header) and safe durability settings
  db.exec("PRAGMA journal_mode = WAL;");
  db.exec("PRAGMA synchronous = NORMAL;");
  db.exec("PRAGMA busy_timeout = 5000;");
  db.exec("PRAGMA foreign_keys = ON;");
  db.exec("PRAGMA temp_store = MEMORY;");
  db.exec("PRAGMA cache_size = -64000;");
 
  db.exec(`
    CREATE TABLE IF NOT EXISTS api_keys (
      id INTEGER PRIMARY KEY,
      key_hash TEXT NOT NULL UNIQUE,
      owner_id TEXT NOT NULL,
      rate_limit INTEGER NOT NULL DEFAULT 1000,
      created_at INTEGER NOT NULL DEFAULT (unixepoch())
    ) STRICT;
 
    CREATE INDEX IF NOT EXISTS idx_api_keys_owner
      ON api_keys (owner_id);
  `);
 
  return db;
}

Essential Pragmas: WAL, synchronous NORMAL, busy_timeout, and STRICT Tables

Each pragma in the initialization block solves a specific production failure mode. Skipping even one of them is the most common reason developers see random lock errors or sluggish writes under load.

  • PRAGMA journal_mode = WAL switches the database into Write-Ahead Logging mode. Because this setting is stored in the database file header, it persists across restarts, though keeping it at startup is idempotent and guarantees newly created databases start in WAL.
  • PRAGMA synchronous = NORMAL avoids calling fsync() on every single commit in WAL mode, syncing only at checkpoint boundaries. In WAL mode, NORMAL remains crash-safe against application crashes and power loss for committed transactions once checkpointed, while dramatically increasing write throughput.
  • PRAGMA busy_timeout = 5000 tells SQLite to wait up to 5,000 milliseconds with backoff if another connection or worker thread briefly holds the write lock, instead of immediately throwing SQLITE_BUSY.
  • PRAGMA foreign_keys = ON is per-connection in SQLite and defaults to off. Always set it explicitly on every connection you open.
  • PRAGMA cache_size = -64000 allocates roughly 64 MB of page cache in memory (negative values specify kilobytes), reducing filesystem reads on hot indexes.
  • STRICT tables enforce exact column data types (INTEGER, TEXT, REAL, BLOB, ANY) at insert and update time, preventing SQLite’s historical type affinity surprises.

Writing Prepared Statements and Atomic Transactions in TypeScript

Never interpolate user input into SQL strings. Always compile parameterized queries with db.prepare() and reuse those statement objects when queries run repeatedly in hot request paths. Parameter binding protects against SQL injection and skips repeated query planning overhead.

When an operation performs multiple writes that must succeed or fail together, wrap them inside an explicit BEGIN IMMEDIATE transaction. Using BEGIN IMMEDIATE acquires the write lock up front rather than starting as a read transaction and upgrading mid-way, which prevents deadlocks between two concurrent writers that both try to upgrade.

typescriptimport type { DatabaseSync, StatementSync } from "node:sqlite";
 
interface ApiKeyRecord {
  id: number;
  owner_id: string;
  rate_limit: number;
  created_at: number;
}
 
export class ApiKeyStore {
  private insertStmt: StatementSync;
  private findByHashStmt: StatementSync;
  private updateLimitStmt: StatementSync;
 
  constructor(private readonly db: DatabaseSync) {
    this.insertStmt = db.prepare(
      "INSERT INTO api_keys (key_hash, owner_id, rate_limit) VALUES (?, ?, ?) RETURNING id, owner_id, rate_limit, created_at"
    );
    this.findByHashStmt = db.prepare(
      "SELECT id, owner_id, rate_limit, created_at FROM api_keys WHERE key_hash = ?"
    );
    this.updateLimitStmt = db.prepare(
      "UPDATE api_keys SET rate_limit = ? WHERE owner_id = ?"
    );
  }
 
  findByHash(keyHash: string): ApiKeyRecord | undefined {
    return this.findByHashStmt.get(keyHash) as ApiKeyRecord | undefined;
  }
 
  rotateAndSetLimit(keyHash: string, ownerId: string, limit: number): ApiKeyRecord {
    this.db.exec("BEGIN IMMEDIATE");
    try {
      this.updateLimitStmt.run(limit, ownerId);
      const created = this.insertStmt.get(keyHash, ownerId, limit) as ApiKeyRecord;
      this.db.exec("COMMIT");
      return created;
    } catch (err) {
      this.db.exec("ROLLBACK");
      throw err;
    }
  }
}

Notice how clean the error path is: if either statement throws a constraint violation or runtime error, the catch block rolls back the transaction cleanly before rethrowing, leaving the database consistent and releasing the write lock immediately.

Checkpointing, Backups, and Avoiding SQLITE_BUSY Errors

As writes accumulate in the -wal file, SQLite must eventually transfer those committed frames back into the main database file through a process called checkpointing. By default, SQLite performs an automatic passive checkpoint whenever the WAL reaches 1,000 pages, as noted in the SQLite WAL specification.

Managing WAL Growth Under Heavy Read Traffic

A long-running read transaction pins an older snapshot of the database and prevents SQLite from resetting the WAL file back to the beginning. If a dashboard query or reporting export holds a read transaction open for minutes while your API writes continuously, the -wal file can grow to hundreds of megabytes.

  • Keep read transactions short and never hold a transaction open while waiting on an external HTTP call or LLM request.
  • Monitor -wal file size in production and trigger PRAGMA wal_checkpoint(TRUNCATE); during low-traffic maintenance windows if needed.
  • Keep all writers inside a single Node.js process (or serialize writes through a queue) to avoid cross-process lock contention.

Taking Safe Online Backups Without Stopping Your App

Never back up a live WAL-mode SQLite database by running a plain cp app.db app.db.bak. Copying the main file without coordinating with the -wal and -shm files produces a torn, corrupted backup. Instead, use SQLite’s online backup API via VACUUM INTO or the sqlite3 .backup command.

bash# Create a consistent, defragmented snapshot while the Node.js app is live
sqlite3 /var/lib/myapp/app.db "VACUUM INTO '/var/backups/myapp-2026-11-27.db';"
 
# Verify integrity of the backup file before uploading to object storage
sqlite3 /var/backups/myapp-2026-11-27.db "PRAGMA integrity_check;"

For an automated script pattern that pairs SQLite snapshots with S3 object storage uploads and retention pruning, see our guide on PocketBase Backup and Restore: Built-in, S3 and sqlite3 Scripts. With WAL mode, strict schemas, short BEGIN IMMEDIATE transactions, and safe VACUUM INTO backups, node:sqlite gives you a zero-dependency database layer that is fast, resilient, and simple to operate.

Featured image credit: Martin Vorel (CC BY-SA 4.0), via Wikimedia Commons.