Sirannon replicates one primary database to separate files on replica nodes. The primary sends checksummed changes over gRPC. Replicas serve reads and can forward writes to the primary.
Static mode uses configured addresses and has no automatic failover. In coordinator mode, Sirannon uses etcd to establish write authority and promote an eligible replica.
Install the transport packages
Install the driver and the gRPC transport's optional peers:
pnpm add -E @delali/sirannon-db better-sqlite3 @grpc/grpc-js @bufbuild/protobuf grpc-health-checkCreate the certificates the nodes present to each other
The transport uses mutual TLS. Each node presents a certificate whose common name matches its nodeId. The peer checks that identity against the replication handshake.
These commands create certificates for a local two-node example. Keep the generated private keys outside version control:
mkdir -p certs data
openssl req -x509 -newkey rsa:2048 -nodes -days 365 \
-subj '/CN=Sirannon replication CA' \
-keyout certs/ca.key -out certs/ca.crt
for node in primary-us-east-1 replica-eu-west-1; do
printf 'basicConstraints = CA:FALSE\nkeyUsage = digitalSignature, keyEncipherment\nextendedKeyUsage = serverAuth, clientAuth\nsubjectAltName = DNS:localhost\n' > "certs/$node.ext"
openssl req -newkey rsa:2048 -nodes -subj "/CN=$node" \
-keyout "certs/$node.key" -out "certs/$node.csr"
openssl x509 -req -in "certs/$node.csr" -days 365 \
-CA certs/ca.crt -CAkey certs/ca.key -CAcreateserial \
-extfile "certs/$node.ext" -out "certs/$node.crt"
doneThe certificates permit both server and client authentication. Their localhost alternative name matches the example's peer address. In a deployment, issue certificates for the host names that peers will dial and protect the certificate authority's private key separately from the nodes.
Start the primary
Save this complete file as primary.ts. The separate writer connection applies changes through the replication engine. ChangeTracker records the watched table's writes, while snapshotConnectionFactory opens read connections for replicas that need a full copy.
import { ChangeTracker, Sirannon, type SQLiteConnection } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { PrimaryReplicaTopology, ReplicationEngine } from '@delali/sirannon-db/replication'
import { GrpcReplicationTransport } from '@delali/sirannon-db/transport/grpc'
const path = './data/orders.db'
const driver = betterSqlite3()
const writer = await driver.open(path)
await writer.exec('CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, total INTEGER NOT NULL)')
const tracker = new ChangeTracker()
await tracker.watch(writer, 'orders')
const sirannon = new Sirannon({ driver })
const db = await sirannon.open('orders', path)
const engine = new ReplicationEngine(db, writer, {
nodeId: 'primary-us-east-1',
topology: new PrimaryReplicaTopology('primary'),
transport: new GrpcReplicationTransport({
host: '127.0.0.1',
port: 4200,
tlsCert: './certs/primary-us-east-1.crt',
tlsKey: './certs/primary-us-east-1.key',
tlsCaCert: './certs/ca.crt',
}),
changeTracker: tracker,
snapshotConnectionFactory: (): Promise<SQLiteConnection> => driver.open(path, { readonly: true }),
})
let stopping: Promise<void> | undefined
const stop = (): Promise<void> => {
stopping ??= engine.stop().finally((): Promise<void> =>
writer.close().finally((): Promise<void> => sirannon.shutdown()))
return stopping
}
const onSignal = (): void => {
stop().catch((error: unknown): void => {
console.error(error)
process.exitCode = 1
})
}
process.once('SIGINT', onSignal)
process.once('SIGTERM', onSignal)
try {
await engine.start()
await engine.execute('INSERT INTO orders (id, total) VALUES (?, ?) ON CONFLICT(id) DO NOTHING', [1, 4999])
console.log(await engine.query('SELECT id, total FROM orders ORDER BY id'))
} catch (error) {
await stop()
throw error
}Start the file with your TypeScript launcher and leave the process available while starting the replica. The insert uses an explicit key so that repeating this example leaves the existing row intact. Send application writes through the engine so that it can enforce replication authority and acknowledgement rules.
Point a replica at the primary
Save the following complete file as replica.ts and start it in another process from the same directory. Static mode uses transportConfig.endpoints to locate the primary. writeForwarding: true permits the replica to forward writes.
import { setTimeout } from 'node:timers/promises'
import { ChangeTracker, Sirannon, type SQLiteConnection } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { PrimaryReplicaTopology, ReplicationEngine } from '@delali/sirannon-db/replication'
import { GrpcReplicationTransport } from '@delali/sirannon-db/transport/grpc'
const driver = betterSqlite3()
const path = './data/orders-replica.db'
const writer = await driver.open(path)
const sirannon = new Sirannon({ driver })
const db = await sirannon.open('orders', path)
const engine = new ReplicationEngine(db, writer, {
nodeId: 'replica-eu-west-1',
topology: new PrimaryReplicaTopology('replica'),
transport: new GrpcReplicationTransport({
tlsCert: './certs/replica-eu-west-1.crt',
tlsKey: './certs/replica-eu-west-1.key',
tlsCaCert: './certs/ca.crt',
}),
transportConfig: { endpoints: ['localhost:4200'] },
changeTracker: new ChangeTracker(),
writeForwarding: true,
})
let stopping: Promise<void> | undefined
const stop = (): Promise<void> => {
stopping ??= engine.stop().finally((): Promise<void> =>
writer.close().finally((): Promise<void> => sirannon.shutdown()))
return stopping
}
const onSignal = (): void => {
stop().catch((error: unknown): void => {
console.error(error)
process.exitCode = 1
})
}
process.once('SIGINT', onSignal)
process.once('SIGTERM', onSignal)
try {
await engine.start()
const deadline = Date.now() + 30_000
while (engine.status().syncState?.phase !== 'ready') {
if (Date.now() >= deadline) throw new Error('Replica did not become ready within the example deadline')
await setTimeout(100)
}
console.log(await engine.query('SELECT id, total FROM orders ORDER BY id'))
} catch (error) {
await stop()
throw error
}The readiness deadline limits this example's wait; size a deployment's sync settings for its database. Both processes print their query results, but this walkthrough has no fixed panel for the network's progress or timing.
First sync
A new replica copies schema and table data in checksummed batches before applying changes made during the copy. It verifies the final manifest before becoming ready to serve reads.
engine.status().syncState.phase progresses through pending, syncing, catching-up, and ready. A small database can pass through intermediate phases between status polls. snapshotSeq is the source's change-log position for the snapshot, and startedAt is an epoch-millisecond timestamp.
A replica with a completed copy can resume its changes on restart. For an out-of-band copy, initialSync: false and resumeFromSeq identify the copied position. Keep the file and that position consistent; a guessed sequence cannot establish which changes the file contains.
Write concerns
Pass writeConcern: { level, timeoutMs } in a write's options. local waits for the local commit, majority waits for a majority, and all waits for every required node. The acknowledgement timeout defaults to 5000 milliseconds. Static mode defaults to a local commit; coordinator mode defaults to majority.
Too few acknowledgements before the deadline produce WRITE_CONCERN_ERROR. This error does not undo the primary's commit, so reconcile the write before retrying it.
A forwarded write uses the primary's hooks and metrics and retains the requested write concern. executeBatch executes its parameter sets in one transaction. executeTransaction can forward a fixed list of statements atomically; a callback passed to transaction executes only on a node that accepts writes.
The transport's forwardDeadlineMs defaults to 30,000 milliseconds and bounds the replica's wait separately from the write concern. Forwarded errors retain their Sirannon code, so match error.code when handling a primary's refusal.
Read concern
Coordinator mode enforces the read concern and defaults to majority. Static mode ignores it.
| Level | Guarantee in coordinator mode |
|---|---|
local | The node returns its local data when its health permits reads. |
majority | The node must qualify for a majority read, including current in-sync membership. |
linearizable | The current primary confirms its term authority with the coordinator before reading. |
A node outside the in-sync set can refuse a majority read with NODE_NOT_IN_SYNC. A draining or repairing node can refuse with READ_CONCERN_ERROR, and a non-primary refuses a linearizable read with STALE_PRIMARY. A failed coordinator check can produce COORDINATOR_UNAVAILABLE.
The topology-aware client uses the levels advertised by GET /db/{id}/cluster when choosing an endpoint.
Conflict resolution
When an incoming change targets an existing row, Sirannon resolves the incoming and local versions according to the configured resolver.
| Resolver | Behaviour |
|---|---|
LWWResolver | It keeps the higher hybrid logical clock timestamp, including for deletes. At an equal timestamp, a remote delete wins; other ties compare node IDs. |
FieldMergeResolver | It merges non-overlapping changes and uses supplied column timestamps for overlapping columns. Without them, it falls back to last-writer-wins. |
PrimaryWinsResolver | It prefers changes from the configured primary identifier and otherwise falls back to last-writer-wins. |
A delete no longer always wins over an update. A later insert can recreate a deleted row. Sirannon applies changes from the same incoming transaction in sequence order, preserving that transaction's final state.
Set defaultConflictResolver for the engine or conflictResolvers for specific tables. A custom resolver implements resolve(context). These choices resolve data conflicts; they do not grant several nodes write authority.
Coordinator-backed failover
Read coordinator failover for session-based address discovery, voter changes, planned maintenance, and history reconciliation. Coordinator mode refuses static peer lists and client-address maps with TOPOLOGY_ERROR.
Schema changes
The engine accepts CREATE TABLE, ALTER TABLE ... ADD COLUMN, DROP TABLE, CREATE INDEX, CREATE UNIQUE INDEX, and DROP INDEX under its replication allowlist. It refuses unsupported schema changes before executing them, with REPLICATION_ERROR.
Incoming schema changes also pass validation. Reserved catalogue targets, multiple statements, AS SELECT, attachment, extension loading, and unsafe functions fail with BATCH_VALIDATION_ERROR. Use migrations for the application's schema and keep every node on compatible migrations.
Replicate an encrypted database
An encrypted database needs its key on every separate driver.open, including the engine's writer and snapshot connections. DatabaseOptions.encryption.key is a loader; OpenOptions.encryption.key is the raw Uint8Array returned by that loader.
An active engine prevents file replacement through a key change or restore with REPLICATION_ACTIVE. Stop the engine and close its writer first. After changing the key, reopen those connections under the new key before starting replication again.
An encrypted node refuses batches and snapshots to a plaintext peer with ENCRYPTION_REQUIRED. To encrypt a group, encrypt replicas first, fail over to one of them, and encrypt the former primary last. The encryption guide describes key retention and recovery.
Report the cluster to clients and to your operators
In coordinator mode, toClusterStatusInfo(engine.status(), { databaseId }) obtains client addresses from live node sessions. Pass its result through the server's getClusterStatus callback. Use toReplicationStatusInfo(engine.status()) with getReplicationStatus for readiness reporting.
Authenticate database requests and restrict authorizeClusterStatus to callers allowed to inspect node addresses. Use resolveExecutionTarget to direct server requests through the engine. See coordinator failover for a complete server setup and backups in a replication group for backup placement.