With continuous backups, Sirannon saves a full copy of the database and then captures the write-ahead log frames that SQLite writes after that copy. The full copy and its change files, in order, form a chain, from which Sirannon can restore the database to any moment that the chain covers.
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 turns SQLite's automatic checkpoints off while continuous backups are on, because a checkpoint outside the cycle can discard frames before Sirannon captures them. On such a database, db.checkpoint() waits for a turn of the cycle, so Sirannon always captures the frames before it checkpoints them. query and execute refuse PRAGMA wal_checkpoint with FORBIDDEN_SQL for the same reason. checkpoint() fails with BACKUP_ERROR when the cycle skips that turn, as the cycle does while the node cannot reach its replication group.
Each turn takes these steps in 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.
When staging fails, Sirannon skips the checkpoint so that SQLite leaves the frames in the log. The staging directory is {databasePath}-backup by default. Sirannon uploads a staged capture from that directory after a restart of the process, so store the directory with the database.
Continuous backups require a writable file in write-ahead logging mode and a driver with a backup engine. Sirannon refuses continuous backups with BACKUP_UNSUPPORTED on an in-memory database, with walMode: false, or on a driver without a backup engine. A read-only database has no backup cycle, so its methods that inspect the cycle or capture changes fail with BACKUP_UNSUPPORTED as well.
The Node driver requires a Node.js build whose node:sqlite exports backup, because without that function the cycle reports a failed full copy through its onError callback.
Turn the cycle on and take one turn
Save the complete memory-destination.ts helper from the restore guide beside the complete continuous-backup.ts below. The helper stores the backups in the memory of one process, so for a deployed service, store them in persistent storage through the destination contract.
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 })
}When the database opens, Sirannon starts the first turn of the cycle, which creates a full copy for a new chain. captureBackupChanges() waits for a turn that it requests and returns the BackupRunReport of that turn. It returns undefined when the turn writes nothing, as a turn can on a node other than the backup node of its replication group.
A change report has kind: 'change' and route: 'staged'. In a change report, pageCount is the number of log frames that the capture contains. Its position contains firstFrame, lastFrame, and the salts of the log. The salts identify the generation of the log that contained those frames, although a restore applies the changes in the order that the chain records them.
Read what the cycle is doing
db.backupStatus() returns the current status from memory. running is true while a turn is active. progress contains the counters of that turn and is absent between turns. chainId identifies the current chain when one exists.
lastRun, lastSkip, and lastError contain the most recent outcome of each kind. An error contains its code, its message, its timestamp, its duration, the chain identifier where one exists, and the progress before the failure. A later successful turn leaves that earlier error in place.
On the staged route for a full copy, remainingPages reaches zero before the transfer starts, while on the streamed route, the progress of the copy and of the transfer can interleave. Follow bytesWritten during the transfer, and use onProgress when you want each update.
db.backupChain() lists the chains at the destination, newest first. Each chain contains an optional full copy as base and its changes in order. The checkpointed field of a change is true when the checkpoint emptied the log, which an active reader can prevent.
Sirannon stores a full copy as sirannon-backup-{chainId}-full.db and a change file as sirannon-backup-{chainId}-000001.wal. It stores the list of chains under sirannon-backup-chain and the records of a chain under sirannon-backup-chain.{chainId}, so give each database a distinct chainName and namePrefix when several databases share a destination.
Check a stored backup before you need it
db.verifyBackup(name) downloads each piece in index order and checks its listing, its total byte count, and its recorded SHA-256 fingerprint. Sirannon loads one piece into memory at a time and writes no local file.
verifyBackup fails with BACKUP_DESTINATION_ERROR on a missing or extra piece, a wrong byte count, or a digest that doesn't match, while it fails with BACKUP_CHAIN_BROKEN for a name that no chain record contains. With fingerprint: false, Sirannon records no digest, so verifyBackup checks the piece listing and the byte count alone.
How often to capture, and when to start again
intervalMs is 60000 by default. With a shorter interval, fewer writes wait for capture, although a destination that fails or answers late can delay the next completed backup. With a value of zero, Sirannon turns the recurring timer off but takes the turn at start-up, the captures that you request, and the last turn at shutdown.
fullCopyIntervalMs is 86400000 by default. A shorter interval makes shorter chains, so a recovery applies fewer change files, although Sirannon then transfers full copies more often.
| 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, while a value of 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 options of a full copy, pagesPerStep, restartLimit, stallTimeoutMs, and noProgressStepLimit, have the same defaults as in backupTo. Configure onError and alert on every failure, because the log grows with every write while backups fail, until it can fill the disk.
When the log grows and nothing captures it
By default, Sirannon retains the log, the staged capture, and the chain while a destination refuses uploads, so the log grows for as long as the application goes on writing.
Set maxUncapturedLogBytes to limit that growth, although Sirannon then discards writes that no restore can recover. When a turn captures nothing and the log is larger than the limit, Sirannon drops the staged state that it can't use, checkpoints the log, and reports BACKUP_CHAIN_BROKEN. Sirannon starts a new full copy at the next eligible turn, so a restore from the old chain lacks the writes that Sirannon discards before that copy.
BACKUP_LOG_REWOUND means that another checkpoint restarted the log before Sirannon captured its frames. Sirannon raises BACKUP_CHAIN_BROKEN when a chain record is missing from the destination. After either failure, Sirannon starts a new chain.
What else the cycle changes
When you close the database, Sirannon asks for a last capture after the writes drain and before the connections close. When that last upload fails, an operator has to finish it, so retain the staging directory and read what onError reports.
During a bulk load with continuous backups on, Sirannon skips the final checkpoint that the load requests, because the backup cycle checkpoints once it stages those frames. In the same way, Sirannon answers a checkpoint through db.checkpoint(), through the client, or through POST /db/:id/checkpoint only once a turn of the cycle ends, so the wait can last as long as a full copy of the database takes.
When Sirannon resumes a saved chain after a restart, it takes a turn before the first recurring interval. When another eligible node in a replication group takes over the backups, that node starts a separate chain, because SQLite can apply the frames of a log only to the database file of that log.
After an encryption key change, Sirannon starts the next chain with a full copy under the new key. Store the key of each chain, and use base.keyId to find it during a recovery.