Operations

Observability

Read what each index stores in memory and on disk, report the memory that the engine uses, alert on the work that the engine does in the background, and probe a server from a load balancer.

The engine reports what it stores through three calls, listIndexes, getPartitionStats, and getMemoryStats, while it reports the work that it does in the background through events. On this page, you'll build monitor, a program that loads 2,500 support tickets into an index that the engine saves to disk. The program then prints what the index contains and how much memory the engine uses, before it sends the events of the engine to an alert function. Each code block below contains the whole file, where green lines show the lines that you add at each step and struck lines show the lines that you remove.

Read what each index contains

listIndexes returns one entry for each index, with its document count, its partition count, and whether it is open. getPartitionStats returns one entry for each partition, with the estimate of the engine for the memory that the partition takes up. For an index that the engine saves to disk, every engine adds two sizes to each partition and to getStats. savedBytes is the size of the files that the latest checkpoint lists, while logBytes is the size of the write-ahead log. The Go module returns each size as an Optional[int64], which encoding/json prints as a number, or as null for an index that exists only in memory.

import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
 
const narsil = await createNarsil({
  durability: { directory: await mkdtemp(join(tmpdir(), 'support-desk-')) },
  workers: { count: 4 },
})
 
await narsil.createIndex('tickets', {
  schema: { subject: 'string', priority: 'enum' },
  partitions: { maxPartitions: 2, maxDocsPerPartition: 1_500, watermark: 0.8 },
})
 
await narsil.insertBatch(
  'tickets',
  Array.from({ length: 2_500 }, (_unused, position) => ({
    id: `ticket-${position}`,
    subject: `Refund request ${position}`,
    priority: position % 3 === 0 ? 'high' : 'low',
  }))
)
 
await narsil.checkpoint('tickets')
 
console.log(JSON.stringify({ indexes: narsil.listIndexes(), partitions: narsil.getPartitionStats('tickets') }, null, 2))
 
await narsil.shutdown()
{
  "indexes": [
    {
      "name": "tickets",
      "documentCount": 2500,
      "partitionCount": 2,
      "language": "english",
      "state": "open",
      "reopenCount": 0
    }
  ],
  "partitions": [
    {
      "partitionId": 0,
      "documentCount": 1250,
      "estimatedMemoryBytes": 223497,
      "savedBytes": 203827,
      "logBytes": 8
    },
    {
      "partitionId": 1,
      "documentCount": 1250,
      "estimatedMemoryBytes": 223493,
      "savedBytes": 203823,
      "logBytes": 8
    }
  ]
}

Every engine spreads the 2,500 tickets evenly, with 1,250 in each partition. Every panel shows the same saved sizes, because the four engines write the same file format, in which the checkpoint takes up about 204 KB for each partition. Each log is 8 bytes, which is the size of the empty segment that the engine opens once the checkpoint covers every earlier write. savedBytes changes only when the engine commits a checkpoint, so the engine reports the same figure for an unchanged index after a restart. For that reason, use savedBytes when you bill for disk space or alert on it. On the Persistence and durability page, you can see how both sizes change as the engine writes to an index.

Each engine computes estimatedMemoryBytes with a formula that leaves out the overhead of its runtime, which is why the panels show different figures. Use the estimate to compare indexes inside one process, and size a host from the process figures in the next step. state is closed once the engine releases an index from memory under the lifecycle limits. reopenCount is the number of times that the engine loads the index again, counted from the start of the engine.

Report the memory that the engine uses

getMemoryStats returns the figures for the whole process, along with the sum of the estimates of the engine. The TypeScript and Go engines report the heap of the process, the heap of each worker thread or search goroutine, and whether each index has worker copies. The Python package and the Rust crate report the resident memory of the process, the sum of the estimates, and the number of open indexes.

import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
 
const narsil = await createNarsil({
  durability: { directory: await mkdtemp(join(tmpdir(), 'support-desk-')) },
  workers: { count: 4 },
})
 
await narsil.createIndex('tickets', {
  schema: { subject: 'string', priority: 'enum' },
  partitions: { maxPartitions: 2, maxDocsPerPartition: 1_500, watermark: 0.8 },
})
 
await narsil.insertBatch(
  'tickets',
  Array.from({ length: 2_500 }, (_unused, position) => ({
    id: `ticket-${position}`,
    subject: `Refund request ${position}`,
    priority: position % 3 === 0 ? 'high' : 'low',
  }))
)
 
await narsil.checkpoint('tickets')
 
console.log(JSON.stringify({ indexes: narsil.listIndexes(), partitions: narsil.getPartitionStats('tickets') }, null, 2)) 
const memory = await narsil.getMemoryStats() 
 
