> Complete content index: https://narsil.sondelali.com/llms.txt

# Change capture

> Follow every insert, update, and removal on an index from a saved position, see each document as it stood before the write, receive only the changes that match a filter, and start again from an export when the feed sends a resync.

URL: https://narsil.sondelali.com/docs/change-capture
Section: Operations
Version: 0.4 (@delali/narsil@0.4.3, latest)

Change capture lets a backend service follow every insert, update, and removal on one index, so that it can keep a cache, a second index, or another system up to date. The service saves a position for each partition of the index, so that after a restart it receives every change above those positions. Following changes inside the engine works only in TypeScript. Over the HTTP server, the TypeScript client, the Python client, and the Go module `github.com/assetcorp/narsil/packages/go/changes` follow the feed.

A subscriber receives the documents of the whole index, because Narsil records no tenant or owner for a document. Decide which services may follow an index before you turn capture on, since a filter on a subscription limits the changes that the subscriber receives and controls no access.

On this page, you'll build `orders.ts`, a program that turns capture on for an index of orders, reads every change, picks up again from a saved position, receives only the open orders, and starts again from an export after a resync. Each code block 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. In the last part of the page, a server serves the feed over HTTP, while programs in TypeScript, Python, and Go follow it.

## Turn capture on and read every change

The engine builds each change from the write-ahead log, so `updateChanges` fails with `CHANGES_DURABILITY_REQUIRED` when the engine has no durability. Capture stays off for each index until you turn it on with these fields:

| Field | What it does |
| --- | --- |
| `enabled` | This turns capture on or off. |
| `previousDocument` | With this on, the engine writes into each log entry the document that the write replaces or removes. It defaults to false. |
| `historyMaxAgeMs` | The engine deletes a log segment from history once the segment is older than this many milliseconds, 30 days by default. |
| `historyMaxBytes` | The engine deletes the oldest history segment while history holds more bytes than this, which defaults to the larger of the checkpoint's length and 1 GiB. |

Turn `previousDocument` on when a subscriber needs to tell an insert from an update or needs the old values, because each change then holds the document as it stood before the write. With the option on, the engine reads the stored document on every update and removal and writes it into the log beside the new one.

A subscriber needs a place to start. The first line of a document export holds the epoch of the index and the position of each partition at the moment of the export, so a new subscriber can take the export, copy its documents, and follow the changes from the positions in that header. `catchUp` in the file below follows the changes from a saved position until it reaches the heads of the partitions, which are in the first event of the feed, and then it returns the new positions.

```ts title="orders.ts"
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import type { AnyDocument, Change, ChangePosition } from '@delali/narsil'

type SavedPositions = { epoch: string; positions: ChangePosition[] }

const narsil = await createNarsil({ durability: { directory: await mkdtemp(join(tmpdir(), 'narsil-orders-')) } })

await narsil.createIndex('orders', { schema: { customer: 'string', status: 'enum', total: 'number' } })
await narsil.updateChanges('orders', { enabled: true, previousDocument: true })

const readExport = async (): Promise<{ header: SavedPositions; documents: AnyDocument[] }> => {
  const text = await new Response(await narsil.exportDocuments('orders')).text()
  const [header, ...documents] = text.trim().split('\n').map((line) => JSON.parse(line))
  return { header: { epoch: header.epoch, positions: header.positions }, documents }
}

const describe = (change: Change): string =>
  `${change.seqNo} ${change.type} ${change.documentId} ${change.previousDocument?.status ?? '-'} -> ${change.document?.status ?? '-'}`

const catchUp = async (from: SavedPositions): Promise<SavedPositions | null> => {
  let positions = from.positions
  let heads: ChangePosition[] = []
  for await (const event of narsil.followChanges('orders', from)) {
    if (event.type === 'resync') {
      console.log(`resync ${event.reason}`)
      return null
    }
    if (event.type === 'subscribed') {
      heads = event.heads
    } else {
      for (const change of event.changes) {
        console.log(describe(change))
      }
      positions = positions.map((position) =>
        position.partitionId === event.partitionId ? { ...position, seqNo: event.scannedSeqNo } : position
      )
    }
    const caughtUp = heads.every((head) =>
      positions.some((position) => position.partitionId === head.partitionId && position.seqNo >= head.seqNo)
    )
    if (caughtUp) {
      return { epoch: from.epoch, positions }
    }
  }
  return { epoch: from.epoch, positions }
}

const start = (await readExport()).header

await narsil.insert('orders', { customer: 'Lucía Fernández', status: 'open', total: 84 }, 'order-1001')
await narsil.insert('orders', { customer: 'Arjun Mehta', status: 'open', total: 129 }, 'order-1002')
await narsil.update('orders', 'order-1001', { customer: 'Lucía Fernández', status: 'shipped', total: 84 })
await narsil.remove('orders', 'order-1002')

const saved = await catchUp(start)

console.log('saved', JSON.stringify(saved?.positions))

await narsil.shutdown()
```

