Networked access

Device sync

Keep a local database usable offline and synchronise its writes with an authenticated server.

Device sync copies writes between a device's local database and a server database, so that the application can save work while the device is offline. The device pushes local writes over HTTP and receives other devices' changes over a WebSocket.

The server database is the unit of access. Although tables selects the live changes that a device receives, a device-sync push can write to any application table in that database. Give each account a separate database when accounts need separate data, and derive access from the authenticated identity.

Device sync is in beta. Check the upgrade guide before changing releases, because its API can change before 1.0.

Follow one note from the laptop it starts on to the phone that confirms it.

Blessing's laptop

  • notes: Draft the release note

waiting to push 1 · pushed through 0

The server

  • change log: empty

next sequence 1

Mikael's phone

  • notes: empty

applied through 0

Her laptop writes the row into its own table first, inside a transaction that also stamps it with her device id and an HLC timestamp. That stamp is what lets the loop read back her unpushed writes.

Each device keeps two cursors of its own, one for what it has pushed and one for what it has applied, and the server keeps the number each device has confirmed. A device resumes from its own two numbers after a restart or a dropped connection, and the numbers the server keeps are what tell it how much of its log it may delete.

Serve the tables a device syncs

The complete server.ts example serves one account's notes. Set SIRANNON_SESSION to a secret 64-character hexadecimal token. The browser example asks for the same token. This example allows the local web origin http://localhost:5173; change it to the origin of your application.

Install the Node driver and server peers from getting started. Use HTTPS and short-lived credentials outside local development.

server.ts
import { timingSafeEqual } from 'node:crypto'
import { mkdir } from 'node:fs/promises'
import { type RequestContext, RequestDeniedError, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { createServer } from '@delali/sirannon-db/server'
 
interface Account {
  accountId: string
}
 
const token = process.env.SIRANNON_SESSION
if (!token || !/^[a-f0-9]{64}$/.test(token)) {
  throw new Error('Set SIRANNON_SESSION to a secret 64-character hexadecimal token')
}
const expected = Buffer.from(token)
 
const authenticate = (context: RequestContext): Account => {
  const { headers } = context
  const resource = context.path.split('/')[3]
  if (context.databaseId !== 'notes' || resource === 'backup' || resource === 'encryption') {
    throw new RequestDeniedError(403, 'FORBIDDEN', 'Route access refused')
  }
  if (headers.origin !== undefined && headers.origin !== 'http://localhost:5173') {
    throw new RequestDeniedError(403, 'FORBIDDEN', 'Origin access refused')
  }
  if (!headers.authorization && headers.origin !== 'http://localhost:5173') {
    throw new RequestDeniedError(403, 'FORBIDDEN', 'A browser credential requires the configured origin')
  }
  const protocols = headers['sec-websocket-protocol']?.split(',').map((value: string): string => value.trim())
  const offered = headers.authorization?.replace(/^Bearer /, '') ?? protocols?.find((value: string): boolean => value !== 'sirannon.v1')
  const received = Buffer.from(offered ?? '')
  if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
    throw new RequestDeniedError(401, 'UNAUTHORIZED', 'Sign in to sync')
  }
  return { accountId: 'notes-account' }
}
 
await mkdir('./data', { recursive: true })
const sirannon = new Sirannon({ driver: betterSqlite3() })
const stopped = Promise.withResolvers<void>()
process.once('SIGINT', stopped.resolve)
process.once('SIGTERM', stopped.resolve)
 
try {
  const db = await sirannon.open('notes', './data/notes.db')
  await db.execute('CREATE TABLE IF NOT EXISTS notes (id TEXT PRIMARY KEY, author TEXT NOT NULL, body TEXT NOT NULL)')
  await db.watch('notes')
 
  const server = createServer<Account>(sirannon, {
    host: '127.0.0.1',
    port: 9876,
    cors: { origin: 'http://localhost:5173' },
    acceptDeviceSync: true,
    maxUnacknowledgedChanges: 500,
    authenticate,
  })
 
  try {
    await server.listen()
    await stopped.promise
  } finally {
    await server.close()
  }
} finally {
  await sirannon.shutdown()
}

acceptDeviceSync defaults to false. Enabling it requires an authenticate hook. The server then serves pushes, acknowledged subscriptions, snapshots, and the migration handshake.

In a service with several accounts, authorise the database before resolving it. Also persist the account associated with each device ID, and check it in onBeforePush and onBeforeSubscribe. A process-local map loses that association after a restart. See security for the request and database hooks.

Connect a device and start the sync loop

Load the complete device.ts file through your browser application's bundler, with the wa-sqlite peer installed. It creates a browser database and starts a controller, recovering a pending replacement before ordinary schema work. A text UUID prevents two devices from allocating the same row ID.

