Backups

Backups in a replication group

Select one eligible node for each backup turn and alert on skipped captures.

Every replica contains a copy of the group's data, so backups on every replica can store and copy the same data several times. Configure the backups against the group's eligible members, so that Sirannon can select another node after a failover.

Give every node the same backups options. Before each turn, Sirannon reads the membership and selects the eligible node that takes the copy. After a failover, Sirannon can select another node without any change to the configuration.

Build group-backup.ts step by step with a membership source that the example supplies, so that you can watch the selection in one process. The continuous-backup guide describes capture and checkpointing. Start each example in a separate empty working directory.

mkdir -p data

What the cycle asks the group

replicationGroup takes a backup group source. This object includes the local nodeId and a readMembership method that returns the current primary and eligible node IDs.

interface BackupGroupSource {
  readonly nodeId: string
  readMembership(): Promise<{ primaryNodeId: string | null; nodeIds: string[] }>
}

preferredNode specifies a preference among eligible nodes. Sirannon sorts their identifiers before it selects one, so that every node with the same membership selects the same identifier.

preferredNodeResolves to
'replica' (the default)Sirannon selects the lowest eligible replica identifier, falling back to an eligible primary.
'primary'Sirannon selects the primary when it is eligible, or skips capture otherwise.
{ nodeId: 'frankfurt-1' }Sirannon selects that identifier only while the membership includes it as eligible.

By default, Sirannon prefers a replica, so that the primary can serve writes while another node copies. When the primary is the only eligible node, Sirannon selects it.

Leave replicationGroup out on a single-node deployment. The local node then takes each turn.

Watch a node stand down

The example supplies a two-node membership with frankfurt-1 as primary. The local node is frankfurt-1, so with the default preference, Sirannon selects singapore-2, and the local node skips its turn.

Sirannon reports each skipped turn through onSkip, so collect those reports and inspect the latest one.

group-backup.ts
import {
  type BackupDestination,
  type BackupGroupMembership,
  type BackupGroupSource,
  type BackupPiece,
  type BackupSkip,
  Sirannon,
} from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
 
const stored = new Map<string, Uint8Array>()
const pieceKey = (name: string, index: number): string => `${name}#${index}`
 
const memory: BackupDestination = {
  async writePiece(name, index, bytes) {
    stored.set(pieceKey(name, index), Uint8Array.from(bytes))
  },
  async writePieceIfAbsent(name, index, bytes) {
    if (stored.has(pieceKey(name, index))) return false
    stored.set(pieceKey(name, index), Uint8Array.from(bytes))
    return true
  },
  async readPiece(name, index) {
    const bytes = stored.get(pieceKey(name, index))
    if (!bytes) throw new Error(`No piece ${index} of '${name}'`)
    return bytes
  },
  async listPieces(name) {
    const pieces: BackupPiece[] = []
    for (const [key, bytes] of stored) {
      if (key.startsWith(`${name}#`)) {
        pieces.push({ index: Number(key.slice(name.length + 1)), byteLength: bytes.byteLength })
      }
    }
    return pieces
  },
}
 
let membership: BackupGroupMembership = { primaryNodeId: 'frankfurt-1', nodeIds: ['frankfurt-1', 'singapore-2'] }
 
const group: BackupGroupSource = {
  nodeId: 'frankfurt-1',
  readMembership: async () => membership,
}
 
const skips: BackupSkip[] = []
 
const sirannon = new Sirannon({ driver: betterSqlite3() })
 
const db = await sirannon.open('orders', './data/orders.db', {
  backups: {
    destination: memory,
    intervalMs: 0,
    replicationGroup: group,
    preferredNode: 'replica',
    onSkip: (skip) => skips.push(skip),
    onError: (err) => console.error('Backup cycle failed:', err.message),
  },
})
 
await db.execute('CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, customer TEXT NOT NULL, total REAL NOT NULL)')
await db.execute('INSERT INTO orders (customer, total) VALUES (?, ?)', ['customer-1', 128.5])
 
const whileTheReplicaIsUp = await db.captureBackupChanges()
 
