With device sync, a laptop, a browser tab, or a phone keeps a copy of one index, so that the app can search and write on the device while it is offline. The device downloads a snapshot of the server's index once, receives every later change from a feed, and uploads the writes made on the device whenever it can reach the server. The device side, @delali/narsil/sync, works only in TypeScript, while the Python client and the Go client can turn sync on for an index and download its snapshot.
Turn sync on only for an index whose documents are all one user's, because every device that syncs an index receives the whole index. Give each user a separate index, such as notes-user-41, and leave sync off for a public index and for any index that holds the data of several users or tenants.
On this page, you'll build notes-sync.ts, a program in which a server serves one user's notes, a device keeps a copy of them, both sides write, and your backend settles a conflict. Each code block below holds the whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.
Turn sync on for one user's index
The server builds the feed from the engine's write-ahead log, so updateSync fails with SYNC_DURABILITY_REQUIRED on an engine that keeps its indexes only in memory. The server serves no sync routes until you pass sync: true. With the routes on, listen() fails with CONFIG_INVALID when the server has no onRequest hook, because the hook is the only check on which credential may download which index. The hook below accepts a credential only for the paths under the index of the credential's owner. In the file, the server's engine writes to a fresh temporary directory, so that the program starts from an empty index every time.
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import { createServer } from '@delali/narsil/server'
const TOKENS: Record<string, string> = { 'token-for-user-41': 'user-41', 'token-for-user-77': 'user-77' }
const dataDirectory = await mkdtemp(join(tmpdir(), 'narsil-sync-'))
const serverEngine = await createNarsil({ durability: { directory: join(dataDirectory, 'server') } })
await serverEngine.createIndex('notes-user-41', { schema: { title: 'string', body: 'string' } })
await serverEngine.insert('notes-user-41', {
id: 'ferry-times',
title: 'Ferry times',
body: 'The first boat to the island leaves the harbour at 06:40.',
})
await serverEngine.updateSync('notes-user-41', { enabled: true })
const credentialOf = (headers: Record<string, string>): string | undefined => {
const bearer = headers.authorization?.match(/^Bearer (.+)$/)?.[1]
const offered = headers['sec-websocket-protocol']?.split(',').map((value) => value.trim())[1]
return bearer ?? offered
}
const server = createServer(serverEngine, {
host: '127.0.0.1',
port: 7700,
sync: true,
onRequest: (request) => {
const user = TOKENS[credentialOf(request.headers) ?? '']
if (user === undefined || !request.path.startsWith(`/indexes/notes-${user}/`)) {
return { status: 403, code: 'FORBIDDEN', message: 'This credential does not own that index.' }
}
return undefined
},
})
await server.listen()
const snapshotStatus = async (token: string): Promise<number> => {
const response = await fetch('http://127.0.0.1:7700/indexes/notes-user-41/sync/snapshot', {
headers: { authorization: `Bearer ${token}` },
})
await response.body?.cancel()
return response.status
}
console.log(
JSON.stringify(
{ owner: await snapshotStatus('token-for-user-41'), anotherUser: await snapshotStatus('token-for-user-77') },
null,
2
)
)
await server.shutdown(){
"owner": 200,
"anotherUser": 403
}The request with the owner's token downloads the snapshot, while the hook refuses the request with the token of user 77. The server calls the hook on every request and on the upgrade of the feed, which is a WebSocket. A browser can set no header on a WebSocket, so the device sends its credential as a second Sec-WebSocket-Protocol value after narsil.sync.v1, from which credentialOf takes it. When the hook returns { expiresAt } in place of undefined, the server closes the feed with close code 4401 at that time, after which the device reconnects with a fresh credential.
With sync on, the server serves two routes for each index:
| Route | What it does |
|---|---|
GET /indexes/{name}/sync/snapshot | It serves the published snapshot archive, with its entity tag and its length. A device can resume a download with a Range request and If-Range. |
GET /indexes/{name}/sync/feed | It opens a WebSocket with the subprotocol narsil.sync.v1, on which the server sends every change after the device's position. |
Keep a copy on the device
createDeviceSync takes an engine on the device, the index name, the server's address, and a store for the device's state, which holds the queue of local writes, the device's position in the feed, and a snapshot download in progress. @delali/narsil/sync/filesystem provides a store for Node.js and Electron, while @delali/narsil/sync/indexeddb provides createIndexedDBDeviceStore for a browser, where the engine takes the IndexedDB persistence adapter. credential is a function that returns the token that the device sends. When the server closes the feed because the credential expires, the device calls that function again.
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import { createServer } from '@delali/narsil/server'
import { createDeviceSync } from '@delali/narsil/sync'
import { createFilesystemDeviceStore } from '@delali/narsil/sync/filesystem'
const TOKENS: Record<string, string> = { 'token-for-user-41': 'user-41', 'token-for-user-77': 'user-77' }
const dataDirectory = await mkdtemp(join(tmpdir(), 'narsil-sync-'))
const serverEngine = await createNarsil({ durability: { directory: join(dataDirectory, 'server') } })
await serverEngine.createIndex('notes-user-41', { schema: { title: 'string', body: 'string' } })
await serverEngine.insert('notes-user-41', {
id: 'ferry-times',
title: 'Ferry times',
body: 'The first boat to the island leaves the harbour at 06:40.',
})
await serverEngine.updateSync('notes-user-41', { enabled: true })
const credentialOf = (headers: Record<string, string>): string | undefined => {
const bearer = headers.authorization?.match(/^Bearer (.+)$/)?.[1]
const offered = headers['sec-websocket-protocol']?.split(',').map((value) => value.trim())[1]
return bearer ?? offered
}
const server = createServer(serverEngine, {
host: '127.0.0.1',
port: 7700,
sync: true,
onRequest: (request) => {
const user = TOKENS[credentialOf(request.headers) ?? '']
if (user === undefined || !request.path.startsWith(`/indexes/notes-${user}/`)) {
return { status: 403, code: 'FORBIDDEN', message: 'This credential does not own that index.' }
}
return undefined
},
})
await server.listen()
const snapshotStatus = async (token: string): Promise<number> => {
const response = await fetch('http://127.0.0.1:7700/indexes/notes-user-41/sync/snapshot', {
headers: { authorization: `Bearer ${token}` },
})
await response.body?.cancel()
return response.status
}
console.log(
JSON.stringify(
{ owner: await snapshotStatus('token-for-user-41'), anotherUser: await snapshotStatus('token-for-user-77') },
null,
2
)
)
const deviceEngine = await createNarsil({ durability: { directory: join(dataDirectory, 'device', 'engine') } })
const store = await createFilesystemDeviceStore({ directory: join(dataDirectory, 'device', 'sync') })
const sync = createDeviceSync({
engine: deviceEngine,
indexName: 'notes-user-41',
url: 'http://127.0.0.1:7700',
store,
credential: () => 'token-for-user-41',
onError: (error) => console.warn('Device sync will retry after', error),
})
await sync.start()
await sync.settled()
const onDevice = await deviceEngine.query('notes-user-41', { term: 'ferry', document: { include: ['title'] } })
const { connection, queuedWrites } = sync.status()
console.log(JSON.stringify({ hits: onDevice.hits.map((hit) => hit.document?.title), connection, queuedWrites }, null, 2))
await sync.stop()
await store.close()
await deviceEngine.shutdown()
await server.shutdown(){
"hits": [
"Ferry times"
],
"connection": "connected",
"queuedWrites": 0
}start() connects and keeps reconnecting until you call stop(). settled() resolves once the device finishes uploading its queue and holds every change up to the server's heads. The device's engine then answers the search with no request to the server. status() returns the state of the connection, the number of queued writes, and the device's position. stop() closes the feed and waits for the work that the device has in progress, while the store stays open for the next start(), so close the store and shut the device's engine down after stop() returns, as notes-sync.ts does.
Write on the device and on the server
Write through sync.put and sync.remove, because the device uploads only the writes that go through those two methods. put saves the whole document under its id, after which a search on the device's engine returns it at once. remove succeeds for a document that the index lacks. The store holds each write in its queue until the server accepts it, so the app keeps working offline, while the device uploads the queue once it can reach the server again.
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import { createNarsil, type Narsil } from '@delali/narsil'
import { createServer } from '@delali/narsil/server'
import { createDeviceSync } from '@delali/narsil/sync'
import { createFilesystemDeviceStore } from '@delali/narsil/sync/filesystem'
const TOKENS: Record<string, string> = { 'token-for-user-41': 'user-41', 'token-for-user-77': 'user-77' }
const dataDirectory = await mkdtemp(join(tmpdir(), 'narsil-sync-'))
const serverEngine = await createNarsil({ durability: { directory: join(dataDirectory, 'server') } })
await serverEngine.createIndex('notes-user-41', { schema: { title: 'string', body: 'string' } })
await serverEngine.insert('notes-user-41', {
id: 'ferry-times',
title: 'Ferry times',
body: 'The first boat to the island leaves the harbour at 06:40.',
})
await serverEngine.updateSync('notes-user-41', { enabled: true })
const credentialOf = (headers: Record<string, string>): string | undefined => {
const bearer = headers.authorization?.match(/^Bearer (.+)$/)?.[1]
const offered = headers['sec-websocket-protocol']?.split(',').map((value) => value.trim())[1]
return bearer ?? offered
}
const server = createServer(serverEngine, {
host: '127.0.0.1',
port: 7700,
sync: true,
onRequest: (request) => {
const user = TOKENS[credentialOf(request.headers) ?? '']
if (user === undefined || !request.path.startsWith(`/indexes/notes-${user}/`)) {
return { status: 403, code: 'FORBIDDEN', message: 'This credential does not own that index.' }
}
return undefined
},
})
await server.listen()
const deviceEngine = await createNarsil({ durability: { directory: join(dataDirectory, 'device', 'engine') } })
const store = await createFilesystemDeviceStore({ directory: join(dataDirectory, 'device', 'sync') })
const sync = createDeviceSync({
engine: deviceEngine,
indexName: 'notes-user-41',
url: 'http://127.0.0.1:7700',
store,
credential: () => 'token-for-user-41',
onError: (error) => console.warn('Device sync will retry after', error),
})
await sync.start()
await sync.settled()
const onDevice = await deviceEngine.query('notes-user-41', { term: 'ferry', document: { include: ['title'] } })
const { connection, queuedWrites } = sync.status()
console.log(JSON.stringify({ hits: onDevice.hits.map((hit) => hit.document?.title), connection, queuedWrites }, null, 2))
await sync.put('ferry-tickets', { title: 'Ferry tickets', body: 'Buy return tickets at the harbour kiosk.' })
const queuedBeforeUpload = sync.status().queuedWrites
await serverEngine.insert('notes-user-41', {
id: 'ferry-delays',
title: 'Ferry delays',
body: 'Storms delay the evening ferry, so check the board.',
})
await sync.settled()
const titles = async (engine: Narsil): Promise<unknown[]> => {
const found = await engine.query('notes-user-41', { term: 'ferry', document: { include: ['title'] } })
return found.hits.map((hit) => hit.document?.title).sort()
}
console.log(
JSON.stringify(
{
queuedBeforeUpload,
onServer: await titles(serverEngine),
onDevice: await titles(deviceEngine),
queuedAfterUpload: sync.status().queuedWrites,
},
null,
2
)
)
await sync.stop()
await store.close()
await deviceEngine.shutdown()
await server.shutdown(){
"queuedBeforeUpload": 1,
"onServer": [
"Ferry delays",
"Ferry tickets",
"Ferry times"
],
"onDevice": [
"Ferry delays",
"Ferry tickets",
"Ferry times"
],
"queuedAfterUpload": 0
}The store holds the device's note in the queue until the upload, while the server sends its note to the device over the feed, so both sides hold all three notes once settled() resolves. After every restore and every restart, the device applies its queued writes again, so a write stays on the device until the server accepts it.
Decide a conflict on your backend
The server keeps the last write that it receives, so a device that uploads after a long time offline replaces any change that the server receives in the meantime. To settle each conflict yourself, pass upload, a function that the device calls with the queued writes in place of the server's document routes. The function returns one outcome for each write, either { accepted: true } or { accepted: false, error }. A refused outcome can also hold serverDocument, which is your backend's copy of the document or null. In the file below, applyNoteWrites stands in for that backend, which refuses an edit whose editedAt is older than that of the copy on the server.
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil, type Narsil } from '@delali/narsil'
import { createNarsil, NarsilError } from '@delali/narsil'
import { createServer } from '@delali/narsil/server'
import { createDeviceSync } from '@delali/narsil/sync'
import { createDeviceSync, type QueuedWrite, type RefusedWrite, type UploadOutcome } from '@delali/narsil/sync'
import { createFilesystemDeviceStore } from '@delali/narsil/sync/filesystem'
const TOKENS: Record<string, string> = { 'token-for-user-41': 'user-41', 'token-for-user-77': 'user-77' }
const dataDirectory = await mkdtemp(join(tmpdir(), 'narsil-sync-'))
const serverEngine = await createNarsil({ durability: { directory: join(dataDirectory, 'server') } })
await serverEngine.createIndex('notes-user-41', { schema: { title: 'string', body: 'string' } })
await serverEngine.insert('notes-user-41', {
id: 'ferry-times',
title: 'Ferry times',
body: 'The first boat to the island leaves the harbour at 06:40.',
})
await serverEngine.updateSync('notes-user-41', { enabled: true })
const credentialOf = (headers: Record<string, string>): string | undefined => {
const bearer = headers.authorization?.match(/^Bearer (.+)$/)?.[1]
const offered = headers['sec-websocket-protocol']?.split(',').map((value) => value.trim())[1]
return bearer ?? offered
}
const server = createServer(serverEngine, {
host: '127.0.0.1',
port: 7700,
sync: true,
onRequest: (request) => {
const user = TOKENS[credentialOf(request.headers) ?? '']
if (user === undefined || !request.path.startsWith(`/indexes/notes-${user}/`)) {
return { status: 403, code: 'FORBIDDEN', message: 'This credential does not own that index.' }
}
return undefined
},
})
await server.listen()
const applyNoteWrites = async (writes: readonly QueuedWrite[]): Promise<UploadOutcome[]> => {
const outcomes: UploadOutcome[] = []
for (const write of writes) {
const current = await serverEngine.get('notes-user-41', write.documentId)
if (write.document === null) {
if (current !== undefined) await serverEngine.remove('notes-user-41', write.documentId)
outcomes.push({ accepted: true })
} else if (current === undefined) {
await serverEngine.insert('notes-user-41', { ...write.document, id: write.documentId })
outcomes.push({ accepted: true })
} else if (Number(current.editedAt ?? 0) > Number(write.document.editedAt ?? 0)) {
outcomes.push({
accepted: false,
error: new NarsilError('NOTE_EDITED_ELSEWHERE', 'A later edit of this note reached the server first.'),
serverDocument: current,
})
} else {
await serverEngine.update('notes-user-41', write.documentId, write.document)
outcomes.push({ accepted: true })
}
}
return outcomes
}
const refusals: RefusedWrite[] = []
const deviceEngine = await createNarsil({ durability: { directory: join(dataDirectory, 'device', 'engine') } })
const store = await createFilesystemDeviceStore({ directory: join(dataDirectory, 'device', 'sync') })
const sync = createDeviceSync({
engine: deviceEngine,
indexName: 'notes-user-41',
url: 'http://127.0.0.1:7700',
store,
credential: () => 'token-for-user-41',
upload: applyNoteWrites,
onRefusedWrite: (refused) => refusals.push(refused),
onError: (error) => console.warn('Device sync will retry after', error),
})
await sync.start()
await sync.settled()
await sync.put('ferry-tickets', { title: 'Ferry tickets', body: 'Buy return tickets at the harbour kiosk.' })
const queuedBeforeUpload = sync.status().queuedWrites
await serverEngine.insert('notes-user-41', {
id: 'ferry-delays',
title: 'Ferry delays',
body: 'Storms delay the evening ferry, so check the board.',
})
await sync.settled()
const titles = async (engine: Narsil): Promise<unknown[]> => {
const found = await engine.query('notes-user-41', { term: 'ferry', document: { include: ['title'] } })
return found.hits.map((hit) => hit.document?.title).sort()
}
await serverEngine.update('notes-user-41', 'ferry-times', {
title: 'Ferry times',
body: 'From 3 November the first boat leaves the harbour at 07:10.',
editedAt: Date.parse('2026-11-02T08:15:00Z'),
})
await sync.put('ferry-times', {
title: 'Ferry times',
body: 'The first boat leaves at 06:40, so set an alarm for 06:00.',
editedAt: Date.parse('2026-11-02T07:50:00Z'),
})
await sync.settled()
console.log(
JSON.stringify(
{
queuedBeforeUpload,
onServer: await titles(serverEngine),
onDevice: await titles(deviceEngine),
queuedAfterUpload: sync.status().queuedWrites,
refused: refusals.map(({ write, error }) => ({ documentId: write.documentId, code: error.code })),
onDevice: (await deviceEngine.get('notes-user-41', 'ferry-times'))?.body,
},
null,
2
)
)
await sync.stop()
await store.close()
await deviceEngine.shutdown()
await server.shutdown(){
"refused": [
{
"documentId": "ferry-times",
"code": "NOTE_EDITED_ELSEWHERE"
}
],
"onDevice": "From 3 November the first boat leaves the harbour at 07:10."
}The server receives the web app's edit at 08:15 first, so the backend refuses the phone's edit from 07:50. The device then replaces its copy of the note with the server's copy, drops the write from its queue, and calls onRefusedWrite, so that the app can show the person both versions. Without upload, the device sends its writes through the server's document routes, and it treats an answer with status 400, 413, or 422 as a refusal. The device retries every other failure, such as a lost connection or a 503, with a growing delay, and reports each one to onError.
When the device loads a new snapshot
The device loads the published snapshot when it holds no copy, when the server's index has a new epoch, and when its position is below the oldest entry in the history that the server keeps. The index takes a new epoch on a rebalance, a clear, a restore, or an analysis change, and when you turn sync off and on again. The device also loads the snapshot when the feed holds more bytes after its position than replayLimitOfSnapshot times the snapshot's length, a multiple that defaults to 1. The store keeps a download in progress, so a device that restarts or loses its connection resumes the download from the last saved byte.
Before the download, the device checks that the app holds a registration for the language, the tokenizer, and the stop words of the server's index. When any of them is missing, the device keeps its copy and raises SYNC_ANALYSIS_UNAVAILABLE. When the device estimates that the old copy and the new one can't both fit in memory, it calls chooseSnapshotLoad with the archive's length, the memory that it needs, and the heap limit. Return 'load' to drop the old copy and load the new one, or 'keep' to keep the old copy and call sync.loadSnapshot() later. Without chooseSnapshotLoad, the device drops the old copy. A browser reports no heap limit, so a device in a browser skips the estimate.
updateSync takes two limits on that history. While a device syncs the index, the server keeps the log segments that a checkpoint covers, so that a device that reconnects can receive every change after its position. The server deletes the oldest segment once it is older than historyMaxAgeMs, 30 days by default, and while the history holds more bytes than historyMaxBytes, which defaults to the length of the published snapshot. The history holds every write, including the writes of a document that a caller later removes. Because the server checks the history once an hour, a removed document's content can stay on the server's disk for up to historyMaxAgeMs plus one hour after a checkpoint moves its segment into history, so set a shorter historyMaxAgeMs when a removed document has to leave the disk sooner. When you turn sync off while change capture is off, the server deletes the history at once.
The device receives each document with a vector field along with its vectors. For a local write to an index with automatic embedding, the device needs the embedding adapter or a vector in the document, while a text query on the device needs the same model.
Settings and errors
The sync option of createServer also takes an object with four settings:
windowBytessets the bytes of unacknowledged entries above which the server stops sending to a device, 8,388,608 by default.maxConnectionssets the number of feed connections that the server holds, 10,000 by default, and the server answers 429 to one more.maxCatchUpssets the number of connections whose history the server reads at once, 32 by default.maxBufferedBytessets the bytes waiting for the network across all feed connections above which the server stops reading entries for every feed, 268,435,456 by default.
In a cluster, any node can serve the routes, while the cluster needs a backup store, because a node builds the device's first copy from a backup.
| Code | Raised when |
|---|---|
SYNC_DURABILITY_REQUIRED | A caller turns sync on in an engine without write-ahead log durability. The server answers 409. |
SYNC_BACKUP_STORE_REQUIRED | A caller turns sync on in a cluster without a backup store. The server answers 409. |
SYNC_NOT_READY | A caller turns sync on, or a device connects, while a cluster node operates on a release that can't serve the feed. The server answers 503. |
SYNC_NOT_ENABLED | A device asks for the snapshot or the feed of an index with sync off. The server answers 404. |
SYNC_SNAPSHOT_PREPARING | A cluster node is taking the backup that the snapshot needs. The server answers 503 with Retry-After. |
SYNC_ANALYSIS_UNAVAILABLE | The device raises this code itself when the app lacks a registration for the language, the tokenizer, or the stop words of the server's index. |
The server closes the feed with code 1008 after a message that breaks the protocol, 1009 after a device message longer than 65,536 bytes, 4401 when the credential expires, and 4410 when the device has to load a new snapshot.
Where to go next
- Read HTTP server for the
onRequesthook and the other server options. - Read Persistence and durability for the write-ahead log from which the server builds the feed.
- Read React Native for an engine inside an iOS or Android app.