Continuous backups save a full database copy and then capture the write-ahead log frames that changed after it. The full copy and its ordered change files form a chain. A restore needs the full copy and every change file through the requested timestamp.
Sirannon starts a new chain with a full copy every 24 hours by default. The restore guide explains how to recover a database from a chain.
What the cycle takes over
Sirannon disables SQLite's automatic checkpoints while continuous backups are enabled. A checkpoint can otherwise discard frames before Sirannon captures them.
Each turn follows this order.
- Sirannon uploads a capture that an earlier turn staged but could not send.
- Sirannon takes the writer lock and stages the new log frames.
- Sirannon checkpoints the log under that lock.
- Sirannon uploads the staged capture and appends its chain record.
If staging fails, Sirannon skips the checkpoint so that the frames remain available. The staging directory defaults to {databasePath}-backup, so a staged capture can remain available across a process restart. Preserve that directory with the database.
Continuous backups require a writable file in write-ahead logging mode and a driver with a backup engine. In-memory databases, walMode: false, and unsupported drivers fail with BACKUP_UNSUPPORTED. A read-only database has no backup cycle, so its cycle inspection and capture methods also fail with BACKUP_UNSUPPORTED.
The Node driver requires a Node build that exports backup from node:sqlite. If the runtime lacks that function, its full copy fails through the cycle's onError callback.
Turn the cycle on and take one turn
Save the complete memory-destination.ts helper from the restore guide beside this complete continuous-backup.ts. The helper demonstrates the API within one process; use persistent storage through the destination contract for a deployed service.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { memory } from './memory-destination.ts'
const directory = await mkdtemp(join(tmpdir(), 'sirannon-continuous-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
try {
const db = await sirannon.open('orders', join(directory, 'orders.db'), {
backups: {
destination: memory,
intervalMs: 60_000,
fullCopyIntervalMs: 24 * 60 * 60 * 1000,
onError: (error): void => console.error('Backup cycle failed', error),
},
})
await db.execute('CREATE TABLE orders (id INTEGER PRIMARY KEY, total INTEGER NOT NULL)')
await db.executeBatch('INSERT INTO orders VALUES (?, ?)', [[1, 12850], [2, 6400], [3, 24999]])
const capture = await db.captureBackupChanges()
const status = db.backupStatus()
const chains = await db.backupChain()
const base = chains[0]?.base
if (!base) throw new Error('The full copy is missing')
const verified = await db.verifyBackup(base.name)
console.log(JSON.stringify({
captureKind: capture?.kind,
lastKind: status.lastRun?.kind,
chains: chains.length,
verifiedKind: verified.kind,
}, (key: string, value: unknown): unknown =>
typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
await sirannon.shutdown()
await rm(directory, { recursive: true, force: true })
}Opening starts the cycle's first turn, which creates a full copy for a new chain. captureBackupChanges() waits for a requested turn and returns its BackupRunReport, or undefined when the turn writes nothing. A turn on a node that is not selected for backups can return undefined.
A change report uses kind: 'change' and route: 'staged'. Its pageCount counts log frames. Its position includes firstFrame, lastFrame, and the log's salts. The salts identify a log generation, while the chain sequence determines restore order.
Read what the cycle is doing
db.backupStatus() returns the current status from memory. running identifies an active turn, while progress reports that turn's counters and is absent between turns. chainId identifies the current chain when one exists.
lastRun, lastSkip, and lastError retain the most recent outcome of each kind. An error includes its code, message, timestamp, duration, chain identifier when available, and progress before the failure. A later successful turn does not erase that earlier error.
On the staged full-copy route, remainingPages reaches zero before transfer starts. On the streamed route, copy and transfer progress can interleave. Follow bytesWritten during transfer and use onProgress when you need each update.
db.backupChain() lists chains from the destination, newest first. Each chain includes an optional full-copy base and ordered changes. A change's checkpointed records whether the checkpoint emptied the log; an active reader can prevent that.
Sirannon stores a full copy as sirannon-backup-{chainId}-full.db and a change file as sirannon-backup-{chainId}-000001.wal. It stores the chain list under sirannon-backup-chain and a chain's records under sirannon-backup-chain.{chainId}. Give separate databases distinct chainName and namePrefix values when they share a destination.
Check a stored backup before you need it
db.verifyBackup(name) downloads each piece in index order and checks its listing, total byte count, and recorded SHA-256 fingerprint. Sirannon keeps one piece in memory without writing a local file.
A missing or extra piece, incorrect byte count, or digest mismatch fails with BACKUP_DESTINATION_ERROR. A name absent from the chain records fails with BACKUP_CHAIN_BROKEN. When fingerprint: false disables the recorded digest, verification checks the piece listing and byte count only.
How frequently to capture, and when to start again
intervalMs defaults to 60000. A shorter interval can reduce the writes awaiting capture, but a failed or delayed destination can leave a longer period without a completed backup. A value of zero disables the recurring timer while preserving the startup turn, explicit captures, and final shutdown turn.
fullCopyIntervalMs defaults to 86400000. A shorter chain requires fewer change files during recovery but transfers full copies more frequently.
| Option | Default | Behaviour |
|---|---|---|
destination | Required. | Sirannon stores backup pieces and records here. |
chainName | sirannon-backup-chain | Sirannon stores the chain list under this name. |
namePrefix | sirannon-backup | Sirannon prefixes each backup's name with this value. |
pieceBytes | 16777216 | Sirannon uses this size for each complete piece. |
fingerprint | true | Sirannon records a SHA-256 digest for each backup. |
stagingDir | {databasePath}-backup | Sirannon stages captures and staged full copies here. |
maxUncapturedLogBytes | Unlimited. | Sirannon checks this log-size limit after turns that capture nothing. |
replicationGroup | Absent. | Sirannon obtains the group membership from this source. |
preferredNode | 'replica' | Sirannon prefers an eligible replica for backups. |
destinationTimeoutMs | 600000 | Sirannon limits each destination call to this many milliseconds; zero removes the deadline. |
onRun | Absent. | Sirannon reports each completed backup through this callback. |
onProgress | Absent. | Sirannon reports copy steps and stored pieces through this callback. |
onSkip | Absent. | Sirannon reports skipped turns through this callback. |
onError | Absent. | Sirannon reports capture, upload, and checkpoint failures through this callback. |
The full-copy options pagesPerStep, restartLimit, stallTimeoutMs, and noProgressStepLimit use the backupTo defaults. Configure onError and alert on failures, because continuing writes can exhaust disk space while backups fail.
When the log grows and nothing captures it
By default, Sirannon preserves the log, staged capture, and chain while a destination refuses uploads. The log can grow for as long as the application continues writing.
maxUncapturedLogBytes exchanges that unlimited growth for a recovery gap. When a turn captures nothing and the log exceeds the configured limit, Sirannon drops the unusable staged state, checkpoints the log, and reports BACKUP_CHAIN_BROKEN. The next eligible turn starts a new full copy. Writes discarded before that full copy are unavailable through the old chain.
BACKUP_LOG_REWOUND means another checkpoint restarted the log before Sirannon captured its frames. A chain record that disappears from the destination also causes BACKUP_CHAIN_BROKEN. Both failures require a new chain.
What else the cycle changes
Closing the database requests a final capture after writes drain and before connections close. A failed final upload still requires operator attention, so preserve the staging directory and inspect onError.
A bulk load skips its requested final checkpoint when continuous backups are enabled. The backup cycle checkpoints after staging those frames.
When Sirannon resumes a saved chain after restart, it takes a turn before the first recurring interval. In a replication group, a different eligible node starts a separate chain because physical log frames are specific to one database file.
After an encryption key change, the next chain starts with a full copy under the new key. Retain the key for each chain, using base.keyId to identify it during recovery.