console.log(
  JSON.stringify(
    {
      whileTheReplicaIsUp: {
        wroteAnything: whileTheReplicaIsUp !== undefined,
        lastSkip: {
          reason: skips[skips.length - 1]?.reason,
          nodeId: skips[skips.length - 1]?.nodeId,
          preferredNodeId: skips[skips.length - 1]?.preferredNodeId,
        },
      },
    },
    (key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value,
    2,
  ),
)
 
await sirannon.shutdown()

captureBackupChanges returns undefined, because the node writes nothing on this turn. The skip includes both identifiers, so an operator can identify the selected node and the node that skipped.

Before it reports a preference skip, Sirannon uploads any staged capture, clears the local cycle state, and checkpoints the log. When Sirannon selects this node again, it therefore starts a new chain on the node. When that upload fails, Sirannon retains the chain, the capture, and the log for a later turn.

Watch the work move on a failover

Once singapore-2 leaves the membership, Sirannon selects the local node on the next turn.

group-backup.ts
import {
  type BackupDestination,
  type BackupGroupMembership,
  type BackupGroupSource,
  type BackupPiece,
  type BackupSkip,
  Sirannon,
} from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
 
const stored = new Map<string, Uint8Array>()
const pieceKey = (name: string, index: number): string => `${name}#${index}`
 
const memory: BackupDestination = {
  async writePiece(name, index, bytes) {
    stored.set(pieceKey(name, index), Uint8Array.from(bytes))
  },
  async writePieceIfAbsent(name, index, bytes) {
    if (stored.has(pieceKey(name, index))) return false
    stored.set(pieceKey(name, index), Uint8Array.from(bytes))
    return true
  },
  async readPiece(name, index) {
    const bytes = stored.get(pieceKey(name, index))
    if (!bytes) throw new Error(`No piece ${index} of '${name}'`)
    return bytes
  },
  async listPieces(name) {
    const pieces: BackupPiece[] = []
    for (const [key, bytes] of stored) {
      if (key.startsWith(`${name}#`)) {
        pieces.push({ index: Number(key.slice(name.length + 1)), byteLength: bytes.byteLength })
      }
    }
    return pieces
  },
}
 
let membership: BackupGroupMembership = { primaryNodeId: 'frankfurt-1', nodeIds: ['frankfurt-1', 'singapore-2'] }
 
const group: BackupGroupSource = {
  nodeId: 'frankfurt-1',
  readMembership: async () => membership,
}
 
const skips: BackupSkip[] = []
 
const sirannon = new Sirannon({ driver: betterSqlite3() })
 
const db = await sirannon.open('orders', './data/orders.db', {
  backups: {
    destination: memory,
    intervalMs: 0,
    replicationGroup: group,
    preferredNode: 'replica',
    onSkip: (skip) => skips.push(skip),
    onError: (err) => console.error('Backup cycle failed:', err.message),
  },
})
 
await db.execute('CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, customer TEXT NOT NULL, total REAL NOT NULL)')
await db.execute('INSERT INTO orders (customer, total) VALUES (?, ?)', ['customer-1', 128.5])
 
const whileTheReplicaIsUp = await db.captureBackupChanges()
 
membership = { primaryNodeId: 'frankfurt-1', nodeIds: ['frankfurt-1'] }
 
const onceTheReplicaHasGone = await db.captureBackupChanges()
 
const chains = await db.backupChain()
 
console.log(
  JSON.stringify(
    {
      whileTheReplicaIsUp: {
        wroteAnything: whileTheReplicaIsUp !== undefined,
        lastSkip: {
          reason: skips[skips.length - 1]?.reason,
          nodeId: skips[skips.length - 1]?.nodeId,
          preferredNodeId: skips[skips.length - 1]?.preferredNodeId,
        },
      },
      onceTheReplicaHasGone: {
        kind: onceTheReplicaHasGone?.kind,
        route: onceTheReplicaHasGone?.route,
        chainsAtTheDestination: chains.length,
        chainHoldsTheFullCopy: chains[0]?.base?.runId === onceTheReplicaHasGone?.runId,
        skipsSoFar: skips.length,
      },
    },
    (key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value,
    2,
  ),
)
 
await sirannon.shutdown()

After the membership changes, captureBackupChanges returns a full-copy report. Sirannon clears a node's cycle state when the node skips a turn, so Sirannon begins a new chain on the node. Sirannon cannot extend that chain with change files from another node, because SQLite can apply the frames of a log only to the database file of that log.

skipsSoFar is two, because Sirannon also skips the cycle's first turn on this node. Sirannon applies the selection to that first turn as well, so a node takes no extra full copy while an eligible replica takes the backups.

Report every skip, and alert on the log

Sirannon calls onSkip for each skipped turn with a skip whose reason identifies the condition.

reasonWhat it means
'not-preferred'Another node of the group takes these backups.
'group-unavailable'readMembership fails, so Sirannon cannot determine which node takes the turn, and this node captures and checkpoints nothing.
'previous-run-active'A scheduled turn comes due while an earlier turn is active.

A skip can include uncapturedLogBytes, the size of the write-ahead log at that turn. Monitor that size with the skip reasons, because an uncaptured log that grows can mean that no node of the group is taking backups. maxUncapturedLogBytes limits the log across turns that capture nothing.

Repeated group-unavailable skips can indicate a coordinator outage, a failed membership source, or an etcd3 package that the process cannot load. Sirannon retains the chain and the log while the membership is unavailable, so that this node can capture again when the source answers.

The destination has to claim a place

Two nodes can start separate chains during a failover and append records to the same chain list. Sirannon uses writePieceIfAbsent to claim an index atomically. When that call returns false, Sirannon tries the next index so that both records can appear in the list.

When the destination has no writePieceIfAbsent, Sirannon writes a record and checks it afterwards, so another node can replace that record between those calls. With a group source and a destination that lacks that method, Sirannon reports BACKUP_DESTINATION_ERROR through onError at startup. Add that method or configure a separate chainName for each node.

Read the membership from your cluster coordinator

A group with coordinator-backed failover records its membership in the coordinator, from which coordinatorBackupGroup reads it. That source lists the in-sync nodes, apart from any that are draining, repairing, or faulted.

Build the coordinator first, pass the group source to sirannon.open, and build the replication engine afterwards with the same nodeId. The example stores the backups in memory to show the API, while a deployment needs shared durable storage behind those methods.

coordinator-backup.ts
import { readFileSync } from 'node:fs'
import { type BackupDestination, type BackupPiece, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { coordinatorBackupGroup } from '@delali/sirannon-db/replication'
import { createEtcdCoordinator } from '@delali/sirannon-db/replication/coordinator/etcd'
 
const stored = new Map<string, Uint8Array>()
const pieceKey = (name: string, index: number): string => `${name}#${index}`
 
const destination: BackupDestination = {
  async writePiece(name, index, bytes) {
    stored.set(pieceKey(name, index), Uint8Array.from(bytes))
  },
  async writePieceIfAbsent(name, index, bytes) {
    if (stored.has(pieceKey(name, index))) return false
    stored.set(pieceKey(name, index), Uint8Array.from(bytes))
    return true
  },
  async readPiece(name, index) {
    const bytes = stored.get(pieceKey(name, index))
    if (!bytes) throw new Error(`No piece ${index} of '${name}'`)
    return bytes
  },
  async listPieces(name) {
    const pieces: BackupPiece[] = []
    for (const [key, bytes] of stored) {
      if (key.startsWith(`${name}#`)) {
        pieces.push({ index: Number(key.slice(name.length + 1)), byteLength: bytes.byteLength })
      }
    }
    return pieces
  },
}
 
const coordinator = createEtcdCoordinator({
  hosts: ['https://etcd-1.internal:2379', 'https://etcd-2.internal:2379'],
  keyPrefix: '/sirannon/orders',
  credentials: {
    rootCertificate: readFileSync('./certs/etcd-ca.crt'),
    privateKey: readFileSync('./certs/orders-node.key'),
    certChain: readFileSync('./certs/orders-node.crt'),
  },
})
 
const sirannon = new Sirannon({ driver: betterSqlite3() })
 
const db = await sirannon.open('orders', './data/orders.db', {
  backups: {
    destination,
    replicationGroup: coordinatorBackupGroup({
      coordinator,
      clusterId: 'commerce',
      groupId: 'orders',
      nodeId: 'primary-us-east-1',
    }),
    onSkip: (skip) => console.log('backup.uncaptured_log_bytes', skip.uncapturedLogBytes ?? 0),
    onError: (err) => console.error('Backup cycle failed:', err.message),
  },
})
 
console.log(db.backupCapabilities().fullCopy)
await sirannon.shutdown()
await coordinator.close()

The program needs a live etcd cluster and the certificates that the replication guide creates. The value that it prints shows whether this driver can make a full copy. Sirannon places the backups by the live membership, so this example has no fixed result panel. Give the backup source the same nodeId as its replication engine, because the coordinator records membership under that identifier.

Give every node the same backup configuration with a separate identifier. Sirannon copies on the selected eligible node, while the others report a skip. A node that cannot read membership reports group-unavailable and retains its chain and log, even when preferredNode pins that node.

For an encrypted database, Sirannon records the key identifier in each stored chain when the loader supplies one. After a key change, Sirannon starts a new chain with a full copy under the new key at the next capture, so retain the earlier keys for the earlier backups, as encryption explains.