Skip to content

Read the same data on other machines

A replica is a real SQLite file on another machine that follows the database within seconds, so reporting, search, and analytics can read locally.

How replicas work

  • One database or a whole prefix

    Replicate a single name to a path, or follow every database under a prefix into a directory, which also brings in databases created later. replicate returns once the first version is on disk, and newer versions keep arriving in the background.

  • Readonly join tokens

    Machines that only read can join with a readonly join token, created with litebackup admin join-token create --name reporting --mode readonly, so a reporting machine can read your databases without being able to back up over them.

  • Write protection

    By default the client holds each replica's SQLite write lock, so a stray write fails with SQLITE_BUSY while reads carry on. The detect mode undoes local writes by rebasing the replica instead, and none leaves it to your app to open the file readonly. Whichever mode you choose, open replicas readonly in your app.

  • A few seconds behind

    A replica can trail the database by a few seconds, so send writes to the machine that backs it up. When any of several servers may need to take writes, use failover, which keeps a replica on each of them and moves the writer for you.

  • Stopping a replica

    litebackup replicate stop NAME stops following one database, and litebackup replicate stop PREFIX/ DIRECTORY stops a prefix. The files stay at their last version without write protection, so you can keep them or delete them.

Keep a readonly copy on a reporting machine

Run this on a second machine that joined the same server, and open the replica readonly with any driver.

import { mkdir } from "node:fs/promises";
import Database from "better-sqlite3";
import { Litebackup } from "@litebackup/sdk";

const litebackup = new Litebackup();

await mkdir("/var/lib/app/reporting", { recursive: true });

// Returns once the first version is on this machine; newer ones follow.
await litebackup.replicas.start("main.sqlite", {
  path: "/var/lib/app/reporting/main.sqlite",
  timeout: "2m",
});
const db = new Database("/var/lib/app/reporting/main.sqlite", { readonly: true });
console.log(db.prepare("SELECT count(*) AS tables FROM sqlite_schema").get());

// Follow every database under tenants/, including ones created later.
await litebackup.replicas.startPrefix("tenants", { directory: "/var/lib/app/reporting/tenants" });
litebackup.close(); // the replicas keep updating in the litebackup client