Networked access

Device sync

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

Device sync copies writes between the local database on a device and a database on a server, so that people can go on working in your application while the device is offline. The device pushes its local writes to the server over HTTP and receives the changes from other devices over a WebSocket connection.

The server grants access one whole database at a time. Although tables selects the live changes that a device receives, a device sync push can write to any application table in that database. When each account needs separate data, give each account a separate database and derive its access from the authenticated identity.

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 that a device syncs

The server in the complete server.ts example serves the notes of one account. Set SIRANNON_SESSION to a secret 64-character hexadecimal token, which the browser example requires as well. The server accepts requests from the local web origin http://localhost:5173, so change that origin to the origin of your application.

Install the Node driver and the server peers from getting started. Outside local development, use HTTPS and short-lived credentials.

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' || resource === 'checkpoint') {
    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. When you set it to true, the server requires an authenticate hook and serves pushes, acknowledged subscriptions, snapshots, and the migration handshake. The hook in this example refuses the backup, encryption, and checkpoint routes, because only an operator needs them.

In a service with several accounts, authorise the database before you resolve it. Store the account that each device ID belongs to in a database, and check that account in onBeforePush and onBeforeSubscribe, because a map in the memory of a process is empty again after the process restarts. The request and database hooks are in Security.

Connect a device and start the sync loop

Load the complete device.ts file through the bundler of your browser application, with the wa-sqlite peer installed. The code in device.ts creates a browser database and skips the schema statements while a snapshot load is pending, so that the controller can finish that load first. The code gives each note a random UUID as its ID, so two devices can create notes at the same time without a clash of IDs.

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(),
    'Field engineer',
    '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 code saves the note locally before the server acknowledges it. Before that insert, a new device downloads a first snapshot so that it receives the rows that the server stored earlier. The example sets autoResync to false, so the controller reports a required resync through onResyncRequired and leaves the replacement to your code. When you add more editing controls, use the edit guards and the manual reload from device sync recovery.

For React Native, use the expoSqlite driver, whose peers and limits are in drivers. When the account on a device changes, switch to a separate local file or storage namespace, so that your application shows each account only the rows that the device cached for that account.

Push local writes to the server

The controller stamps each local write with a device ID, a transaction ID, and a hybrid logical clock timestamp. Its push loop starts at once and repeats every pushIntervalMs, which defaults to 1,000 milliseconds. triggerPush() asks the loop to push sooner and returns void.

batchSize defaults to 100 changes per request and accepts whole numbers from 1 to 1,000. When a local transaction is larger than one batch, the server stages its batches and applies the transaction after the last batch, so a read on the server returns either all of that transaction or none of it.

The controller saves its push cursor after the server acknowledges a push. When a request fails before that acknowledgement, the controller can send those changes again, although the server applies each change only once. After a failed push, the controller backs off exponentially up to maxPushRetryDelayMs, which defaults to 30,000 milliseconds. In a browser, the controller pauses its pushes while navigator.onLine is false and tries again when the online event fires.

The server refuses a timestamp more than five minutes ahead of its clock with DEVICE_CLOCK_AHEAD, after which the controller records the error and tries the pending writes again. After a HOOK_DENIED refusal, the controller leaves the writes in its outbox as well, while a MIGRATION_REQUIRED refusal starts the migration handshake before the controller tries again.

Receive everyone else's writes

The controller opens one ordered subscription for all the tables in tables. The server sends the device only the changes that came from other devices, so the controller calls onChange only for the changes that it pulls, after their local commit. Redraw a local edit when you save it, because a local edit produces no onChange call.

The server also leaves the rows that migrations write out of the stream, because each device executes the migration SQL locally. For a schema change, follow the handshake in device sync recovery.

Hold each change before applying it

The controller stages incoming changes in _sirannon_staged_changes before it applies them. The server marks the last change of each transaction with txEnd. Once the controller stages that change, it resolves conflicts, applies the transaction, advances the pull cursor, and removes the staged rows, all in one local transaction.

When a delivery stops partway, the local database contains the changes that the controller staged. On restart, the controller applies every complete staged transaction and resumes delivery from the last position that it saved. When the controller fails to apply a transaction, it reconnects from the earlier applied cursor and tries again with back-off.

