Replicas contain copies of the group's data, so taking backups on every replica can duplicate storage and copying work. Configure backup placement against the group's eligible membership so that Sirannon can select a node after failover.
Give every node the same backups options. Before each turn, Sirannon obtains the membership and selects an eligible node to copy. A failover can change that selection without changing the configuration.
This page builds group-backup.ts with a supplied membership source so that the selection can be demonstrated in one process. The continuous-backup guide describes capture and checkpointing. Start each example in a separate empty working directory.
mkdir -p dataWhat 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 selection so that nodes with the same membership select the same identifier.
preferredNode | Resolves 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. |
The default prefers a replica so that the primary can serve writes while another node copies. If only the primary remains eligible, Sirannon selects that primary.
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 the default preference selects singapore-2 and the local node skips its turn.
onSkip reports each skipped turn. Collect those reports and inspect the latest one.
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 (?, ?)', ['Peter Nkosi', 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 this turn wrote nothing at all. The skip includes both identifiers, so an operator can identify the selected node and the node that skipped.
Before reporting a preference skip, Sirannon uploads any staged capture, clears the local cycle state, and checkpoints the log. A later selected turn therefore starts a new chain. If that upload fails, Sirannon retains the chain, capture, and log for a later turn.
Watch the work move on a failover
With singapore-2 out of the membership, the same node resolves to itself on the next turn.
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 (?, ?)', ['Peter Nkosi', 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 cleared this node's previous cycle state when it skipped, so the node begins a new chain. Change files from another node cannot extend that chain, because the files have different physical layouts.
skipsSoFar is two because Sirannon also skipped the cycle's first turn. That first selection prevents another full copy when an eligible replica already takes the backups.
Report every skip, and alert on the log
Sirannon calls onSkip for each skipped turn. Its reason identifies the condition.
reason | What happened |
|---|---|
'not-preferred' | Another node of the group takes these backups. |
'group-unavailable' | readMembership failed, so this node could not tell whose turn it was. It captures nothing and checkpoints nothing. |
'previous-run-active' | A scheduled turn became due while an earlier turn remained active. |
A skip can include uncapturedLogBytes, the size of the write-ahead log at that turn. Monitor it alongside skip reasons, because a growing uncaptured log can indicate that the group cannot take 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 log while membership is unavailable so that capture can continue when the source answers again.
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.
Without writePieceIfAbsent, Sirannon writes a record and checks it afterwards. Another node can replace that record between those calls. For a group source without a conditional-write destination, the cycle 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 that already uses coordinator-backed failover keeps its membership in the coordinator, and coordinatorBackupGroup reads it from there. The source includes in-sync nodes and excludes draining, repairing, and faulted nodes.
Build the coordinator first, pass the group source to sirannon.open, and build the replication engine afterwards with the same nodeId. The example retains the in-memory destination for its API demonstration. A deployment requires shared durable storage behind those methods.
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()That file needs a live etcd cluster and the certificates that the replication guide creates. The printed capability reports whether this driver can make a full copy. Backup placement depends on 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.
Every node uses the same backup configuration with its 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, each stored chain records the key identifier when the loader supplies one. A key change causes the next capture to start a full chain under the new key, so retain earlier keys for earlier backups. See encryption.