device.ts
import { type ChangeEvent, Sirannon } from '@delali/sirannon-db'
import { waSqlite } from '@delali/sirannon-db/driver/wa-sqlite'
import { LWWResolver, type SyncStatus, SyncController } from '@delali/sirannon-db/client'
 
const session = window.prompt('Enter the notes session token')
if (!session || !/^[a-f0-9]{64}$/.test(session)) {
  throw new Error('A 64-character hexadecimal session token is required')
}
 
const sirannon = new Sirannon({ driver: waSqlite() })
const db = await sirannon.open('notes', 'notes.db')
const BOOTSTRAP_KEY = 'notes-account:notes:bootstrapped'
const hasPendingLoad = await db.deviceSync().snapshotLoadPending()
const hasSavedPull = (await db.deviceSync().getPullState()) !== null
if (!hasSavedPull) localStorage.removeItem(BOOTSTRAP_KEY)
if (!hasPendingLoad) {
  await db.execute('CREATE TABLE IF NOT EXISTS notes (id TEXT PRIMARY KEY, author TEXT NOT NULL, body TEXT NOT NULL)')
  await db.watch('notes')
}
 
interface NoteRow {
  id: string
  author: string
  body: string
}
 
const renderNotes = async (): Promise<void> => {
  console.log(await db.query<NoteRow>('SELECT id, author, body FROM notes ORDER BY id'))
}
 
const sync = new SyncController(db, {
  url: 'http://localhost:9876',
  databaseId: 'notes',
  tables: ['notes'],
  headers: { Authorization: `Bearer ${session}` },
  webSocketProtocols: [session],
  resolver: new LWWResolver(),
  autoResync: false,
  onResyncRequired: (): void => console.log('Request a fresh copy before further edits'),
  onChange: (_event: ChangeEvent): void => {
    renderNotes().catch((error: unknown): void => console.error(error))
  },
  onStatusChange: (status: SyncStatus): void => {
    console.log(status.state, status.pendingPushCount, status.lastError)
  },
})
 
export const closeNotes = async (): Promise<void> => {
  try {
    await sync.stop()
  } finally {
    await sirannon.shutdown()
  }
}
 
try {
  await sync.start()
  const status = await sync.status()
  if (hasPendingLoad || localStorage.getItem(BOOTSTRAP_KEY) !== 'yes' || status.resyncRequired) {
    await sync.downloadSnapshot()
    localStorage.setItem(BOOTSTRAP_KEY, 'yes')
  }
  await db.execute('INSERT INTO notes (id, author, body) VALUES (?, ?, ?)', [
    crypto.randomUUID(),
    'Paola Gómez',
    'Draft the release note',
  ])
  sync.triggerPush()
  await renderNotes()
} catch (error: unknown) {
  await closeNotes()
  throw error
}

Call the exported closeNotes() when the application disposes of this database. The device saves the note locally before the server acknowledges it. A new device explicitly downloads a first snapshot before that insert so that it receives earlier server rows. Automatic replacement remains disabled in this example. Use the edit guards and manual reload action from device sync recovery when adding further editing controls.

For React Native, use the experimental expoSqlite driver. Drivers lists its peers and limits. Use a separate local file or storage namespace when an account changes, so that one account cannot read another account's cached rows.

Push local writes to the server

The controller stamps local writes with a device ID, transaction ID, and hybrid logical clock timestamp. Its push loop starts immediately and repeats every pushIntervalMs, which defaults to 1,000 milliseconds. triggerPush() requests an earlier drain and returns void.

batchSize defaults to 100 changes per request and accepts integers from 1 to 1,000. When a local transaction exceeds one batch, the server stages its batches and applies the transaction after the last batch. Server readers therefore observe the complete transaction.

The controller persists its push cursor after acknowledgement. If a request fails before acknowledgement, it can resend those changes without applying them twice. A failed push uses exponential back-off, capped by maxPushRetryDelayMs, which defaults to 30,000 milliseconds. In a browser, the controller waits while navigator.onLine is false and retries when the online event fires.

The server refuses a timestamp more than five minutes ahead of its clock with DEVICE_CLOCK_AHEAD. The controller retains the pending writes, records the error, and retries. A HOOK_DENIED refusal also leaves the writes pending. A MIGRATION_REQUIRED refusal starts the migration handshake before retrying.

Receive everyone else's writes

One ordered subscription contains changes for all selected tables. The server suppresses changes whose origin is this device, so onChange reports pulled changes after their local commit. Redraw local edits when saving them, because those edits produce no pull callback.

The server also suppresses rows written by migrations, because each device applies the migration SQL locally. Schema changes use the handshake in device sync recovery.

Hold each change before applying it

The controller stages incoming changes in _sirannon_staged_changes before applying them. A change marked txEnd completes its server transaction. The controller then resolves conflicts, applies that transaction, advances the pull cursor, and removes its staged rows in one local transaction.