A server that advertises sync.staged-stream can send packed changes frames and pace delivery by individual changes. The controller asks for this mode whenever the server advertises it. With an older compatible server, the controller accepts one frame per change, while the server paces delivery by whole transactions.

Resolve a row edited on two devices

The server and the device both use LWWResolver by default. The resolver compares hybrid logical clock timestamps and applies the change with the higher timestamp. It compares an incoming delete by its timestamp in the same way as an update. When two timestamps are equal, the resolver prefers the delete; for any other tie, it compares the node IDs. A later insert can recreate a deleted row.

The server resolves pushed changes by last-writer-wins. The device applies its resolver option to pulled conflicts, so with a different rule on the device, the rows on the device can differ from the rows on the server.

ResolverBehaviour
LWWResolverThe resolver applies the change with the higher timestamp and follows the tie rules above.
FieldMergeResolverThe resolver merges columns through the application's getColumnVersions callback, while it falls back to last-writer-wins for a column without that metadata.
PrimaryWinsResolverThe resolver prefers the changes from the configured node ID, which can be the ID of the device that made a pulled change.

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

The server answers a push with applied, skipped, and conflicts. The device sync route accepts row inserts, updates, and deletes, so a schema change requires a migration.

How a device confirms what it has received

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

The server stores the acknowledgements of many devices in one transaction, up to 5,000 in each, and it starts each transaction at least 200 milliseconds after the start of the one before. It answers an acknowledgement only after the transaction that stores the cursor of the device commits, so the server can answer up to 200 milliseconds after it receives the acknowledgement, plus the time that the transactions take. When the database closes before that transaction, the server fails the acknowledgement with DATABASE_CLOSED.

ackIntervalMs defaults to 2,000 milliseconds. The device acknowledges sooner when its unacknowledged changes reach immediateAckAfterChanges, which defaults to half the window that the server advertises, or to 500 when the server advertises no window.

The server pauses delivery when the unacknowledged changes of a device reach maxUnacknowledgedChanges, which defaults to 1,000. On a staged stream, the server can pause in the middle of a transaction. On a legacy stream, the server checks that limit only before a new transaction starts, so the device receives a transaction larger than the limit whole. After the device acknowledges, the server fetches the later changes from the change log.

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.

The server closes a connection with 4290 when the bytes that it buffers for that connection exceed maxWebSocketBackpressureBytes, after which the controller reconnects and resumes. When the server deletes the cursor of a device because of retention or maxChangesHeldForDevice, it closes the connection of that device with 4410 at the next acknowledgement or log scan, so that the device 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 your application shows that the changes are saved. pushCaughtUp is true when the local outbox is empty.

The sequence fields are bigint values, so convert them with String() before you display them or serialise a status as JSON.

pause() stops the loops and retains the cursors, while resume() restarts them. stop() ends the work of the controller, although a later start() resumes from the saved cursors.

Follow the status without polling

The controller calls onStatusChange with a SyncStatus after a change of state, a push, an applied pull, a required resync, or a change of error. It queues those callbacks in order on microtasks and catches any exception that a listener throws.

The pending count can lag behind the other fields, because the controller queries that count from the database. While a listener is attached, the controller refreshes the count in the background at most once every 100 milliseconds and reports it whenever it changes.

Controller options

The controller requires url, databaseId, and a tables list with at least one table. Every option is in Configuration, including snapshot retries, callback arguments, and request timeouts. requestTimeout defaults to 30,000 milliseconds, while requestTimeout: 0 removes the HTTP deadline. snapshotPageSize accepts 1 to 1,000 rows and defaults to 500.

How a browser device sends its credential

A browser lets a WebSocket offer subprotocols, but it has no API for custom handshake headers. Send the HTTP bearer credential in headers and a short-lived WebSocket ticket in webSocketProtocols. The local example sends the same token both ways, while a deployed service can issue a separate credential for each. The details of that setup are in security.

The controller offers sirannon.v1 before your protocols. Each extra protocol has to be a distinct HTTP token of at least one character, so it can contain no spaces, commas, or quotation marks. The controller refuses an invalid protocol with INVALID_ARGUMENT and leaves the credential out of the error message.

In Node and Bun, the controller can attach the configured headers to the upgrade request. In a browser, a controller that has headers and no webSocketProtocols fails before it opens the connection.