Quick start
1. Install the package
npm install @litebackup/sdk
It needs Node.js 22 or later and brings the litebackup binary for Linux and macOS, so there is nothing else to install. For Go, see the Go section below.
2. Give your app a join token
Create one under Machines, Add machine in your console and set it as LITEBACKUP_TOKEN where your app runs. The first time your app starts, Litebackup joins your server with it.
LITEBACKUP_TOKEN=TOKEN@your-instance.litebackup.cloud node server.js
3. Back up your database
import { backup } from "@litebackup/sdk";
backup("/var/lib/app/main.sqlite");
That is all. backup() returns at once, and every change reaches your server within seconds from then on.
Add it to your existing app
Your app already opens its database somewhere. Hand that handle to backup() right after, and change nothing else: your queries, migrations, and driver stay as they are.
// db.ts, wherever your app opens SQLite
import Database from "better-sqlite3";
import { backup } from "@litebackup/sdk";
export const db = new Database("/var/lib/app/main.sqlite");
backup(db); // the one new line
With any other driver, pass the path instead: backup("/var/lib/app/main.sqlite"). better-sqlite3 is not a dependency of the SDK. In Go, add the call after sql.Open:
db, err := sql.Open("sqlite3", "/var/lib/app/main.sqlite")
if err != nil {
return err
}
if _, err := litebackup.Backup(ctx, "/var/lib/app/main.sqlite", litebackup.BackupOptions{}); err != nil {
return err
}
Here is the same in a complete Express app:
// LITEBACKUP_TOKEN=TOKEN@your-instance.litebackup.cloud node server.js
import express from "express";
import Database from "better-sqlite3";
import { backup } from "@litebackup/sdk";
const db = new Database("/var/lib/app/main.sqlite");
db.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)");
backup(db); // backed up as main.sqlite
const app = express();
app.use(express.json());
app.get("/notes", (req, res) => {
res.json(db.prepare("SELECT id, body FROM notes ORDER BY id").all());
});
app.post("/notes", (req, res) => {
const { lastInsertRowid } = db.prepare("INSERT INTO notes (body) VALUES (?)").run(req.body.body);
res.status(201).json({ id: Number(lastInsertRowid) });
});
app.listen(3000);
Back up
Name your databases
A database's name is its file name in lowercase, with every other character turned into -. Choose your own with name or prefix:
backup("/var/lib/app/My App.sqlite"); // my-app.sqlite
backup("/var/lib/app/orders.sqlite", { prefix: "shop/" }); // shop/orders.sqlite
backup("/var/lib/app/users.sqlite", { name: "shop/accounts.sqlite" }); // shop/accounts.sqlite
Wait until a change is safe
const orders = backup("/var/lib/app/orders.sqlite");
await orders.wait("server"); // on your Litebackup server
await orders.wait("cloud"); // in your bucket
await orders.stop(); // stops backing up; the backups stay
To wait before backup() returns, pass { wait: "server" } and await it.
One writer per database
Litebackup never lets two machines write the same database. If another machine already backs up that name, backup() fails and changes nothing:
main.db is already backed up from web-2; pass a prefix or a name, or use failover()
Read on other machines
A replica is a readonly copy that stays within seconds of the database. replicate() resolves once the first version is on this machine.
import Database from "better-sqlite3";
import { replicate } from "@litebackup/sdk";
await replicate("main.sqlite", { to: "/var/lib/app/main.sqlite" });
const db = new Database("/var/lib/app/main.sqlite", { readonly: true });
console.log(db.prepare("SELECT count(*) AS notes FROM notes").get());
Keep writing when a server goes down
Run the same app on several identical servers and call failover() on each. One becomes the origin and takes writes; the others become replicas with a live readonly copy at the same path. When the origin goes down, a replica takes over by itself. The high availability guide covers the setup.
// LITEBACKUP_TOKEN=TOKEN@your-instance.litebackup.cloud node server.js
import express from "express";
import Database from "better-sqlite3";
import { failover } from "@litebackup/sdk";
const path = "/var/lib/app/main.sqlite";
const cluster = await failover(path); // a replica takes over about 60 s after the origin stops
const db = new Database(path);
cluster.on("origin", () => console.log("This server now takes writes"));
cluster.on("replica", () => console.log("Another server takes writes"));
cluster.on("conflictSaved", (path) => console.warn("Unsynced writes were saved as a conflict copy", path));
const app = express();
app.use(express.json());
// Your load balancer sends writes only to the server that answers 200 here.
app.get("/healthz/origin", (req, res) => {
res.sendStatus(cluster.isOrigin ? 200 : 503);
});
app.get("/notes", (req, res) => {
res.json(db.prepare("SELECT id, body FROM notes ORDER BY id").all());
});
app.post("/notes", (req, res) => {
if (!cluster.isOrigin) {
res.status(503).json({ error: "This server is a replica" });
return;
}
const { lastInsertRowid } = db.prepare("INSERT INTO notes (body) VALUES (?)").run(req.body.body);
res.status(201).json({ id: Number(lastInsertRowid) });
});
app.listen(3000);
cluster.role is "origin" or "replica", and cluster.stop() leaves the group. The new origin takes writes on the same file the moment it is promoted, so there is no gap for your app. If the old origin comes back, any writes that never reached your server are saved as a conflict copy, never deleted, and it becomes a replica.
When a replica takes over
A replica takes over about 60 seconds after the origin stops, and your server's --session-lease sets that time. writer() returns the machine that writes the database and whether it is still active:
console.log(await cluster.writer());
Share databases across a worker pool
When any worker may pick up any database, such as one per customer, acquire it where the job runs and release it when the job is done. Only one machine holds a database at a time, and the next worker gets the latest version. Acquire refuses a name that has no version anywhere, so a mistyped name never becomes a database. The first time, create an empty file and acquire it, as below.
import Database from "better-sqlite3";
import { LitebackupError, acquire, release } from "@litebackup/sdk";
export async function recordVisit(customerId: string) {
const name = `customers/${customerId}.sqlite`;
const path = `/var/lib/app/customer-${customerId}.sqlite`;
try {
await acquire(name, { to: path });
} catch (error) {
if (!(error instanceof LitebackupError && error.code === "not_found")) throw error;
// A new customer: open and close a new database here, and acquire creates it.
new Database(path).close();
await acquire(name, { to: path });
}
const db = new Database(path);
try {
db.exec("CREATE TABLE IF NOT EXISTS visits (at INTEGER NOT NULL)");
db.prepare("INSERT INTO visits (at) VALUES (?)").run(Date.now());
} finally {
db.close();
await release(name, { wait: "server" });
}
}
Restore a version
List the versions your server keeps, then restore one into a new file on any machine that joined. A restore never overwrites a file, and the directory must already exist.
import { restore, versions } from "@litebackup/sdk";
console.table(await versions("main.sqlite"));
await restore("main.sqlite", {
to: "/tmp/main-0930.sqlite",
time: new Date("2026-11-15T09:30:00Z"),
});
Pass version instead of time to restore one exact version.
Go
go get github.com/litebackup/sdk/litebackup
The Go SDK runs the litebackup command, so install it on the machine first. It looks for LITEBACKUP_PATH, then litebackup on your PATH. Every call takes a context, and the calls match the TypeScript ones above.
Back up
package main
import (
"context"
"database/sql"
"log"
"net/http"
"github.com/litebackup/sdk/litebackup"
_ "github.com/mattn/go-sqlite3"
)
// Run with LITEBACKUP_TOKEN=TOKEN@your-instance.litebackup.cloud
func main() {
ctx := context.Background()
path := "/var/lib/app/main.sqlite"
db, err := sql.Open("sqlite3", path)
if err != nil {
log.Fatal(err)
}
if _, err := db.Exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, body TEXT NOT NULL)"); err != nil {
log.Fatal(err)
}
if _, err := litebackup.Backup(ctx, path, litebackup.BackupOptions{}); err != nil { // backed up as main.sqlite
log.Fatal(err)
}
http.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) {
if _, err := db.ExecContext(r.Context(), "INSERT INTO notes (body) VALUES (?)", r.FormValue("body")); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
})
log.Fatal(http.ListenAndServe(":3000", nil))
}
Fail over
Each server calls litebackup.Failover, and the health check answers 200 only on the origin:
package main
import (
"context"
"database/sql"
"log"
"net/http"
"github.com/litebackup/sdk/litebackup"
_ "github.com/mattn/go-sqlite3"
)
func main() {
ctx := context.Background()
path := "/var/lib/app/main.sqlite"
cluster, err := litebackup.Failover(ctx, path, litebackup.FailoverOptions{})
if err != nil {
log.Fatal(err)
}
db, err := sql.Open("sqlite3", path)
if err != nil {
log.Fatal(err)
}
http.HandleFunc("GET /healthz/origin", func(w http.ResponseWriter, r *http.Request) {
if !cluster.IsOrigin() {
http.Error(w, "replica", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})
http.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) {
if !cluster.IsOrigin() {
http.Error(w, "this server is a replica", http.StatusServiceUnavailable)
return
}
if _, err := db.ExecContext(r.Context(), "INSERT INTO notes (body) VALUES (?)", r.FormValue("body")); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
})
log.Fatal(http.ListenAndServe(":3000", nil))
}
Replicas, worker pools, and restores
Inside a function that has a ctx and imports log and time:
if _, err := litebackup.Replicate(ctx, "main.sqlite", litebackup.ReplicateOptions{To: "/var/lib/app/main.sqlite"}); err != nil {
return err
}
client, err := litebackup.Default(ctx) // the client the package functions share
if err != nil {
return err
}
name := "customers/42.sqlite"
if _, err := client.Acquire(ctx, name, litebackup.AcquireOptions{To: "/var/lib/app/customer-42.sqlite"}); err != nil {
return err
}
// Write with any SQLite driver, then close the database.
if _, err := client.Release(ctx, name, litebackup.ReleaseOptions{Wait: litebackup.DurabilityServer}); err != nil {
return err
}
list, err := litebackup.Versions(ctx, "main.sqlite", litebackup.VersionsOptions{})
if err != nil {
return err
}
for _, version := range list {
log.Printf("%+v", version)
}
at := time.Date(2026, time.November, 15, 9, 30, 0, 0, time.UTC)
if _, err := litebackup.Restore(ctx, "main.sqlite", litebackup.RestoreOptions{To: "/tmp/main-0930.sqlite", Time: at}); err != nil {
return err
}
To use another token, litebackup.Connect(ctx, litebackup.Options{Token: os.Getenv("REPORTS_LITEBACKUP_TOKEN")}) returns a client with the same calls.
Reference
More than one server or token
The functions above use LITEBACKUP_TOKEN. Litebackup.connect() returns a client with every call, and its token option overrides the variable.
import { Litebackup } from "@litebackup/sdk";
const litebackup = await Litebackup.connect({ token: process.env.REPORTS_LITEBACKUP_TOKEN });
const reports = litebackup.backup("/var/lib/app/reports.sqlite");
await reports.wait("cloud");
console.log(await litebackup.writer("reports.sqlite"));
Roles and states
Each database on a machine has a role, origin or replica, and one of these states:
syncing: changes are on their way to your server.synced: your server has every change.waiting: another machine is the origin.offloaded: the local copy was removed because your bucket holds it.stopped: Litebackup no longer follows this file.conflicted: a conflict copy was saved and needs a look.error: something needs your attention; the error says what.
With the service
When litebackup install service runs Litebackup on the machine, the SDK talks to the service instead of starting its own, as long as your app runs as root or as the service's user.
The full reference is in the SDK's README on npm and on GitHub.