A partition is a slice of an index that holds a separate set of terms and statistics. The engine creates an index with the number of partitions in maxPartitions, which is 1 by default, and changes that number only when you rebalance the index. In TypeScript, worker threads hold copies of an index, so that the engine can answer searches off the main thread and leave that thread free for the rest of your application.
On this page, you'll build logs, a program that splits 85,000 log records across four partitions and then reshapes them into eight. The second program, search-logs, spreads searches across worker threads whose copies apply every write. 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.
Split an index across partitions
With partitions.maxPartitions, you set the number of partitions that the engine creates for the index. With maxDocsPerPartition, you set the capacity of the index, which holds at most that number multiplied by the partition count, or 100,000 documents here. The engine refuses a write past that capacity with PARTITION_CAPACITY_EXCEEDED. With watermark, you set the share of that capacity at which the engine emits partitionWatermark, which it does once for each crossing. The program turns worker threads off, so that the engine answers every search in this file on the calling thread. The engine routes each document to a partition by a hash of its ID, and because the hash is the same in every language, all four programs print the same counts.
import { createNarsil } from '@delali/narsil'
const RECORD_COUNT = 85_000
const SERVICES = ['checkout', 'gateway', 'inventory', 'search'] as const
const narsil = await createNarsil({ workers: { enabled: false } })
const warnings: string[] = []
narsil.on('partitionWatermark', (event) => {
warnings.push(`${event.indexName} holds ${event.documentCount} of ${event.capacity}`)
})
await narsil.createIndex('logs', {
schema: { message: 'string', service: 'enum', level: 'enum', timestamp: 'number' },
partitions: { maxPartitions: 4, maxDocsPerPartition: 25_000, watermark: 0.8 },
})
await narsil.insertBatch(
'logs',
Array.from({ length: RECORD_COUNT }, (_unused, position) => ({
id: `log-${position}`,
message: `Request ${position} completed through the ${SERVICES[position % SERVICES.length]} service`,
service: SERVICES[position % SERVICES.length],
level: position % 50 === 0 ? 'error' : 'info',
timestamp: 1_790_000_000_000 + position * 1_000,
}))
)
console.log(
JSON.stringify(
{ partitions: narsil.getPartitionStats('logs').map((partition) => partition.documentCount), warnings },
null,
2
)
)
await narsil.shutdown(){
"partitions": [
21250,
21250,
21250,
21250
],
"warnings": [
"logs holds 85000 of 100000"
]
}The engine spreads the 85,000 records evenly, with 21,250 in each partition. It emits one warning as the load passes 80 per cent of the capacity of 100,000. When a batch goes past the capacity, the engine stores the documents that fit. For example, from a batch of 90 records into a capacity of 80, it stores 80 and reports PARTITION_CAPACITY_EXCEEDED for each of the other 10.
You gain from extra partitions only when separate threads or separate hosts search them in parallel. Inside one thread, extra partitions can slow both inserts and searches without adding any parallel work, so keep maxPartitions low for an engine in a single process.
Reshape the index while it answers searches
updatePartitionConfig raises the limits, while rebalance(indexName, count) moves the documents into the new number of partitions. The engine refuses a rebalance to more than maxPartitions partitions with PARTITION_CAPACITY_EXCEEDED. It refuses a new maxDocsPerPartition with the same code when the new limit leaves no room for the documents that the index already holds.
import { createNarsil } from '@delali/narsil'
const RECORD_COUNT = 85_000
const SERVICES = ['checkout', 'gateway', 'inventory', 'search'] as const
const narsil = await createNarsil({ workers: { enabled: false } })
const warnings: string[] = []
narsil.on('partitionWatermark', (event) => {
warnings.push(`${event.indexName} holds ${event.documentCount} of ${event.capacity}`)
})
await narsil.createIndex('logs', {
schema: { message: 'string', service: 'enum', level: 'enum', timestamp: 'number' },
partitions: { maxPartitions: 4, maxDocsPerPartition: 25_000, watermark: 0.8 },
})
await narsil.insertBatch(
'logs',
Array.from({ length: RECORD_COUNT }, (_unused, position) => ({
id: `log-${position}`,
message: `Request ${position} completed through the ${SERVICES[position % SERVICES.length]} service`,
service: SERVICES[position % SERVICES.length],
level: position % 50 === 0 ? 'error' : 'info',
timestamp: 1_790_000_000_000 + position * 1_000,
}))
)
await narsil.updatePartitionConfig('logs', { maxPartitions: 8, maxDocsPerPartition: 50_000 })
await narsil.rebalance('logs', 8)
const gateway = await narsil.query('logs', { term: 'gateway', limit: 0 })
console.log(
JSON.stringify(
{ partitions: narsil.getPartitionStats('logs').map((partition) => partition.documentCount), warnings },
{ partitions: narsil.getPartitionStats('logs').map((partition) => partition.documentCount), gateway: gateway.count },
null,
2
)
)
await narsil.shutdown(){
"partitions": [
10624,
10625,
10625,
10624,
10626,
10625,
10625,
10626
],
"gateway": 21250
}After the rebalance, each of the eight partitions holds about 10,625 records. The search counts every gateway record, as the same search does before the rebalance. The engine keeps answering searches while a rebalance moves the documents. Meanwhile, it holds new writes in a queue, which it replays in order once the rebalance completes. In one measured test of the TypeScript engine on an 11-core Apple M3 Pro under Node 24, the rebalance takes 0.8 seconds. During the rebalance, the test sends 30 searches with a 10 ms pause after each one, and every search counts 21,250 records. During a rebalance, the slowest searches can take longer than they do at other times, so plan a rebalance for a period of low traffic, or size maxDocsPerPartition at the start so that the index can grow without one.
Search on several threads
This section applies to the TypeScript package and the Go module. The Python package and the Rust crate keep one copy of each index, which every thread of your program searches, so in those languages, a search starts as soon as you call it, without any setting.
Once an index holds promotionThreshold documents, which is 1,000 by default, the TypeScript engine gives it copies on worker threads and sends searches to them. With workers.count, you set the thread budget, which the engine splits between keyword copies and a pool for vector search, so with count: 4, the engine gives each index two keyword copies. With mainCopyQueries: 'none', the engine sends every search to a copy, which is what an engine behind createServer does by default. Under the default 'lone', the engine answers a search from the main copy when no other search is in progress and the index holds at most 50,000 documents, because sending the search to a worker thread and back adds time in that case. The Go module keeps one copy of the index in memory. Once the index passes the same threshold, the module answers its searches from a pool of workers.count goroutines and emits the same workerPromote event.
import { createNarsil } from '@delali/narsil'
const SERVICES = ['checkout', 'gateway', 'inventory', 'search'] as const
const narsil = await createNarsil({ workers: { count: 4, mainCopyQueries: 'none' } })
const copies: number[] = []
narsil.on('workerPromote', (event) => {
copies.push(event.workerCount)
})
await narsil.createIndex('logs', {
schema: { message: 'string', service: 'enum', level: 'enum', timestamp: 'number' },
})
await narsil.insertBatch(
'logs',
Array.from({ length: 2_000 }, (_unused, position) => ({
id: `log-${position}`,
message: `Request ${position} completed through the ${SERVICES[position % SERVICES.length]} service`,
service: SERVICES[position % SERVICES.length],
level: 'info',
timestamp: 1_790_000_000_000 + position * 1_000,
}))
)
await Promise.all(
Array.from({ length: 50 }, (_unused, position) =>
narsil.insert('logs', {
id: `burst-${position}`,
message: `Payment ${position} declined at the gateway`,
service: 'gateway',
level: 'error',
timestamp: 1_790_010_000_000 + position,
})
)
)
await narsil.waitForWrites('logs')
const declined = await narsil.query('logs', { term: 'declined', limit: 0 })
console.log(JSON.stringify({ copies, declined: declined.count }, null, 2))
await narsil.shutdown(){
"copies": [
2
],
"declined": 50
}The TypeScript engine gives the index two worker copies once the load passes 1,000 documents, while the Go module reports its pool of four goroutines, which all search the one copy. In TypeScript, a write returns once the main copy holds it, while each worker copy applies the write afterwards. A search that the engine sends to a copy straight after a burst of concurrent writes can therefore miss some of them. waitForWrites(indexName) resolves once every copy holds every write that completes before you call waitForWrites, which is why the count here includes all 50 writes. With { wait: true } on one write, you get the same guarantee for that write. The Go module holds one copy, so a search there includes every completed write. In Go, WaitForWrites waits only for the writes that the engine holds in its queue during a rebalance.
The TypeScript engine drops the copies of an index after workers.idleTimeoutMs without a read or a write, which is five minutes by default. On the next read or write, the engine loads the copies again while it answers the call from the main copy. When a worker thread dies, the engine emits workerCrash and keeps answering from the other copies. It starts a replacement after a delay that begins at one second and doubles after each failed try, up to a minute. The engine copies the configuration of an index into each worker, but it can't copy a function into a worker. An index with a tokeniser instance or a stop-word function therefore stays on the main thread, and the engine emits workerPromoteFailure for it. To move such an index to workers, register the tokeniser under a name, following the steps on Language support. Then set workers.bootstrapModule to the absolute path or URL of a module that registers the tokeniser in every worker.
Behind createServer, the threads that hold the copies also receive the HTTP requests. Each of those threads answers a search on an index whose copy it holds, while it sends every write to the main thread. Read HTTP server for the server itself.
Where to go next
- Read Persistence and durability for the folders that the engine writes for each partition, and for the directory that several processes can share.
- Read Full-text search for the scoring modes, with which you choose the partition statistics that the engine uses for a query.