@delali/narsil/distribution spreads an index across several Node.js processes, called nodes. The engine splits each index into a fixed number of partitions and gives each partition one primary node. The primary accepts every write to that partition, and it waits until each in-sync replica on another node acknowledges the write before the call returns. Because of the replicas, a cluster can keep answering while one node is down, and because of the partitions, it can hold more documents than fit in the memory of one machine. The cluster works only in TypeScript, while the programs that call a node over HTTP can use the TypeScript, Python, or Go client.
On this page, you'll build cluster.ts, a program that starts three nodes in one process and waits until every partition has its copies. The program then backs the index up to a directory and restores the backup onto a cluster of one node. 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 a real cluster, the nodes are on separate machines, which this page can't reproduce offline, so the sections on etcd, TCP, S3, and Google Cloud Storage show the code and describe its behaviour in prose.
Start three nodes in one process
A node needs two adapters. The coordinator holds the state that every node shares, such as the schemas, the registered nodes, and the node that holds each copy of each partition, while the transport sends messages between the nodes. The in-memory pair keeps a whole cluster inside one process, which suits a test or this page. Each node below writes its partitions to a separate durability directory, because a backup needs the write-ahead log that durability keeps.
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createClusterNode } from '@delali/narsil/distribution'
import type { ClusterNode } from '@delali/narsil/distribution'
import { createInMemoryCoordinator } from '@delali/narsil/distribution/coordinator/in-memory'
import { createInMemoryNetwork, createInMemoryTransport } from '@delali/narsil/distribution/transport/in-memory'
const dataDirectory = await mkdtemp(join(tmpdir(), 'narsil-cluster-'))
const startCluster = async (nodeIds: string[]): Promise<ClusterNode[]> => {
const coordinator = createInMemoryCoordinator()
const network = createInMemoryNetwork()
const nodes: ClusterNode[] = []
for (const nodeId of nodeIds) {
const node = await createClusterNode({
coordinator,
transport: createInMemoryTransport(nodeId, network),
address: `${nodeId}:9200`,
nodeId,
engine: { durability: { directory: join(dataDirectory, nodeId) } },
})
await node.start()
nodes.push(node)
}
return nodes
}
const shop = await startCluster(['node-a', 'node-b', 'node-c'])
const [nodeA, , nodeC] = shop
await nodeA.createIndex(
'products',
{ schema: { title: 'string', category: 'enum', price: 'number' } },
{ partitionCount: 6, replicationFactor: 1 }
)
await nodeA.insertBatch('products', [
{ id: 'kettle-steel', title: 'Stainless steel kettle', category: 'kitchen', price: 39 },
{ id: 'kettle-glass', title: 'Glass kettle with tea infuser', category: 'kitchen', price: 45 },
{ id: 'rice-cooker', title: 'Rice cooker with steamer basket', category: 'kitchen', price: 89 },
{ id: 'desk-lamp', title: 'Desk lamp with dimmer', category: 'lighting', price: 54 },
{ id: 'floor-lamp', title: 'Arc floor lamp', category: 'lighting', price: 129 },
{ id: 'wool-rug', title: 'Hand-woven wool rug', category: 'living-room', price: 240 },
])
const found = await nodeC.query('products', { term: 'kettle', document: false })
console.log(JSON.stringify({ hits: found.hits.map((hit) => hit.id), coverage: found.coverage }, null, 2))
for (const node of shop) {
await node.shutdown()
}{
"hits": [
"kettle-glass",
"kettle-steel"
],
"coverage": {
"totalPartitions": 6,
"queriedPartitions": 6,
"timedOutPartitions": 0,
"failedPartitions": 0
}
}createIndex splits products into six partitions and keeps one replica of each partition beside its primary, so the cluster holds two copies of every document. When you pass neither option, the engine gives an index five partitions and one replica. The call returns once every partition has a primary in service, so the engine sends the insert that follows straight to the primaries. When that takes longer than waitForServingMs, which is 30 seconds by default, the call returns anyway. A write can then fail with QUERY_ROUTING_FAILED until the controller places the partitions. Node C sends the query to one copy of each partition and merges the answers, while coverage reports an answer from all six partitions. Check coverage wherever a partial answer can mislead a caller, because when every copy of a partition fails, the engine leaves the documents of that partition out of count and out of the ranking.
Each node has three roles unless you set roles:
- A
datanode holds partitions and answers searches. - A
coordinatornode sends each client request to the nodes that hold the data and merges their answers. - A
controllernode takes part in the election of a controller, and the elected node assigns the partitions to nodes.
Giving every node all three roles suits a cluster of three nodes or fewer.
Wait until every partition holds its copies
createIndex returns once each partition has a primary, while each replica copies its partition from the primary after that. node.cluster.getHealth() reports the progress of that copying, for the cluster and for each index:
greenmeans that every partition isACTIVE, with a primary and as many in-sync replicas as the replication factor.yellowmeans that every partition has a primary, while at least one partition is notACTIVEor has fewer in-sync replicas.redmeans that at least one partition has no primary, so the cluster can neither read nor write the documents in that partition.
The health report counts a copy only while its node stays registered with the coordinator. In the step below, the program checks the health every 250 milliseconds until it turns green or until 30 seconds pass.
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { setTimeout } from 'node:timers/promises'
import { createClusterNode } from '@delali/narsil/distribution'
import type { ClusterNode } from '@delali/narsil/distribution'
import type { ClusterHealth, ClusterNode } from '@delali/narsil/distribution'
import { createInMemoryCoordinator } from '@delali/narsil/distribution/coordinator/in-memory'
import { createInMemoryNetwork, createInMemoryTransport } from '@delali/narsil/distribution/transport/in-memory'
const dataDirectory = await mkdtemp(join(tmpdir(), 'narsil-cluster-'))
const startCluster = async (nodeIds: string[]): Promise<ClusterNode[]> => {
const coordinator = createInMemoryCoordinator()
const network = createInMemoryNetwork()
const nodes: ClusterNode[] = []
for (const nodeId of nodeIds) {
const node = await createClusterNode({
coordinator,
transport: createInMemoryTransport(nodeId, network),
address: `${nodeId}:9200`,
nodeId,
engine: { durability: { directory: join(dataDirectory, nodeId) } },
})
await node.start()
nodes.push(node)
}
return nodes
}
const waitForGreen = async (node: ClusterNode): Promise<ClusterHealth> => {
const deadline = Date.now() + 30_000
let health = await node.cluster.getHealth()
while (health.status !== 'green' && Date.now() < deadline) {
await setTimeout(250)
health = await node.cluster.getHealth()
}
return health
}
const shop = await startCluster(['node-a', 'node-b', 'node-c'])
const [nodeA, , nodeC] = shop
await nodeA.createIndex(
'products',
{ schema: { title: 'string', category: 'enum', price: 'number' } },
{ partitionCount: 6, replicationFactor: 1 }
)
await nodeA.insertBatch('products', [
{ id: 'kettle-steel', title: 'Stainless steel kettle', category: 'kitchen', price: 39 },
{ id: 'kettle-glass', title: 'Glass kettle with tea infuser', category: 'kitchen', price: 45 },
{ id: 'rice-cooker', title: 'Rice cooker with steamer basket', category: 'kitchen', price: 89 },
{ id: 'desk-lamp', title: 'Desk lamp with dimmer', category: 'lighting', price: 54 },
{ id: 'floor-lamp', title: 'Arc floor lamp', category: 'lighting', price: 129 },
{ id: 'wool-rug', title: 'Hand-woven wool rug', category: 'living-room', price: 240 },
])
const found = await nodeC.query('products', { term: 'kettle', document: false })
console.log(JSON.stringify({ hits: found.hits.map((hit) => hit.id), coverage: found.coverage }, null, 2))
const health = await waitForGreen(nodeA)
console.log(JSON.stringify(health, null, 2))
for (const node of shop) {
await node.shutdown()
}{
"hits": [
"kettle-glass",
"kettle-steel"
],
"coverage": {
"totalPartitions": 6,
"queriedPartitions": 6,
"timedOutPartitions": 0,
"failedPartitions": 0
}
}
{
"status": "green",
"indexes": [
{
"indexName": "products",
"status": "green",
"partitionCount": 6,
"replicationFactor": 1,
"partitionsWithoutPrimary": 0,
"underReplicatedPartitions": 0
}
]
}In one measured test with the same three nodes and six partitions, the health is still yellow 1 second after createIndex returns, and it turns green at 1.5 seconds, once the six replicas catch up. On a node that serves HTTP, GET /cluster/health returns the same body. The route answers with status 200 whatever the health, so a load balancer has to check status in the body.
Back up the index to a directory
A backup copies an index to a store outside the cluster, so that any cluster with access to the same store can restore the index later. Give every node the same backups setting, because the primary of each partition uploads the files of that partition. The setting holds a persistence adapter for the store and the key prefix under which this cluster writes. In this step, the program keeps the backups in a directory through the filesystem adapter. In a real cluster, that directory can be a volume that every node mounts.
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { setTimeout } from 'node:timers/promises'
import { createFilesystemPersistence } from '@delali/narsil/adapters/filesystem'
import { createClusterNode } from '@delali/narsil/distribution'
import type { ClusterHealth, ClusterNode } from '@delali/narsil/distribution'
import { createInMemoryCoordinator } from '@delali/narsil/distribution/coordinator/in-memory'
import { createInMemoryNetwork, createInMemoryTransport } from '@delali/narsil/distribution/transport/in-memory'
const dataDirectory = await mkdtemp(join(tmpdir(), 'narsil-cluster-'))
const backups = {
store: createFilesystemPersistence({ directory: join(dataDirectory, 'backups') }),
keyPrefix: 'clusters/shop',
}
const startCluster = async (nodeIds: string[]): Promise<ClusterNode[]> => {
const coordinator = createInMemoryCoordinator()
const network = createInMemoryNetwork()
const nodes: ClusterNode[] = []
for (const nodeId of nodeIds) {
const node = await createClusterNode({
coordinator,
transport: createInMemoryTransport(nodeId, network),
address: `${nodeId}:9200`,
nodeId,
backups,
engine: { durability: { directory: join(dataDirectory, nodeId) } },
})
await node.start()
nodes.push(node)
}
return nodes
}
const waitForGreen = async (node: ClusterNode): Promise<ClusterHealth> => {
const deadline = Date.now() + 30_000
let health = await node.cluster.getHealth()
while (health.status !== 'green' && Date.now() < deadline) {
await setTimeout(250)
health = await node.cluster.getHealth()
}
return health
}
const shop = await startCluster(['node-a', 'node-b', 'node-c'])
const [nodeA, , nodeC] = shop
await nodeA.createIndex(
'products',
{ schema: { title: 'string', category: 'enum', price: 'number' } },
{ partitionCount: 6, replicationFactor: 1 }
)
await nodeA.insertBatch('products', [
{ id: 'kettle-steel', title: 'Stainless steel kettle', category: 'kitchen', price: 39 },
{ id: 'kettle-glass', title: 'Glass kettle with tea infuser', category: 'kitchen', price: 45 },
{ id: 'rice-cooker', title: 'Rice cooker with steamer basket', category: 'kitchen', price: 89 },
{ id: 'desk-lamp', title: 'Desk lamp with dimmer', category: 'lighting', price: 54 },
{ id: 'floor-lamp', title: 'Arc floor lamp', category: 'lighting', price: 129 },
{ id: 'wool-rug', title: 'Hand-woven wool rug', category: 'living-room', price: 240 },
])
const found = await nodeC.query('products', { term: 'kettle', document: false })
console.log(JSON.stringify({ hits: found.hits.map((hit) => hit.id), coverage: found.coverage }, null, 2))
const health = await waitForGreen(nodeA)
console.log(JSON.stringify(health, null, 2))
const backup = await nodeA.cluster.createBackup('products', 'products-2026-11-13')
console.log(
JSON.stringify({ name: backup.name, partitionCount: backup.partitionCount, files: backup.files, bytes: backup.bytes }, null, 2)
)
for (const node of shop) {
await node.shutdown()
}{
"hits": [
"kettle-glass",
"kettle-steel"
],
"coverage": {
"totalPartitions": 6,
"queriedPartitions": 6,
"timedOutPartitions": 0,
"failedPartitions": 0
}
}
{
"status": "green",
"indexes": [
{
"indexName": "products",
"status": "green",
"partitionCount": 6,
"replicationFactor": 1,
"partitionsWithoutPrimary": 0,
"underReplicatedPartitions": 0
}
]
}
{
"name": "products-2026-11-13",
"partitionCount": 6,
"files": 11,
"bytes": 6088
}createBackup asks the primary of every partition to take a checkpoint and upload its files, after which the controller writes a manifest that lists every file. The backup holds every write that the cluster acknowledges before each primary receives the request. The primaries take their checkpoints at separate positions in their logs, so each partition in the backup reflects a separate point in its log. A primary without write-ahead log durability refuses the backup with BACKUP_DURABILITY_REQUIRED. files holds the number of stored files that the backup lists, including the manifest of each partition and the index configuration, while bytes holds the sum of their sizes.
The adapter stores each file under the SHA-256 of its bytes, while a primary uploads only the files that are missing from the store. A second backup of an unchanged index therefore adds only its manifest. A backup name has 1 to 128 characters from the letters, the digits, ., _, and -, and it starts with a letter or a digit. createBackup fails with BACKUP_ALREADY_EXISTS for a name that a stored backup or a backup in progress already uses, which is why the name above includes a date.
Keep the backups in S3 or Google Cloud Storage
createS3Persistence from @delali/narsil/adapters/s3 stores each file as an object in an S3 bucket, or in another service with an S3-compatible API once you set endpoint and forcePathStyle. createGcsPersistence from @delali/narsil/adapters/gcs stores each file as an object in a Google Cloud Storage bucket. Each adapter loads an SDK that Narsil declares as an optional peer dependency, so install the one that you use:
pnpm add @aws-sdk/client-s3
pnpm add @google-cloud/storageimport { createS3Persistence } from '@delali/narsil/adapters/s3'
import type { ClusterBackupConfig } from '@delali/narsil/distribution'
export const backups: ClusterBackupConfig = {
store: await createS3Persistence({ bucket: 'shop-search-backups', region: 'eu-west-2' }),
keyPrefix: 'clusters/shop',
}import { createGcsPersistence } from '@delali/narsil/adapters/gcs'
import type { ClusterBackupConfig } from '@delali/narsil/distribution'
export const backups: ClusterBackupConfig = {
store: await createGcsPersistence({ bucket: 'shop-search-backups', projectId: 'shop-search' }),
keyPrefix: 'clusters/shop',
}Import backups from either module and pass it to createClusterNode on every node, in place of the filesystem setting in cluster.ts. When you leave out the credentials, the S3 adapter takes them from the default credential chain of the AWS SDK, while the Cloud Storage adapter takes them from the default credentials of the host. When the SDK is missing, the adapter throws PERSISTENCE_DEPENDENCY_MISSING with a message that includes the install command.
On the first backup, the controller stores the id of the cluster under the key prefix. From then on, a backup or a deletion that another cluster starts under that prefix fails with BACKUP_STORE_CLAIMED, so that one cluster can't delete the files of another. Give each cluster a separate prefix for that reason. Turn off any rule that expires objects under the prefix, such as a bucket lifecycle rule, because backups share their stored files. The newest backup can list a file from the oldest backup, so once a rule deletes that file, a restore of any backup that lists it fails with BACKUP_DAMAGED. Delete old backups with node.cluster.deleteBackup, which removes the manifest and each file that no other backup lists.
Restore the backup onto a cluster of another size
node.cluster.restoreBackup creates a new index from a backup on a cluster of any number of nodes. The restored index keeps the partition count of the backup, while it takes the replication factor and the placement rules that you pass, or those of the backup when you pass none. In this step, the program shuts the three nodes down and starts a cluster of one node with a new coordinator, and that node uses the same backup store and key prefix. The new cluster has no second node to hold a replica, so the call passes a replication factor of 0.
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { setTimeout } from 'node:timers/promises'
import { createFilesystemPersistence } from '@delali/narsil/adapters/filesystem'
import { createClusterNode } from '@delali/narsil/distribution'
import type { ClusterHealth, ClusterNode } from '@delali/narsil/distribution'
import { createInMemoryCoordinator } from '@delali/narsil/distribution/coordinator/in-memory'
import { createInMemoryNetwork, createInMemoryTransport } from '@delali/narsil/distribution/transport/in-memory'
const dataDirectory = await mkdtemp(join(tmpdir(), 'narsil-cluster-'))
const backups = {
store: createFilesystemPersistence({ directory: join(dataDirectory, 'backups') }),
keyPrefix: 'clusters/shop',
}
const startCluster = async (nodeIds: string[]): Promise<ClusterNode[]> => {
const coordinator = createInMemoryCoordinator()
const network = createInMemoryNetwork()
const nodes: ClusterNode[] = []
for (const nodeId of nodeIds) {
const node = await createClusterNode({
coordinator,
transport: createInMemoryTransport(nodeId, network),
address: `${nodeId}:9200`,
nodeId,
backups,
engine: { durability: { directory: join(dataDirectory, nodeId) } },
})
await node.start()
nodes.push(node)
}
return nodes
}
const waitForGreen = async (node: ClusterNode): Promise<ClusterHealth> => {
const deadline = Date.now() + 30_000
let health = await node.cluster.getHealth()
while (health.status !== 'green' && Date.now() < deadline) {
await setTimeout(250)
health = await node.cluster.getHealth()
}
return health
}
const shop = await startCluster(['node-a', 'node-b', 'node-c'])
const [nodeA, , nodeC] = shop
await nodeA.createIndex(
'products',
{ schema: { title: 'string', category: 'enum', price: 'number' } },
{ partitionCount: 6, replicationFactor: 1 }
)
await nodeA.insertBatch('products', [
{ id: 'kettle-steel', title: 'Stainless steel kettle', category: 'kitchen', price: 39 },
{ id: 'kettle-glass', title: 'Glass kettle with tea infuser', category: 'kitchen', price: 45 },
{ id: 'rice-cooker', title: 'Rice cooker with steamer basket', category: 'kitchen', price: 89 },
{ id: 'desk-lamp', title: 'Desk lamp with dimmer', category: 'lighting', price: 54 },
{ id: 'floor-lamp', title: 'Arc floor lamp', category: 'lighting', price: 129 },
{ id: 'wool-rug', title: 'Hand-woven wool rug', category: 'living-room', price: 240 },
])
const found = await nodeC.query('products', { term: 'kettle', document: false })
console.log(JSON.stringify({ hits: found.hits.map((hit) => hit.id), coverage: found.coverage }, null, 2))
const health = await waitForGreen(nodeA)
console.log(JSON.stringify(health, null, 2))
const backup = await nodeA.cluster.createBackup('products', 'products-2026-11-13')
console.log(
JSON.stringify({ name: backup.name, partitionCount: backup.partitionCount, files: backup.files, bytes: backup.bytes }, null, 2)
)
for (const node of shop) {
await node.shutdown()
}
const recovery = await startCluster(['node-d'])
const [nodeD] = recovery
await nodeD.cluster.restoreBackup('products-2026-11-13', { indexName: 'products', replicationFactor: 0 })
const lamps = await nodeD.query('products', { term: 'lamp', document: false })
console.log(JSON.stringify({ documents: await nodeD.countDocuments('products'), lamps: lamps.hits.map((hit) => hit.id) }, null, 2))
for (const node of recovery) {
await node.shutdown()
}{
"hits": [
"kettle-glass",
"kettle-steel"
],
"coverage": {
"totalPartitions": 6,
"queriedPartitions": 6,
"timedOutPartitions": 0,
"failedPartitions": 0
}
}
{
"status": "green",
"indexes": [
{
"indexName": "products",
"status": "green",
"partitionCount": 6,
"replicationFactor": 1,
"partitionsWithoutPrimary": 0,
"underReplicatedPartitions": 0
}
]
}
{
"name": "products-2026-11-13",
"partitionCount": 6,
"files": 11,
"bytes": 6088
}
{
"documents": 6,
"lamps": [
"floor-lamp",
"desk-lamp"
]
}Each primary checks the length and the SHA-256 of every file before it loads any of them. When a file is missing or differs, restoreBackup fails with BACKUP_DAMAGED and creates no index. It also fails with INDEX_ALREADY_EXISTS when the cluster already holds an index under that name, so to roll a live index back, restore it under a new name and point your application at that name. A new cluster can restore the backups of a cluster that you shut down, as the one-node cluster above does, because Narsil skips the check on the key prefix for a restore and for a listing. Give the new cluster a separate prefix before it takes its first backup.
Serve a node over HTTP
clusterNodeEngine wraps a node in the interface of a single engine, so that createServer from @delali/narsil/server can serve any node unchanged. Pass node.cluster as the cluster option too. Without it, the server answers the cluster routes, the backup routes, and GET /metrics with CLUSTER_OPERATION_UNSUPPORTED and status 501, as it does in front of a single engine. With it, the server also answers GET /readyz with 200 only while the node serves all of its partitions. The program below serves one node that holds the six products, and it closes the server when the process receives SIGTERM or SIGINT, as the program on the HTTP server page does.
import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createFilesystemPersistence } from '@delali/narsil/adapters/filesystem'
import { clusterNodeEngine, createClusterNode } from '@delali/narsil/distribution'
import { createInMemoryCoordinator } from '@delali/narsil/distribution/coordinator/in-memory'
import { createInMemoryNetwork, createInMemoryTransport } from '@delali/narsil/distribution/transport/in-memory'
import { createServer } from '@delali/narsil/server'
const dataDirectory = await mkdtemp(join(tmpdir(), 'narsil-node-'))
const node = await createClusterNode({
coordinator: createInMemoryCoordinator(),
transport: createInMemoryTransport('node-a', createInMemoryNetwork()),
address: 'node-a:9200',
nodeId: 'node-a',
backups: {
store: createFilesystemPersistence({ directory: join(dataDirectory, 'backups') }),
keyPrefix: 'clusters/shop',
},
engine: { durability: { directory: join(dataDirectory, 'node-a') } },
})
await node.start()
await node.createIndex(
'products',
{ schema: { title: 'string', category: 'enum', price: 'number' } },
{ partitionCount: 3, replicationFactor: 0 }
)
await node.insertBatch('products', [
{ id: 'kettle-steel', title: 'Stainless steel kettle', category: 'kitchen', price: 39 },
{ id: 'kettle-glass', title: 'Glass kettle with tea infuser', category: 'kitchen', price: 45 },
{ id: 'rice-cooker', title: 'Rice cooker with steamer basket', category: 'kitchen', price: 89 },
{ id: 'desk-lamp', title: 'Desk lamp with dimmer', category: 'lighting', price: 54 },
{ id: 'floor-lamp', title: 'Arc floor lamp', category: 'lighting', price: 129 },
{ id: 'wool-rug', title: 'Hand-woven wool rug', category: 'living-room', price: 240 },
])
const API_TOKEN = process.env.NARSIL_API_TOKEN ?? 'shop-search-token'
const server = createServer(clusterNodeEngine(node), {
host: '127.0.0.1',
port: 9701,
cluster: node.cluster,
onRequest: (request) =>
request.headers.authorization === `Bearer ${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.close()
await node.shutdown()
process.exit(0)
}
process.once('SIGTERM', stop)
process.once('SIGINT', stop)
console.log(`${node.nodeId} answers on port ${server.listeningPort}`)node-a answers on port 9701Keep the server going in one terminal while you try the programs in the next three sections from another. Install the client for your language with the steps on the HTTP server page.
Check the health and the replication figures
The server answers GET /cluster/health with the body that getHealth returns, while it answers GET /metrics in the Prometheus text format. Because the TypeScript client has no method for either route, the TypeScript program calls fetch, while the Python and Go clients each have a method for both. The server calls the onRequest hook for both routes, so a request to either one needs the same token as a request that changes data. Each program prints the health of the cluster and the commit point of each partition of products.
import type { ClusterHealth } from '@delali/narsil/distribution'
const headers = { authorization: `Bearer ${process.env.NARSIL_API_TOKEN ?? 'shop-search-token'}` }
const health = (await (await fetch('http://127.0.0.1:9701/cluster/health', { headers })).json()) as ClusterHealth
const metrics = await (await fetch('http://127.0.0.1:9701/metrics', { headers })).text()
console.log(health.status)
console.log(metrics.split('\n').filter((line) => line.startsWith('narsil_commit_point{index="products"')).join('\n'))green
narsil_commit_point{index="products",partition="0"} 2
narsil_commit_point{index="products",partition="1"} 2
narsil_commit_point{index="products",partition="2"} 2A node reports these series:
narsil_replication_lag, with the labelsindex,partition, andreplica, holds the number of entries that each replica has yet to acknowledge, for each partition that the node leads.narsil_commit_point, with the labelsindexandpartition, holds the highest sequence number that the node acknowledges to a client, for each partition that it leads.narsil_commit_point_floorholds the floor on the commit point that the allocation table stores for every partition in the cluster. The controller raises it only when it admits a replica, so it can trailnarsil_commit_pointby many writes.narsil_in_sync_replicasholds the number of replicas in the in-sync set of every partition in the cluster, not counting the primary.narsil_vector_rebuild_waiting_for_memory, with the labelsindexandfield, holds 1 for each vector field whose rebuild is waiting until the node has enough memory for a second graph.narsil_coordinator_request_seconds, with the labeloperation, is a histogram of how long each call from the node to the coordinator takes.
Scrape every node, because each node reports the lag and the commit point only for the partitions that it leads.
Back up and restore over HTTP
The server starts each backup operation as a task. POST /indexes/{name}/backups starts a backup, POST /backups/{backup}/_restore starts a restore, DELETE /backups/{backup} starts a deletion, and GET /backups lists the backups. Each program below backs products up, restores the backup as products-restored, waits for both tasks to finish, and counts the documents in the restored index. While a task is in progress, steps.done in its record holds the number of partitions that are done, and steps.total holds the number of partitions in the task.
import { createNarsilClient } from '@delali/narsil/client'
const client = createNarsilClient({
url: 'http://127.0.0.1:9701',
apiKey: process.env.NARSIL_API_TOKEN ?? 'shop-search-token',
})
const backup = await client.createBackup('products', 'products-nightly')
const backedUp = await client.waitForTask(backup.id)
const restore = await client.restoreBackup('products-nightly', { indexName: 'products-restored' })
const restored = await client.waitForTask(restore.id)
console.log(backedUp.status, restored.status, await client.countDocuments('products-restored'))succeeded succeeded 6When you start the same program a second time against the same server, it prints failed failed 6. The backup fails because the store already holds products-nightly, while the restore fails because the cluster already holds products-restored, and the error field of each task record holds the reason. Restart the server to begin again from an empty store.
Reach every node from the client
Because each node forwards a request to the nodes that hold the data, a client can send any request to any node, so the TypeScript, Python, and Go clients each take a list of node URLs. The programs below list a second address, port 9702, on which nothing listens, so the client retries each search that it sends there on the node at port 9701. Keep the server from the section above going while you try them.
import { createNarsilClient } from '@delali/narsil/client'
const client = createNarsilClient({
url: ['http://127.0.0.1:9702', 'http://127.0.0.1:9701'],
apiKey: process.env.NARSIL_API_TOKEN ?? 'shop-search-token',
})
for (const term of ['kettle', 'lamp', 'rug']) {
const found = await client.query('products', { term, document: false })
console.log(term, found.hits.map((hit) => hit.id).join(' '))
}kettle kettle-glass kettle-steel
lamp desk-lamp floor-lamp
rug wool-rugThe client sends each request to one URL, moving to the next URL in the list for every new request, so that the requests spread across the nodes. The client retries a read on the next URL when the connection fails, when the request times out, or when the node answers 502, 503, or 504. It retries a write only when it sends none of the request, as with a refused connection, or when the node answers NODE_NOT_READY, so that the cluster never applies one change twice. After a node refuses a connection, the client skips its URL for 1 second, and it doubles that wait after each further refusal, up to 30 seconds.
Deploy the nodes across machines
In production, each node is a separate process on a separate host, so you swap the two in-memory adapters for ones that reach across the network. createEtcdCoordinator from @delali/narsil/distribution/coordinator/etcd keeps the shared state in etcd, while createTcpTransport from @delali/narsil/distribution/transport/tcp sends messages between the hosts over TCP, with mutual TLS once you pass tls. createGrpcTransport from @delali/narsil/distribution/transport/grpc sends them over gRPC. The etcd coordinator and the gRPC transport each load a package that Narsil declares as an optional peer dependency, so install the one that you use, while the TCP transport needs no extra package:
pnpm add etcd3
pnpm add @grpc/grpc-jsThe program below starts one node of a production cluster, with its backups in S3, and serves that node over HTTP. Because the program needs etcd, the certificates, and the bucket, this page shows no output for it.
import { readFileSync } from 'node:fs'
import { createS3Persistence } from '@delali/narsil/adapters/s3'
import { clusterNodeEngine, createClusterNode } from '@delali/narsil/distribution'
import { createEtcdCoordinator } from '@delali/narsil/distribution/coordinator/etcd'
import { createTcpTransport } from '@delali/narsil/distribution/transport/tcp'
import { createServer } from '@delali/narsil/server'
const nodeId = process.env.NARSIL_NODE_ID ?? 'node-a'
const API_TOKEN = process.env.NARSIL_API_TOKEN ?? 'shop-search-token'
const coordinator = await createEtcdCoordinator({
endpoints: ['https://etcd-1.internal:2379', 'https://etcd-2.internal:2379', 'https://etcd-3.internal:2379'],
tls: {
ca: readFileSync('/etc/narsil/etcd-ca.pem'),
cert: readFileSync('/etc/narsil/etcd-client.pem'),
key: readFileSync('/etc/narsil/etcd-client-key.pem'),
},
})
const transport = createTcpTransport(nodeId, {
host: '0.0.0.0',
port: 9200,
tls: {
ca: readFileSync('/etc/narsil/cluster-ca.pem'),
cert: readFileSync('/etc/narsil/node.pem'),
key: readFileSync('/etc/narsil/node-key.pem'),
},
})
const node = await createClusterNode({
coordinator,
transport,
address: `${nodeId}.narsil.internal:9200`,
nodeId,
backups: {
store: await createS3Persistence({ bucket: 'shop-search-backups', region: 'eu-west-2' }),
keyPrefix: 'clusters/shop',
},
engine: { durability: { directory: '/var/lib/narsil' } },
})
await node.start()
const server = createServer(clusterNodeEngine(node), {
host: '0.0.0.0',
port: 9701,
cluster: node.cluster,
onRequest: (request) =>
request.headers.authorization === `Bearer ${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.close()
await node.shutdown()
process.exit(0)
}
process.once('SIGTERM', stop)
process.once('SIGINT', stop)Start the same file on each host with a different NARSIL_NODE_ID, while address holds the host and port at which the other nodes reach this node over TCP. createEtcdCoordinator connects to etcd before it returns, so a wrong certificate makes that call fail with COORDINATOR_UNAVAILABLE, while a user or a password that etcd refuses makes it fail with COORDINATOR_AUTH_FAILED. A node with a durability directory and no nodeId generates an id once and stores it in a .narsil-node-id file in that directory, so that the controller recognises the node's copies after a restart. The server binds 0.0.0.0, and because any host on the network can reach that address, listen refuses to bind it without an onRequest hook.
Change the replication factor or the partition count
node.cluster.setReplicationFactor(indexName, factor) changes the number of replicas of each partition beside its primary, from 0 to 255. When you raise the factor, the controller adds replicas, and each new replica copies its partition from the primary. When you lower it, the controller removes the surplus replicas, starting with the ones that lag furthest, and it never removes the primary. Over HTTP, send PUT /indexes/{name}/replication-factor.
node.rebalance(indexName, partitionCount) moves an index onto a new number of partitions, from 1 to 65,536. The controller creates a hidden index with the new partition count and copies every document into it, while the current primaries keep serving reads and writes and forward each new write to the hidden index. Once every current partition has 1,000 or fewer writes still to forward, the controller blocks writes to the index for up to 10 seconds and moves the name onto the new partitions. A write that the cluster receives during that pause fails with PARTITION_REBALANCING_BACKPRESSURE, which the HTTP server answers with status 409, so send the write again once the pause ends. When the hidden index can't catch up within 10 seconds, the controller lifts the block and tries again. After 10 tries, the call fails with ALLOCATION_FAILED, and the index stays on its old partitions. Over HTTP, send POST /indexes/{name}/_rebalance, and the server starts the change as a task.
Take a node out of the cluster
node.decommission() moves every copy off a node before the node leaves. The controller places nothing new on the node, moves the lead of each partition that the node leads to an in-sync replica on another node, and adds each new replica before it drops the old one. The call returns once the node appears in no allocation table and shuts down. The call keeps waiting while no other node can take a copy, so pass signal, such as AbortSignal.timeout(600_000), when you want to stop waiting. Aborting the call leaves the node in the cluster.
With node.shutdown(), the node leaves at once, so the controller treats it as failed. It promotes an in-sync replica for each partition whose primary is on that node, and then it waits for controller.nodeLeftDelayMs, 60,000 milliseconds by default, before it moves the replicas of the node elsewhere. A node that registers again under the same id within that time keeps its replicas and catches up on the writes that arrive while it is away.
Keep writes away from a node that is short of memory
Each node measures its memory once a second. A node counts as full once its process memory passes 90% of the limit that the host or the container sets, or once the old generation of its V8 heap passes 75% of its limit, and it counts as clear again once the two figures fall below 80% and 65%. While a node that holds a copy of an index counts as full, every node refuses inserts and updates to that index with CLUSTER_WRITE_BLOCKED, which the HTTP server answers with status 429. The nodes still accept removes and searches, so you can free memory by removing documents, or you can restart the node with a larger memory limit. With memory: { blockWritesAbove, resumeWritesBelow } in the node configuration, you set the two levels for the process memory, while each heap level takes the smaller of its setting and 75% or 65%.
Find out what a cluster node refuses
A cluster node behind clusterNodeEngine refuses snapshot, restore, importDocumentExport, updatePartitionConfig, registerEmbeddingAdapter, waitForWrites, and the vector maintenance calls with CLUSTER_OPERATION_UNSUPPORTED, which the HTTP server answers with status 501. It exports the documents of an index only while change capture is on for that index. Move an index between clusters with a backup, and read Change capture to learn how to export the documents.
Where to go next
- Read HTTP server for the rest of the routes and for how the server stops.
- Read Persistence and durability for the write-ahead log that a backup needs.
- Read Change capture to follow the writes to an index from a saved position.