console.log(
  JSON.stringify(
    {
      estimatedIndexBytes: memory.estimatedIndexBytes,
      openIndexCount: memory.openIndexCount,
      closedIndexCount: memory.closedIndexCount,
      workerCopies: memory.workerCopies,
      workerThreads: memory.workers.length,
    },
    null,
    2
  )
)
 
await narsil.shutdown()
{
  "estimatedIndexBytes": 446990,
  "openIndexCount": 1,
  "closedIndexCount": 0,
  "workerCopies": [
    {
      "indexName": "tickets",
      "scaledOut": true,
      "reloadCount": 0
    }
  ],
  "workerThreads": 2
}

Each program prints only the figures that are the same every time that you start it, because the process figures depend on the host. estimatedIndexBytes is the sum of the partition estimates from the first step. In TypeScript, the engine gives half of its budget of four threads to keyword copies, so workers contains a heap report for each of those two threads, each of which loads a copy of tickets. The Go module reports one entry for each of its four search goroutines, which all search the one copy of the index.

The TypeScript engine takes the process figures from Node, so process.heapLimit is the size that the heap can reach before Node ends the process. Node sets that limit from --max-old-space-size, from --max-old-space-size-percentage, or from the memory that the host reports. In each workerCopies entry, reloadCount is the number of times that the engine loads the copies again after it drops them under workers.idleTimeoutMs.

Alert on the work that the engine does in the background

The engine emits an event for the work that it does apart from your calls. The engine reports a failure in that work only through the event, because none of your promises depends on that work. For each event that you want to alert on, register a handler with on before the engine starts the work behind that event. In the last column, you can see the packages that emit each event.

EventThe engine emits it whenPackages
writeA call changes what a read returns from an index.All four
durabilityErrorA write to the durability directory fails.All four
partitionWatermarkThe documents in an index reach the share of its capacity that you set with watermark.All four
partitionRebalanceThe engine finishes moving an index onto a new partition count.All four
analysisRebuildThe engine starts, completes, or fails a rebuild of the terms of an index.All four
layoutUpgradeThe engine starts, completes, or fails the rewrite of an index in the on-disk layout of release 0.3.All four
querySuggestionsBuild, querySuggestionsWarningA build of popular query suggestions changes state, or the engine works around a problem with them.All four
heapPressureThe heap reaches nine tenths of its limit during a write or a load.TypeScript and Go
workerCrashA worker thread or a search goroutine fails, and the engine answers its searches elsewhere.TypeScript and Go
workerPromoteThe engine gives an index worker copies, or the Go module starts its search goroutines.TypeScript and Go
workerPromoteFailureThe engine can't give an index worker copies, so the engine searches the index on the main thread.TypeScript
checkpointHeldThe engine delays every checkpoint of an index with a vector field until a failed partition of the index recovers.TypeScript
invalidationErrorAn invalidation adapter fails to publish a change, or a process fails to reload a changed partition.TypeScript

In this step, the program sends the events that each package emits to an alert function, which writes one JSON line for each event.

import { mkdtemp } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createNarsil } from '@delali/narsil'
 
const narsil = await createNarsil({
  durability: { directory: await mkdtemp(join(tmpdir(), 'support-desk-')) },
  workers: { count: 4 },
})
 
const alert = (event: string, detail: Record<string, unknown>): void => { 
  console.log(JSON.stringify({ event, ...detail }))
}
 
narsil.on('durabilityError', (payload) => alert('durabilityError', { message: payload.error.message }))
narsil.on('heapPressure', (payload) => alert('heapPressure', payload))
narsil.on('workerCrash', (payload) => alert('workerCrash', { workerId: payload.workerId, indexNames: payload.indexNames }))
narsil.on('workerPromote', (payload) => alert('workerPromote', { workerCount: payload.workerCount }))
narsil.on('partitionWatermark', (payload) => alert('partitionWatermark', payload))
 
await narsil.createIndex('tickets', {
  schema: { subject: 'string', priority: 'enum' },
  partitions: { maxPartitions: 2, maxDocsPerPartition: 1_500, watermark: 0.8 },
})
 
await narsil.insertBatch(
  'tickets',
  Array.from({ length: 2_500 }, (_unused, position) => ({
    id: `ticket-${position}`,
    subject: `Refund request ${position}`,
    priority: position % 3 === 0 ? 'high' : 'low',
  }))
)
 
await narsil.checkpoint('tickets')
 
const memory = await narsil.getMemoryStats() 
 