```txt result open
1 insert order-1001 - -> open
2 insert order-1002 - -> open
3 update order-1001 open -> shipped
4 remove order-1002 open -> -
saved [{"partitionId":0,"seqNo":4}]
```

`followChanges` returns the changes as an async iterable of three kinds of event. The first event, `subscribed`, holds the epoch, the positions that the changes follow, and the heads of the partitions. Each `changes` event holds the changes of one partition in `seqNo` order, along with `scannedSeqNo`, which is the position to save once you apply them. A `resync` event ends the iteration, for the reasons in [Start again after a resync](#start-again-after-a-resync). Each change holds `seqNo`, `type`, `documentId`, and, when they apply, `document` and `previousDocument`. Its `type` takes one of four values:

| `type` | What it means |
| --- | --- |
| `insert` | A write adds a new document while `previousDocument` is on, and `document` holds it. |
| `update` | A write replaces a document while `previousDocument` is on, so `document` holds the new version while `previousDocument` holds the old one. |
| `put` | A write adds or replaces a document while `previousDocument` is off, and `document` holds the new version. |
| `remove` | A write removes a document, and `previousDocument` holds it when the option is on. |

A document in a change holds every field and every computed vector, so a subscriber can store it without reading the index again.

## Pick up again from a saved position

In the next step, the program makes two more writes and follows the changes again from the saved positions, so `catchUp` returns only the two new changes. Apply each batch of changes first and save its `scannedSeqNo` afterwards, so that after a crash between the two, the subscriber receives some changes again and skips none. Store the epoch and the positions in the same place as your copy of the documents, in the same transaction when that store allows it.

```ts title="orders.ts"
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import type { AnyDocument, Change, ChangePosition } from '@delali/narsil'

type SavedPositions = { epoch: string; positions: ChangePosition[] }

const narsil = await createNarsil({ durability: { directory: await mkdtemp(join(tmpdir(), 'narsil-orders-')) } })

await narsil.createIndex('orders', { schema: { customer: 'string', status: 'enum', total: 'number' } })
await narsil.updateChanges('orders', { enabled: true, previousDocument: true })

const readExport = async (): Promise<{ header: SavedPositions; documents: AnyDocument[] }> => {
  const text = await new Response(await narsil.exportDocuments('orders')).text()
  const [header, ...documents] = text.trim().split('\n').map((line) => JSON.parse(line))
  return { header: { epoch: header.epoch, positions: header.positions }, documents }
}

const describe = (change: Change): string =>
  `${change.seqNo} ${change.type} ${change.documentId} ${change.previousDocument?.status ?? '-'} -> ${change.document?.status ?? '-'}`

const catchUp = async (from: SavedPositions): Promise<SavedPositions | null> => {
  let positions = from.positions
  let heads: ChangePosition[] = []
  for await (const event of narsil.followChanges('orders', from)) {
    if (event.type === 'resync') {
      console.log(`resync ${event.reason}`)
      return null
    }
    if (event.type === 'subscribed') {
      heads = event.heads
    } else {
      for (const change of event.changes) {
        console.log(describe(change))
      }
      positions = positions.map((position) =>
        position.partitionId === event.partitionId ? { ...position, seqNo: event.scannedSeqNo } : position
      )
    }
    const caughtUp = heads.every((head) =>
      positions.some((position) => position.partitionId === head.partitionId && position.seqNo >= head.seqNo)
    )
    if (caughtUp) {
      return { epoch: from.epoch, positions }
    }
  }
  return { epoch: from.epoch, positions }
}

const start = (await readExport()).header

await narsil.insert('orders', { customer: 'Lucía Fernández', status: 'open', total: 84 }, 'order-1001')
await narsil.insert('orders', { customer: 'Arjun Mehta', status: 'open', total: 129 }, 'order-1002')
await narsil.update('orders', 'order-1001', { customer: 'Lucía Fernández', status: 'shipped', total: 84 })
await narsil.remove('orders', 'order-1002')

const saved = await catchUp(start) // [!code --]
let saved = await catchUp(start) // [!code ++]

console.log('saved', JSON.stringify(saved?.positions))

await narsil.insert('orders', { customer: 'Mei Lin', status: 'open', total: 56 }, 'order-1003') // [!code ++:8]
await narsil.update('orders', 'order-1001', { customer: 'Lucía Fernández', status: 'delivered', total: 84 })

if (saved !== null) {
  saved = await catchUp(saved)
}

console.log('saved', JSON.stringify(saved?.positions))

await narsil.shutdown()
```

```txt result open
1 insert order-1001 - -> open
2 insert order-1002 - -> open
3 update order-1001 open -> shipped
4 remove order-1002 open -> -
saved [{"partitionId":0,"seqNo":4}]
5 insert order-1003 - -> open
6 update order-1001 shipped -> delivered
saved [{"partitionId":0,"seqNo":6}]
```

The engine delivers each change at least once, so a subscriber can receive a change again after a restart. Each change holds a whole document or a removal, so a subscriber that applies it twice ends with the same copy, as long as it counts the removal of a document that the copy lacks as a success.

## Receive only the changes that match a filter

With `previousDocument` on, a subscription can hold a filter in the syntax of a query's filters, while `followChanges` fails with `CHANGES_PREVIOUS_DOCUMENT_REQUIRED` for a filter on an index with the option off. The engine tests the filter against the document before the write and the document after it:

- The subscriber receives a document that starts to match as an `insert`.
- It receives a document that stops matching as a `remove` that holds its `previousDocument`.
- It receives the change itself for a document that matches before and after the write.
- It receives nothing for a write that matches at neither time.

In this step, the program follows the same history again from the start, and it keeps only the open orders.

```ts title="orders.ts"
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import type { AnyDocument, Change, ChangePosition } from '@delali/narsil' // [!code --]
import type { AnyDocument, Change, ChangePosition, FilterExpression } from '@delali/narsil' // [!code ++]

type SavedPositions = { epoch: string; positions: ChangePosition[] }

const narsil = await createNarsil({ durability: { directory: await mkdtemp(join(tmpdir(), 'narsil-orders-')) } })

await narsil.createIndex('orders', { schema: { customer: 'string', status: 'enum', total: 'number' } })
await narsil.updateChanges('orders', { enabled: true, previousDocument: true })

const readExport = async (): Promise<{ header: SavedPositions; documents: AnyDocument[] }> => {
  const text = await new Response(await narsil.exportDocuments('orders')).text()
  const [header, ...documents] = text.trim().split('\n').map((line) => JSON.parse(line))
  return { header: { epoch: header.epoch, positions: header.positions }, documents }
}

const describe = (change: Change): string =>
  `${change.seqNo} ${change.type} ${change.documentId} ${change.previousDocument?.status ?? '-'} -> ${change.document?.status ?? '-'}`

const catchUp = async (from: SavedPositions): Promise<SavedPositions | null> => { // [!code --]
const catchUp = async (from: SavedPositions, filter?: FilterExpression): Promise<SavedPositions | null> => { // [!code ++]
  let positions = from.positions
  let heads: ChangePosition[] = []
  for await (const event of narsil.followChanges('orders', from)) { // [!code --]
  for await (const event of narsil.followChanges('orders', { ...from, filter })) { // [!code ++]
    if (event.type === 'resync') {
      console.log(`resync ${event.reason}`)
      return null
    }
    if (event.type === 'subscribed') {
      heads = event.heads
    } else {
      for (const change of event.changes) {
        console.log(describe(change))
      }
      positions = positions.map((position) =>
        position.partitionId === event.partitionId ? { ...position, seqNo: event.scannedSeqNo } : position
      )
    }
    const caughtUp = heads.every((head) =>
      positions.some((position) => position.partitionId === head.partitionId && position.seqNo >= head.seqNo)
    )
    if (caughtUp) {
      return { epoch: from.epoch, positions }
    }
  }
  return { epoch: from.epoch, positions }
}

const start = (await readExport()).header

await narsil.insert('orders', { customer: 'Lucía Fernández', status: 'open', total: 84 }, 'order-1001')
await narsil.insert('orders', { customer: 'Arjun Mehta', status: 'open', total: 129 }, 'order-1002')
await narsil.update('orders', 'order-1001', { customer: 'Lucía Fernández', status: 'shipped', total: 84 })
await narsil.remove('orders', 'order-1002')

let saved = await catchUp(start)

console.log('saved', JSON.stringify(saved?.positions))

await narsil.insert('orders', { customer: 'Mei Lin', status: 'open', total: 56 }, 'order-1003')
await narsil.update('orders', 'order-1001', { customer: 'Lucía Fernández', status: 'delivered', total: 84 })

if (saved !== null) {
  saved = await catchUp(saved)
}

console.log('saved', JSON.stringify(saved?.positions))

console.log('open orders only') // [!code ++:2]
await catchUp(start, { fields: { status: { eq: 'open' } } })

await narsil.shutdown()
```

```txt result open
1 insert order-1001 - -> open
2 insert order-1002 - -> open
3 update order-1001 open -> shipped
4 remove order-1002 open -> -
saved [{"partitionId":0,"seqNo":4}]
5 insert order-1003 - -> open
6 update order-1001 shipped -> delivered
saved [{"partitionId":0,"seqNo":6}]
open orders only
1 insert order-1001 - -> open
2 insert order-1002 - -> open
3 remove order-1001 open -> -
4 remove order-1002 open -> -
5 insert order-1003 - -> open
```

Change 3 marks order 1001 as shipped, so the order stops matching and the subscriber receives the change as a removal. Change 6 moves the same order from shipped to delivered, which matches at neither time, so the subscriber receives nothing for it. Under a filter, a `changes` event can hold an empty list, while its `scannedSeqNo` holds the position past the entries that the engine examines. Save `scannedSeqNo` from every `changes` event, empty ones included, so that the position of a subscriber whose filter matches little stays above the oldest entry in history.

A history entry that the engine writes while `previousDocument` is off holds no copy of the document from before the write. Under a filter, the subscriber receives such an entry as a `put` when the new document matches, and otherwise as a `remove` without `previousDocument`, so that the subscriber drops the document from its copy whenever the copy holds it.

## Start again after a resync

When the engine can't serve the changes above the saved positions, the last event is `resync`, with a `reason` field that holds one of these values:

- `epoch` means that the index has a new epoch. A rebalance, a clear, a restore, an analysis change, and turning capture off and on each give the index a new epoch.
- `history` means that history lacks the entries right above a position, because the engine deletes the oldest segments.
- `ahead` means that a position is above every entry of its partition.

After a resync, take a document export of the index, replace your copy with its documents, and follow the changes again from the epoch and the positions in the export's header. In this step, the program clears the index, which gives the index a new epoch, so the next catch-up ends with a resync, after which the program starts again from an export.

```ts title="orders.ts"
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
import type { AnyDocument, Change, ChangePosition, FilterExpression } from '@delali/narsil'

type SavedPositions = { epoch: string; positions: ChangePosition[] }

const narsil = await createNarsil({ durability: { directory: await mkdtemp(join(tmpdir(), 'narsil-orders-')) } })

await narsil.createIndex('orders', { schema: { customer: 'string', status: 'enum', total: 'number' } })
await narsil.updateChanges('orders', { enabled: true, previousDocument: true })

const readExport = async (): Promise<{ header: SavedPositions; documents: AnyDocument[] }> => {
  const text = await new Response(await narsil.exportDocuments('orders')).text()
  const [header, ...documents] = text.trim().split('\n').map((line) => JSON.parse(line))
  return { header: { epoch: header.epoch, positions: header.positions }, documents }
}

const describe = (change: Change): string =>
  `${change.seqNo} ${change.type} ${change.documentId} ${change.previousDocument?.status ?? '-'} -> ${change.document?.status ?? '-'}`

const catchUp = async (from: SavedPositions, filter?: FilterExpression): Promise<SavedPositions | null> => {
  let positions = from.positions
  let heads: ChangePosition[] = []
  for await (const event of narsil.followChanges('orders', { ...from, filter })) {
    if (event.type === 'resync') {
      console.log(`resync ${event.reason}`)
      return null
    }
    if (event.type === 'subscribed') {
      heads = event.heads
    } else {
      for (const change of event.changes) {
        console.log(describe(change))
      }
      positions = positions.map((position) =>
        position.partitionId === event.partitionId ? { ...position, seqNo: event.scannedSeqNo } : position
      )
    }
    const caughtUp = heads.every((head) =>
      positions.some((position) => position.partitionId === head.partitionId && position.seqNo >= head.seqNo)
    )
    if (caughtUp) {
      return { epoch: from.epoch, positions }
    }
  }
  return { epoch: from.epoch, positions }
}

const start = (await readExport()).header

await narsil.insert('orders', { customer: 'Lucía Fernández', status: 'open', total: 84 }, 'order-1001')
await narsil.insert('orders', { customer: 'Arjun Mehta', status: 'open', total: 129 }, 'order-1002')
await narsil.update('orders', 'order-1001', { customer: 'Lucía Fernández', status: 'shipped', total: 84 })
await narsil.remove('orders', 'order-1002')

let saved = await catchUp(start)

console.log('saved', JSON.stringify(saved?.positions))

await narsil.insert('orders', { customer: 'Mei Lin', status: 'open', total: 56 }, 'order-1003')
await narsil.update('orders', 'order-1001', { customer: 'Lucía Fernández', status: 'delivered', total: 84 })

if (saved !== null) {
  saved = await catchUp(saved)
}

console.log('saved', JSON.stringify(saved?.positions))

console.log('open orders only')
await catchUp(start, { fields: { status: { eq: 'open' } } })

await narsil.clear('orders') // [!code ++:7]

if (saved !== null && (await catchUp(saved)) === null) {
  const { header, documents } = await readExport()
  saved = header
  console.log('export', documents.length, 'documents', JSON.stringify(saved.positions))
}

await narsil.shutdown()
```

```txt result open
1 insert order-1001 - -> open
2 insert order-1002 - -> open
3 update order-1001 open -> shipped
4 remove order-1002 open -> -
saved [{"partitionId":0,"seqNo":4}]
5 insert order-1003 - -> open
6 update order-1001 shipped -> delivered
saved [{"partitionId":0,"seqNo":6}]
open orders only
1 insert order-1001 - -> open
2 insert order-1002 - -> open
3 remove order-1001 open -> -
4 remove order-1002 open -> -
5 insert order-1003 - -> open
resync epoch
export 0 documents [{"partitionId":0,"seqNo":6}]
```

The export is in JSON Lines, with the header on its first line. Each position in that header is the last `seqNo` that the checkpoint behind the export holds for its partition, so a subscriber that follows from it receives every write that the export leaves out. The server returns the same export for `GET /indexes/{name}/export`, and so does `exportDocuments` on each client.

## Keep the history long enough for your subscribers

While capture is on, the engine keeps the log segments that each checkpoint covers as history, so that a subscriber that reconnects can receive every change after its position. The engine checks history once an hour and deletes the oldest segment once it is older than `historyMaxAgeMs`, or while history holds more bytes than `historyMaxBytes`. A subscriber whose position falls below the oldest segment receives a resync with the reason `history` and will have to start again from an export, so set `historyMaxAgeMs` longer than the longest time that a subscriber can stay offline.

History holds every write to the index, including the writes of a document that a caller later removes, while with `previousDocument` on, the entry for the removal holds the removed document too. The content of a removed document can therefore stay on the server's disk for `historyMaxAgeMs`, plus up to an hour until the next check, after a checkpoint moves its segment into history. When a removed document has to leave the disk sooner, turn capture off, along with device sync when sync is on, and then turn each one on again, because the engine deletes the history once both are off.

The engine saves the setting with the index, while a snapshot leaves it out, so after you restore a snapshot onto another server, that server serves no changes for the index until you turn capture on there.

## Follow the changes from another service

The HTTP server serves no change feed until you set its `changes` option. With the feed on, `listen` refuses to start without an `onRequest` hook and throws `CONFIG_INVALID`, because the hook is the only check on which credential may follow which index. The server serves three routes for each index:

| Route | What it does |
| --- | --- |
| `GET /indexes/{name}/changes` | It returns the setting and the epoch, as `getChanges` does. |
| `PUT /indexes/{name}/changes` | It replaces the setting, as `updateChanges` does. |
| `GET /indexes/{name}/changes/feed` | It opens a WebSocket with the subprotocol `narsil.changes.v1`, on which the server sends every change after the subscriber's positions. |

The server calls the hook on every request and on the upgrade of the feed. A subscriber that can set no header on a WebSocket, such as a browser or the TypeScript client, sends its credential as a second `Sec-WebSocket-Protocol` value after `narsil.changes.v1`, so the hook below accepts the token from that header as well as from `authorization`. The server answers the upgrade with `narsil.changes.v1` alone, so the response never includes the credential. When the hook returns `{ expiresAt }`, the server closes the feed with close code 4401 at that time.

```ts title="changes-server.ts"
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 engine = await createNarsil({ durability: { directory: await mkdtemp(join(tmpdir(), 'narsil-orders-')) } })

await engine.createIndex('orders', { schema: { customer: 'string', status: 'enum', total: 'number' } })
await engine.updateChanges('orders', { enabled: true, previousDocument: true })

const API_TOKEN = process.env.NARSIL_API_TOKEN ?? 'order-feed-token'

const server = createServer(engine, {
  host: '127.0.0.1',
  port: 7701,
  changes: true,
  onRequest: (request) => {
    const offered = request.headers['sec-websocket-protocol']?.split(',').map((value) => value.trim()) ?? []
    return request.headers.authorization === `Bearer ${API_TOKEN}` || offered.includes(API_TOKEN)
      ? undefined
      : { status: 401, code: 'UNAUTHORISED', message: 'Send the API token as a bearer token.' }
  },
})

await server.listen()

const stop = async (): Promise<void> => {
  await server.shutdown()
  process.exit(0)
}

process.once('SIGTERM', stop)
process.once('SIGINT', stop)

console.log(`Narsil serves the order feed on port ${server.listeningPort}`)
```

```txt result open
Narsil serves the order feed on port 7701
```

The `changes` option also takes an object in place of `true`, with four fields:

- `windowBytes` sets the bytes of unacknowledged changes above which the server stops sending to a subscriber, 8,388,608 by default.
- `maxConnections` sets the number of feed connections that the server holds, 10,000 by default, and the server answers 429 to one more.
- `maxCatchUps` sets the number of connections whose history the server reads at once, 32 by default.
- `maxBufferedBytes` sets the bytes waiting for the network across all feed connections above which the server stops reading changes for every subscriber, 268,435,456 by default.

Install the subscriber for your language. To follow the feed, the Python client needs its `changes` extra, which adds `websockets` and `msgpack` to the install. Because the Go module depends on release 0.1.2 of the Go client, `go get` moves a Go client older than 0.1.2 up to that release.

<CodeGroup sync="language">

```bash title="pnpm" tab="TypeScript"
pnpm add @delali/narsil
```

```bash title="pip" tab="Python"
pip install "narsil-client[changes]==0.2.0"
```

```bash title="go get" tab="Go"
go get github.com/assetcorp/narsil/packages/go/changes@v0.1.0
```

</CodeGroup>

Start the server, then start one of these programs in another terminal. Each program subscribes from the present, writes an order and marks it as shipped once the server confirms the subscription, prints the two changes, acknowledges each position, and stops. Restart the server before you try another program, because the order already exists after the first one.

<CodeGroup sync="language">

```ts title="subscriber.ts" tab="TypeScript"
import { createNarsilClient } from '@delali/narsil/client'

const API_TOKEN = process.env.NARSIL_API_TOKEN ?? 'order-feed-token'

const client = createNarsilClient({ url: 'http://127.0.0.1:7701', apiKey: API_TOKEN })
const subscription = client.followChanges('orders', { credential: API_TOKEN })

let received = 0

for await (const event of subscription) {
  if (event.type === 'subscribed') {
    await client.insert('orders', { customer: 'Sofia Rossi', status: 'open', total: 72 }, 'order-2001')
    await client.update('orders', 'order-2001', { customer: 'Sofia Rossi', status: 'shipped', total: 72 })
  } else if (event.type === 'changes') {
    for (const change of event.changes) {
      console.log(change.type, change.documentId, change.previousDocument?.status ?? '-', '->', change.document?.status ?? '-')
    }
    subscription.ack([{ partitionId: event.partitionId, seqNo: event.scannedSeqNo }])
    received += event.changes.length
    if (received === 2) {
      subscription.close()
    }
  } else {
    console.log('resync', event.reason)
    subscription.close()
  }
}
```

```txt result open
insert order-2001 - -> open
update order-2001 open -> shipped
```

```python title="subscriber.py" tab="Python"
import os

from narsil_client import ChangesBatch, ChangesResync, ChangesSubscribed, NarsilClient

API_TOKEN = os.environ.get("NARSIL_API_TOKEN", "order-feed-token")


def status_of(document: dict | None) -> str:
    return "-" if document is None else document["status"]


with NarsilClient("http://127.0.0.1:7701", api_key=API_TOKEN) as client:
    with client.follow_changes("orders", credential=API_TOKEN) as subscription:
        received = 0
        for event in subscription:
            if isinstance(event, ChangesSubscribed):
                order = {"customer": "Sofia Rossi", "status": "open", "total": 72}
                client.insert("orders", {"document": order, "id": "order-2001"})
                client.update("orders", "order-2001", {"document": {**order, "status": "shipped"}})
            elif isinstance(event, ChangesBatch):
                for change in event.changes:
                    print(change.type, change.document_id, status_of(change.previous_document), "->", status_of(change.document))
                subscription.ack([event.position])
                received += len(event.changes)
                if received == 2:
                    subscription.close()
            elif isinstance(event, ChangesResync):
                print("resync", event.reason)
                subscription.close()
```

```txt result open
insert order-2001 - -> open
update order-2001 open -> shipped
```

```go title="main.go" tab="Go"
package main

import (
	"cmp"
	"context"
	"fmt"
	"log"
	"os"

	narsil "github.com/assetcorp/narsil/packages/go"
	"github.com/assetcorp/narsil/packages/go/changes"
)

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func statusOf(document narsil.AnyDocument) any {
	if document == nil {
		return "-"
	}
	return document["status"]
}

func run(ctx context.Context) error {
	token := cmp.Or(os.Getenv("NARSIL_API_TOKEN"), "order-feed-token")
	client, err := narsil.New(narsil.Config{URLs: []string{"http://127.0.0.1:7701"}, APIKey: token})
	if err != nil {
		return err
	}
	defer client.CloseIdleConnections()

	subscription, err := changes.Follow(ctx, client, "orders", changes.Options{Credential: token})
	if err != nil {
		return err
	}
	defer subscription.Close()

	received := 0
	for event, err := range subscription.All() {
		if err != nil {
			return err
		}
		switch event := event.(type) {
		case *changes.Subscribed:
			order := narsil.AnyDocument{"customer": "Sofia Rossi", "status": "open", "total": 72}
			if _, err := client.Insert(ctx, "orders", narsil.InsertBody{Document: order, ID: narsil.Ptr("order-2001")}); err != nil {
				return err
			}
			order["status"] = "shipped"
			if _, err := client.Update(ctx, "orders", "order-2001", narsil.DocumentBody{Document: order}); err != nil {
				return err
			}
		case *changes.Batch:
			for _, change := range event.Changes {
				fmt.Println(change.Type, change.DocumentID, statusOf(change.PreviousDocument), "->", statusOf(change.Document))
			}
			if err := subscription.Ack([]changes.Position{{PartitionID: event.PartitionID, SeqNo: event.ScannedSeqNo}}); err != nil {
				return err
			}
			received += len(event.Changes)
			if received == 2 {
				return nil
			}
		case *changes.Resync:
			fmt.Println("resync", event.Reason)
			return nil
		}
	}

	return nil
}
```

```txt result open
insert order-2001 - -> open
update order-2001 open -> shipped
```

</CodeGroup>

The server stops sending once the subscriber's unacknowledged changes pass `windowBytes`, so acknowledge each position after you save it, and acknowledge only the positions that you save. When the connection fails, the iteration ends with `CLIENT_CONNECTION_FAILED`, so subscribe again from the saved positions. The server closes the feed with one of these codes:

| Close code | Meaning |
| --- | --- |
| 1001 | The server is shutting down, and the subscriber can connect again to any node. |
| 1008 | The subscriber sends a message that breaks the protocol, such as a malformed epoch, a list of positions that leaves out a partition, or a filter past a query's limits. |
| 1009 | The subscriber sends a message longer than 65,536 bytes. |
| 1011 | The server fails to serve the connection, and the subscriber can connect again. |
| 4401 | The credential of the connection reaches its `expiresAt` time. |
| 4409 | The server refuses the subscription under the setting of the index, and the close reason holds the error code. |
| 4410 | The subscriber will have to take a fresh document export, after a `resync` or after a caller turns capture off. |

A subscriber in another language can follow the feed directly. Each message is a MessagePack map in one binary WebSocket frame. The subscriber sends `{ type: 'subscribe', epoch, positions, filter }` first, and each of its three fields after `type` is optional. The server answers with `subscribed` and then sends `changes` messages, while the subscriber sends `{ type: 'ack', positions }`, with a position for every partition, after it saves those positions.

## Follow the changes of a cluster

A subscriber can connect to any node of a [cluster](/docs/cluster), because that node fetches the changes of each partition from the primary of the partition. The node sends a change only once every in-sync copy of the partition holds the write, so the copy that becomes primary after a failover holds every change that any subscriber receives. Each node keeps history for every copy of a partition that it holds, so a new primary can serve the feed after a failover.

In a cluster, `updateChanges` fails with `CHANGES_BACKUP_STORE_REQUIRED` until you give the nodes a backup store, because a node builds the export of an index with capture on from a backup. While a node takes that backup, it answers the export with `CHANGES_EXPORT_PREPARING`, status 503, and a `Retry-After` header. These backups appear in the backup listing. For each index, the cluster keeps the two newest backups that change capture takes and deletes the older ones, while it leaves every backup that you take alone. Upgrade every node to a release that supports change capture before you turn capture on, because a node answers `CHANGES_NOT_READY` while a node on an older release is registered.

## Find the error codes

| Code | Raised when |
| --- | --- |
| `CHANGES_DURABILITY_REQUIRED` | A caller turns capture on in an engine without write-ahead log durability. The server answers 409. |
| `CHANGES_BACKUP_STORE_REQUIRED` | A caller turns capture on in a cluster without a backup store. The server answers 409. |
| `CHANGES_NOT_READY` | A caller turns capture on, or a subscriber connects, while a cluster node is on a release that can't serve the feed. The server answers 503. |
| `CHANGES_NOT_ENABLED` | A subscriber asks for the feed, or a program asks for the changes, of an index with capture off. The server answers 404. |
| `CHANGES_PREVIOUS_DOCUMENT_REQUIRED` | A subscription holds a filter on an index with `previousDocument` off. The server closes the feed with code 4409, and the close reason holds the code. |
| `CHANGES_EXPORT_PREPARING` | A cluster node is taking the backup that a document export needs. The server answers 503 with `Retry-After`. |
| `CHANGES_INVALID_POSITIONS` | A program asks for changes with a malformed epoch, with one of the epoch and the positions without the other, or with a list of positions that leaves out a partition, repeats one, or holds a partition that the index lacks. The server answers 400. |

## Where to go next

- Read [Persistence and durability](/docs/persistence-and-durability) for the write-ahead log from which the engine builds each change.
- Read [Device sync](/docs/device-sync) for the feature that shares an epoch with change capture.
- Read [Cluster](/docs/cluster) for the backup store that a cluster needs before capture.
