Skip to content

Keep writing when a server goes down

Run your app on two or more servers with the database at the same path and route writes to the machine that confirms its writer lease.

How failover works

  • Origin and replicas

    Each server calls failover with the same path. The server that holds the write lock is the origin and backs the database up, while the others keep live replicas at that path and ask for the lock about once a second.

  • Takeover

    When the origin stops, one replica becomes the origin once the old session's lease runs out, about 60 seconds by default, and your server's --session-lease changes that time. Before it takes writes, the new origin catches up to the newest version your server has.

  • Sending writes to the origin

    Your app learns its role from the origin and replica events, which also report the role at start, or from isOrigin. The health route also asks the server to confirm that this machine still holds the writer lease before it answers 200. When the Litebackup client on a server stops answering, its role is unknown and isOrigin is false until the client answers again.

  • Writes your server never received

    When an old origin returns with writes your server never received, Litebackup leaves its file exactly as it is, reports a denied event, and stops following there. Stop failover on that server, then move the file aside and start failover again, or start it with `--discard-local` to replace the file with the current database. Restoring the current database to another path leaves the file in place, so a restart refuses it again.

  • A file already at the path

    A server that joins as a replica keeps the file at that path only when it is empty, already the newest version on your server, or a copy of the version that server last synced. Any other file is refused and left untouched. To replace it with the newest version, start failover with --discard-local.

  • Which server writes

    litebackup writer NAME, or writer() in the SDK, names the machine that writes a database right now and tells you when its lease ends.

Fail over between servers

Start the same code on every server, and your load balancer follows the origin through its health route.

import express from "express";
import { Litebackup } from "@litebackup/sdk";

const litebackup = new Litebackup();

// Run this on every server, with the database at the same path.
const cluster = await litebackup.failovers.start("/var/lib/app/main.sqlite");
cluster.on("origin", () => console.log("This server takes writes"));
cluster.on("replica", () => console.log("Another server takes writes"));
cluster.on("denied", (message) => console.warn("This server stopped following:", message));

// Your load balancer sends writes only where this answers 200.
const app = express();
let writerCheck: Promise<boolean> | undefined;

async function writerReady(): Promise<boolean> {
  if (!cluster.isOrigin) return false;
  if (!writerCheck) {
    const started = performance.now();
    writerCheck = new Promise<boolean>((resolve) => {
      const timeout = setTimeout(() => resolve(false), 500);
      void cluster.writer().then(async (writer) => {
        if (!writer.active || !writer.thisMachine || writer.lapsed) return false;
        const database = await litebackup.databases.get(cluster.name);
        const elapsed = performance.now() - started;
        return database.failover && database.role === "origin" && !database.draining &&
          database.state === "synced" && elapsed < 500 &&
          (writer.leaseRemainingMillis ?? 0) > 5000 + elapsed;
      }).then(resolve, () => resolve(false)).finally(() => {
        clearTimeout(timeout);
        writerCheck = undefined;
      });
    });
  }
  const confirmed = await writerCheck;
  return confirmed && cluster.isOrigin;
}

app.get("/health/origin", async (_req, res) => {
  res.sendStatus(await writerReady() ? 200 : 503);
});
app.listen(8080);

The health route allows 500 ms to confirm the writer lease and check the local database. It requires more than five seconds of lease time after both checks. An origin that starts offline can acquire the lease before it finishes restoring its file. Requiring the local state to be synced keeps writes off that file and also pauses routed writes while ordinary changes are waiting to sync. Give the load balancer a one-second check timeout, probe every second, and remove the host on the first failure. During a partition the old origin can still commit to its local SQLite file. The probe takes it out of routed write traffic. Requests already in flight can finish locally. Background workers must make the same readiness check before starting writes.