After an interrupted delivery, staged changes remain in the local database. On restart, the controller applies complete staged transactions and resumes delivery from the durable position. If application fails, it reconnects from the earlier applied cursor and retries with back-off.

A server advertising sync.staged-stream can send packed changes frames and pace delivery by individual changes. The controller requests this mode automatically. Against an older compatible server, it accepts one frame per change and whole-transaction pacing.

Resolve a row edited on two devices

Both the server and the device use LWWResolver by default. The resolver compares hybrid logical clock timestamps, so the higher timestamp wins. An incoming delete competes by timestamp like an update. At equal timestamps, a delete wins; other ties use the node ID. A later insert can recreate a deleted row.

The server uses last-writer-wins for pushed changes. The device's resolver option controls pulled conflicts, so a different device rule can leave its rows different from the server's rows.

ResolverBehaviour
LWWResolverThe resolver keeps the higher timestamp and applies the tie rules above.
FieldMergeResolverThe resolver merges columns using the application's getColumnVersions callback and falls back to last-writer-wins where that metadata is absent.
PrimaryWinsResolverThe resolver prefers the configured node ID, which can identify a device that originally wrote a pulled change.

Import these classes and their conflict types from @delali/sirannon-db/client in a browser. The replication entry imports Node modules. Pass one resolver for every table or a function that returns a resolver for each table.

The push response reports applied, skipped, and conflicts. The device-sync route accepts row inserts, updates, and deletes. Schema changes require migrations.

How a device confirms what it has received

A device acknowledges a sequence only after committing its changes to local storage, whether staged or applied. The server uses that acknowledgement to resume delivery and retain history for the device.

ackIntervalMs defaults to 2,000 milliseconds. The device acknowledges sooner when outstanding changes reach immediateAckAfterChanges, which defaults to half the server's advertised window, or 500 when the server provides no window.

The server pauses delivery at maxUnacknowledgedChanges, which defaults to 1,000. A staged stream counts individual changes, while a legacy stream preserves whole transactions. The server reloads later changes from its log after acknowledgement.

Twelve changes are waiting in the change log.

maxUnacknowledgedChanges 4, default 1000

123456789101112
confirmed by the devicesent, still unconfirmedheld in the log

The server sends through 7 and then waits, because sending change 8 would leave 5 changes unconfirmed, one more than the window allows.

The server may pause the stream to a device that stages at any point, because such a device confirms each change as it stages it. It pauses the stream to a device that applies from memory only where a transaction starts, so one save larger than the whole window still arrives whole.

A connection whose buffered bytes exceed maxWebSocketBackpressureBytes closes with 4290. The controller reconnects and resumes. If the server deletes a device cursor because of retention or maxChangesHeldForDevice, the next acknowledgement or log scan closes a connected device with 4410, so that it reconnects and resyncs.

Read the sync status

await sync.status() returns state, deviceId, serverCapabilities, schemaVersion, pendingPushCount, lastPushedSeq, lastPulledSeq, pushCaughtUp, resyncRequired, and lastError.

The state can be stopped, starting, running, paused, or snapshotting. A running controller can have a connection error, so inspect lastError and the pending count before showing that changes are saved. pushCaughtUp means the local outbox is empty.

The sequence fields use bigint. Convert them with String() before displaying them or serialising a status as JSON.

pause() stops the loops while retaining cursors. resume() restarts them, and stop() ends the controller's activity. A later start() resumes from durable cursors.

Follow the status without polling

onStatusChange receives a SyncStatus after a state change, push, applied pull, resync requirement, or error change. The controller queues callbacks in order on microtasks and contains listener exceptions.

The pending count can lag other fields because it requires a database read. With a listener installed, the controller refreshes that count in the background at most once every 100 milliseconds and reports a changed count.

Controller options

url, databaseId, and a non-empty tables list are required. Configuration lists every option, including snapshot retries, callback arguments, and request timeouts. requestTimeout: 0 removes the HTTP deadline; otherwise the default is 30,000 milliseconds. snapshotPageSize accepts 1 to 1,000 rows and defaults to 500.

How a browser device sends its credential

Browser WebSockets accept subprotocols but provide no API for custom handshake headers. Send the HTTP bearer credential in headers and a short-lived WebSocket ticket in webSocketProtocols. The local example uses the same token for both paths; a deployed service can issue separate credentials as security explains.

The controller offers sirannon.v1 before your protocols. Each extra protocol must be a distinct, non-empty HTTP token, which excludes spaces, commas, and quotation marks. Invalid options fail with INVALID_ARGUMENT without including the credential in the message.

Node and Bun can attach the configured headers to the upgrade. A browser controller with headers but no webSocketProtocols fails before opening the connection.