console.log(
  JSON.stringify(
    {
      estimatedIndexBytes: memory.estimatedIndexBytes,
      openIndexCount: memory.openIndexCount,
      closedIndexCount: memory.closedIndexCount,
      workerCopies: memory.workerCopies,
      workerThreads: memory.workers.length,
    },
    null,
    2
  )
)
 
await narsil.shutdown()
{"event":"workerPromote","workerCount":2}
{"event":"partitionWatermark","indexName":"tickets","documentCount":2500,"capacity":3000,"partitionCount":2}

Every engine emits one partitionWatermark once the index reaches 80% of its capacity of 3,000 tickets. The engine emits the event again only after the count drops below the mark or after you raise the capacity, so alert writes one line for each crossing. The TypeScript engine loads two worker copies once the index contains 1,000 tickets, while the Go module starts its four search goroutines at the same point. In those two panels, you can therefore also see a workerPromote line. In the Python and Rust panels, you can see only the watermark line, because neither package has worker events.

Alert before the heap fills up

The TypeScript engine measures the heap after each write and each load, and emits heapPressure once the heap reaches nine tenths of heapLimit. It also measures the heap after each chunk inside a batch, so the engine emits the event partway through a large batch that crosses the line. A handler for the event can delay the next batch, but the engine goes on writing the batch that crosses the line. On a host where the heap is close to its limit, keep each batch small for that reason. Set --max-old-space-size or --max-old-space-size-percentage on any host where you rely on the event. Without either flag, the engine compares the heap with the headroom that V8 reports, which is higher than the real ceiling, so on a small default heap, the process can end before the engine emits the event.

The Go module compares the live objects on its heap with the memory limit that you set with GOMEMLIMIT or debug.SetMemoryLimit. In a process without a limit, the module checks nothing, so set a limit wherever you rely on the event or on the write block below. Both engines emit the event once for each crossing and arm it again once the heap falls back below eight tenths of the limit.

Refuse writes before memory fills up

Every engine refuses an insert or an update with MEMORY_WRITE_BLOCKED once its memory passes the memory.blockWritesAbove share of its limit, which is 0.9 by default. The engine accepts those writes again once the memory falls below memory.resumeWritesBelow, which is 0.8 by default. The engine accepts removals, searches, and reads the whole time, so you can remove documents to bring the engine back under the resume level. The engine refuses the whole of a batch that you send while the engine is full.

import { createNarsil } from '@delali/narsil'
 
const narsil = await createNarsil({ memory: { blockWritesAbove: 0.85, resumeWritesBelow: 0.75 } })
 
await narsil.shutdown()

The engines measure different figures against different limits:

  • The TypeScript engine measures the memory of the process against the limit of the container or the memory of the host, and it measures its heap against the heap limit. On Node.js, it blocks writes once the heap passes the smaller of blockWritesAbove and 0.75 of its limit, and it resumes them below the smaller of resumeWritesBelow and 0.65. It caps both settings because V8 stops a process after four full collections in a row, after each of which the old generation fills at least 0.8 of its limit.
  • The Python package and the Rust crate measure the resident memory of the process against the limit of the container or the memory of the machine.
  • The Go module measures its heap against the limit that you set with GOMEMLIMIT or debug.SetMemoryLimit, and in a process without a limit, it blocks no writes.

A browser reports no memory limit, so the TypeScript engine accepts every write in a browser without a memory check.

Probe a server

A server from createServer answers GET /livez with 200 while the process serves HTTP. It answers GET /readyz and GET /health with 200 once the engine is ready, and with 503 once shutdown begins, so point the health check of a load balancer at /readyz. The server answers those probes, along with /version and /capabilities, without calling the onRequest hook, so a load balancer can call them without a token.

GET /version returns the name and the version of the server, in a body such as {"name":"narsil","version":"0.4.1","gitSha":null,"dirty":false,"vectorSearch":"native"}. A server from a default createServer call reports the version of the installed @delali/narsil package, even from a bundled build. When you pass a version in the build option, the server reports that version in place of the package version. gitSha and dirty are null and false until you set them in the same option.

The server calls the hook for the routes that return the figures of the engine, as it does for any other route. GET /stats/memory returns the report from getMemoryStats with one more field, requestThreads, which is the number of worker threads that receive requests and answer searches from their copies. On an 11-core machine with the default worker budget, requestThreads is 8. GET /indexes/{name}/stats and GET /indexes/{name}/partitions return the counts, the memory estimate, and the saved and log sizes for one index. A server in front of a cluster node answers GET /cluster/health with the health of the cluster and GET /metrics with its figures in the Prometheus text format, while a server in front of a single engine answers both routes with 501 CLUSTER_OPERATION_UNSUPPORTED. Read Cluster for both routes.

Where to go next