Running a worker
Creating an indexer
Every way of running the worker starts fromcreateIndexer in @sonamu-kit/opensearch/postgres.
search/drain.workflow.ts
getPrimaryDatabase must return a Knex instance, not a transaction. The worker opens read-only snapshots from that pool, and Knex ignores the isolation level and the read-only option on a nested transaction. If it returns a transaction, the drain fails with SearchConfigurationError.
createIndexer opens no connection and starts no timer; work begins when you call drainOnce() or start(). One indexer runs one drain at a time. While its start() loop is draining or another drainOnce() has not finished, an overlapping drainOnce() returns at once, without I/O, a report whose outcome is busy. The limits (concurrent bulks, maxInFlightBytes, claim size) apply per drain, so several indexers in one process multiply them.
start and stop
start({ pollIntervalMs, signal }) starts the resident loop and returns a handle at once. An indexer has one loop; calling start again returns the same handle.
- After a full claim the loop goes straight to the next drain. Otherwise it waits for the longer of
pollIntervalMsand the remaining cooldown. - After a failed drain the state becomes
degradedand the loop waits a backoff before retrying. Configuration errors, a missing schema, and a store binding mismatch do not heal until an operator fixes them, so for those it waitsretryMaxDelayMs.
stop({ deadlineMs }) does the following, in order:
- Sets the state to
stopping. From then ondrainOnce()is rejected withSearchStoppingwithout any I/O. - Waits up to the deadline for in-flight drains to finish.
- At the deadline, aborts them. Documents not yet sent are released without budget; documents sent with an unknown outcome are left unrecorded until their lease expires. A drain still running
3 × statementTimeoutMsafter the abort is not waited for. - Deletes the heartbeat row and closes the client wrapper. If
ownsClientistrue, the SDK client is closed too.
{ drained, abortedInFlight, abandonedDrains, clientClosed, elapsedMs }. abandonedDrains counts the drains it stopped waiting for; their documents’ leases expire or are released. stop() therefore returns within the deadline plus 3 × statementTimeoutMs. A second stop returns the same promise, and aborting the signal passed to start equals stop({ deadlineMs: 0 }).
Documents not finished by the deadline are not lost: another worker processes them after their lease ends. If the orchestrator kills the process before the deadline, though, the cleanup steps never run. The recommended 30-second deadline equals Kubernetes’ default termination grace period, so set terminationGracePeriodSeconds longer than that.
In a Sonamu server
createSearchLifecycle from @sonamu-kit/opensearch/sonamu starts and stops the worker and closes clients along the Sonamu server’s lifecycle.
search/worker.ts
onStart and onShutdown from server.lifecycle in sonamu.config.ts.
sonamu.config.ts
- Sonamu calls listen, starts the workflow workers, then calls
onStart. On shutdown it callsonShutdown, cleans up workflows, then callsSonamu.destroy. Paths that callSonamu.destroy()themselves, such as CLIs and tests, must callonShutdown()first. onStartapplies Sonamu’s default locale, awaitssynchronization.initialize(), and starts the worker ifworker.enabledistrue. It runs after listen and does not guarantee readiness. To cover writes that arrive in between, also use theonReadyhook orexpectedStoreIdfrom Setup. Until search is ready, search APIs getSearchNotReadyorSearchUnavailable; other APIs are unaffected.- Whether a process runs the worker is set with
worker.enabled, never inferred. Withfalse,onStartonly initializes the synchronization; the example runs the worker only whereSEARCH_WORKER=1. Keep itfalsein Sonamu test mode. - The lifecycle creates the worker’s own client from the
worker.clientoptions and closes it when that worker stops. To share one SDK client with the query handles, giveworker.clientacreateClientthat returns the shared client andownsClient: false. The query handles’SearchClientwrapper itself cannot be handed to the worker: when the worker stops it closes the wrapper, and later searches getSearchStopping. - The lifecycle closes a wrapper passed in
clientswhen a hot-reload replacement does not pass it again.onShutdownstops the running worker (closing the worker’s client) and closes only retired generations’ wrappers. It leaves the latest generation’s wrappers open, because that generation’s query handles still hold them and use them again ifonStartruns afteronShutdownin the same process (tests, a development server restart). At process exit the application closes them afteronShutdown, asshutdownSearchdoes. - A lifecycle can be stopped and started again in one process.
getSearchLifecycleStatus(name)reads a lifecycle’s status by name without creating a slot, a connection, or a timer, so a health check does not have to import the lifecycle module. The example below builds a health-check value from it, including the targets whose fence was lost; itsstateisabsentwhen this process never created a lifecycle of that name.
search/worker.ts
Hot reload
Lifecycles with the samename share one process-wide slot. When the development server re-evaluates the module that creates the lifecycle, the new lifecycle stops the previous worker within stopDeadlineMs (deleting its heartbeat row, releasing its leases, closing its client) and then starts its own. The slot never holds more than one worker, and if the definitions changed, the new worker uses the new ones. sonamu.config.ts is not re-evaluated, so Sonamu keeps calling the first generation’s onStart and onShutdown; both act on the whole slot, so that is correct. Nothing depends on import.meta.hot.dispose.
When initialization fails
Ifinitialize() fails with a retryable error, such as a failed database connection, onStart does not reject. It sets the state to degraded, retries with a delay growing from 1 to 30 seconds (change it with initializeRetry), and starts the worker anyway. Meanwhile markChanged fails with store-identity-uninitialized, so domain transactions do not commit. Once initialization succeeds, the state becomes running.
For errors that retrying cannot fix, such as configuration errors, a missing schema, or a store mismatch, onStart rejects with that error and the state is failed. The lifecycle’s status() and getSearchLifecycleStatus(name) show the state, the generation number, whether initialization finished, the worker status, the report of the last stopped worker, and the last error.
In a separate process
The worker can run in a process other than the API server. That process does not start Sonamu: it creates the client, the synchronization handle, and the indexer itself, callsstart(), and on a termination signal awaits stop() before exiting. It connects to the database with the worker role, and its namespace must match the API processes. Without Sonamu, its definitions must be defineSearch definitions that read only through the snapshot (context.trx); the model methods of defineSonamuSearch need Sonamu’s database configuration.
search/standalone-worker.ts
synchronization.initialize()beforestart()checks that the primary and the search schema are reachable; if it fails, the process ends without starting the loop.- On SIGTERM or SIGINT the process stops the worker with
RECOMMENDED_WORKER_STOP_DEADLINE_MSas described under “start and stop”, so set the orchestrator’s termination grace period longer than that.stop()also closes the client wrapper.
node standalone-worker.main.js) passes in the application’s logger and metrics.
search/standalone-worker.main.ts
From a scheduled workflow
Instead of a resident loop, a scheduled workflow can drain the backlog. It usesdrainIndexer and MAX_DRAINS_PER_RUN from the indexer example above.
search/drain.workflow.ts
- The module creates one indexer and every run reuses it. The factories do not connect, so creating them at module level is fine, and the workflow does not depend on handles created in
onStart, which may run later. - If the previous run is still draining, the next run’s
drainOnce()getsbusyand the run ends. Overlapping runs therefore never double the claims, snapshots, or bulks, and the limits hold for the whole process. - A run drains at most
MAX_DRAINS_PER_RUNtimes and ends early when nothing was claimed or a cooldown is active. In this form the heartbeat row exists only duringdrainOnce(). - Tasks may repeat a run. Leases prevent concurrent processing of the same document, and external versions keep an old revision from overwriting a newer one.
- It can run alongside a resident worker.
Limits
Every field is required. SpreadRECOMMENDED_WORKER_LIMITS and override only what you need; an object with a missing field is rejected with invalid-worker-limits. createIndexer checks the relationships in the last column and throws SearchConfigurationError with the details.reason shown.
Why each relationship holds:
heartbeat-exceeds-half-lease: the lease must survive one missed heartbeat.timeout-exceeds-lease: a stage that uses its whole time limit must still end within one lease, so no other worker takes the same documents while heartbeats are stalled.lease-too-short-for-drain: the worker sends a bulk only when the request can finish before the documents’ lease ends, so the lease must leave room for one request between heartbeats.retry-age-below-base-delay: otherwise the delay of the first retry alone exhausts the budget.isolation-budget-too-small: with fewer calls, one bad document in a full claim may never be found, and its neighbors in the same half can be released forever.in-flight-below-bulk: with less, the worker cannot hold one large document.fence-interval-below-request-timeout: one fence advance, a single remote write, must fit within the renewal interval.
workerBounds from the same limits (Operations).
Memory and time bounds
While one claim is processed, JavaScript heap growth stays roughly within this bound, where C ismaxConcurrentBulkRequests:
2 × maxInFlightBytes + (3 + C) × maxBulkBytes + 8 MiB
The first term covers the held bytes and the objects the projector returned for a chunk; the second covers joining request bodies and the working copies of one document. On the recommended values it is about 65 MiB. An integration test compares heap growth on a claim of large documents with this bound. Buffer memory lives outside the heap and is not included.
One drain ends within this time, where P is projectionTimeoutMs, R is requestTimeoutMs, and S is statementTimeoutMs:
leaseDurationMs + max(P + S, R + 3S) + 16S
Once a lease length has passed since the claim started, the worker starts no new projection, document validation, bulk send, or conflict check, and releases the remaining documents. The rest of the formula covers the one piece of work already started at that point and the settlement statements. On the recommended values it is 4 min 5 s (245 s). One very large document can exceed it by its own processing time.
Report, events, and status
Drain report
TheDrainReport that drainOnce() returns holds only numbers and stable codes and is not localized.
Events
onEvent receives these events. Every drain attempt produces exactly one drain or error event. Events carry codes and identifiers only, never document content, and exceptions thrown by the listener are ignored. The last column says when a person has to act; alert thresholds are in Operations.
The listener below turns events into logs and counters. Counter labels use only fields with a bounded set of values, such as
outcome, code, and reason; targetId and documentId go to logs only. When the store binding does not match, the error event’s code is SEARCH_STORE_MISMATCH and its reason says why.
search/worker-events.ts
Status
A worker handle’sstatus() shows the state (idle, running, degraded, stopping, stopped), the last report, the last error (code, key, params, and a message rendered in the package locale when status() is read), the number of consecutive failures, paused targets, targets whose fence was lost (fenceLostTargets), and targets it does not handle (unsupportedTargets). A non-empty unsupportedTargets means the deployed workers’ definitions do not match the registered targets.
The state becomes degraded after a failed drain or when a client or database cooldown starts. It stays degraded after the cooldown has passed until a request in that scope succeeds once. A drain that claimed nothing is no evidence of recovery, so an idle worker stays degraded until its next successful bulk or snapshot. Every change arrives as a state event, so there is no need to poll status(); the listener above updates these gauges on each one.
search/worker-events.ts
Heartbeat rows
Each worker keeps one row inworker_heartbeats and refreshes it every heartbeatIntervalMs. The administrative handle’s inspect shows these rows.
- The row of a worker run by
start()is deleted bystop(). - The row of a caller that only calls
drainOnce()withoutstart()(a scheduled workflow, an administrative CLI) exists only for that call. - The row of a killed worker drops out of
inspectonce it has not been refreshed for 24 hours, and is deleted the next time a live worker writes its heartbeat. - A worker that drains less often than every 24 hours disappears from
inspectbetween drains and reappears with its next heartbeat.
What the worker does not do
- It does not mark documents, so it needs no store identity.
- It does not create indexes. Bulk requests go only to the write alias, with
require_alias=true. If the alias is missing, OpenSearch rejects the request with 404 instead of creating an index, and the worker pauses the target. The worker needs no permission to create indexes. - It does not resume paused targets or resend quarantined documents. Both wait for an administrator (Recovery runbooks).
- It does not spend retry budget on outages. Problems of the cluster, the network, credentials, or a whole target are released without budget, and time spent waiting out an outage is not counted (see “Retry budget and cooldown”).
- It does not take a 409 as success. It verifies the conflict against the index and the ledger first (see “Version conflicts (409)”).
- It does not store cooldowns. They live only in the process; an indexer’s
start()loop and a directdrainOnce()see the same cooldown. - It does not throw when it loses a target fence, and the fence does not block writes. It stops sending to that target and keeps indexing the others (see “Target fence”).
- It does not decide anything from heartbeat rows. No statement blocks or decides on them: retirement looks at the leases on intents, and cutover at the backlog count.
- It does not clean up. Ledger rows and the tombstones of deleted documents are never deleted (known limits).
What one drain does
drainOnce({ signal }) works through these steps and returns a report.
- Gate: if the worker is stopping, it fails with
SearchStopping. If another drain of the same indexer is running, it returns abusyreport; during a client or database cooldown it reads nothing and returns acooldownreport. - Targets and store binding: it reads the active targets with writes enabled and, in the same statement, checks that this database is the one the store was recorded in. If the binding does not match, it writes and sends nothing and ends with
SearchStoreMismatch(Recovery runbooks). It does not claim for targets whose fence was lost, skips targets in cooldown, and leaves alone targets with no matching(key, fingerprint, hash version)definition, reporting them inunsupportedTargets. A drain that ends here for lack of work still renews fences that are due. - Claim: it takes up to
maxDocumentsPerClaimintents with a lease token. Every later write is checked against this token, so a worker that lost its lease cannot change someone else’s rows. Intents are ordered by the later of their arrival and their last claim, so documents re-marked over and over on one target cannot starve another target’s documents. - Lease extension: it extends the lease every
heartbeatIntervalMs. - Per-target processing: for each target it reads the ledger revisions in a primary snapshot and runs the projection, splitting a large claim into several snapshots (chunks) to fit
maxInFlightBytes. It checks the fence, packs the results into NDJSON requests of at mostmaxBulkBytes, checks before each request that the target is still writable, and sends to the write alias with external versions and a fence action in front. It classifies the response per document and records each as done, retry, release, or quarantine.
statementTimeoutMs. Past that, the server cancels it and the worker treats it as an infrastructure failure (SearchTimeout) without using retry budget, so a worker does not queue behind a migration’s table lock.
When acknowledgement overlaps a new mark
When the worker records an outcome (a success acknowledgement, a counted failure, a release), it neither waits on nor skips an intent row that a domain transaction holds. If a transaction re-marking the same document is open at the moment of acknowledgement, the worker releases that revision’s lease at once and counts it underreleased. The next claim picks up the new revision as soon as that transaction commits, so editing a document right after it is indexed adds no wait for a lease to expire. Lease extension does not skip such rows either. skippedLocked counts only rows whose runtime state another package transaction, such as an administrative operation, holds.
Claim cost
A claim reads intents without runtime state in index order and claimable intents with runtime state separately, then merges them; it neither scans nor sorts the whole backlog. The integration tests check, at 200,000 intents, that the plan has no sequential scan ofdeliveries and that its sorts are bounded by the candidate count. They do not measure time. Measured timings, and how quarantined intents slow every claim, are under known limits in Operations.
From marking to indexing
A commit is usually indexed within the poll interval plus about a second. For a healthy worker with no backlog the ceiling ispollIntervalMs + 2 × (projectionTimeoutMs + requestTimeoutMs): one drain already running at commit, one pause, and the drain that picks the mark up. On the recommended values this ceiling is longer than the lease, so treat it as a ceiling, not an expectation.
Outcomes
Each document ends in one of the outcomes below. What decides it is what failed, not the HTTP status. Problems of the cluster, the network, credentials, or a whole target are not the document’s fault and use no budget; only a problem specific to this revision of this document uses budget or leads to quarantine. A response the worker cannot interpret counts as neither success nor the document’s fault, and the document is released without budget.- Quarantine stops only that revision of that document. A quarantined intent is not claimed again; marking the same document again delivers the new revision with a fresh budget. Resending after fixing the cause is in Recovery runbooks.
- Target pause stops the whole target until an administrator checks the cause and resumes it (Recovery runbooks). A retiring or retired target never goes back to paused.
- A bulk rejected as a whole (request 400, 413) wrote nothing, so the worker splits the request in halves and resends them to find the document that causes it. When a single-document request is rejected, that document is quarantined. Each group may split and resend up to
maxIsolationCallsPerBatch - 1times; documents not settled within that are released without budget, and the next drain continues the search. invalid_idarises only for an ID that reached the ledger withoutmarkChanged, such as a manual write;markChangedrefuses such IDs up front.
Version conflicts (409)
OpenSearch rejects with 409 when the same revision is sent twice or a newer revision arrived first. The worker does not take a 409 as success: it reads the document’ssonamu_meta from the physical index, reads the ledger again, and compares. With M the revision it sent, V the indexed revision, and L the current ledger revision:
V = Mwith the same hash version, hash, and deleted flag is a verified duplicate.M < V ≤ Lmeans a newer revision is already indexed, so the delivery is recorded as done.V = Mwith a different hash means the projection produced different content for the same revision. That revision is quarantined and ahash-mismatchevent is emitted.V = Mwith a different hash version means a worker from a package version with different canonicalization rules indexed that revision first. The document is released without budget instead of quarantined, and ahash-version-mismatchevent is emitted. It does not settle on its own and stays pending until it is marked again (a higher revision) or the target is rebuilt.V > L,V < M, or the document sitting in another index means the index and the ledger disagree, so the target is paused (revision_divergence).- If the reads fail or the document is missing, the worker does not decide and releases the document without budget.
Retry budget and cooldown
Retry budget
The budget is counted per intent row and per attempted revision.- A counted failure raises
attemptsby one and adds toretry_age_msthe time that processing took plus the delay before the next attempt. The delay isretryBaseDelayMs × 2^attempts, capped atretryMaxDelayMs, then randomly reduced by up to half. - When
attemptsreachesmaxRetryAttemptsorretry_age_msreachesmaxRetryAgeMs, the revision is quarantined and its failure record getsexhausted. - A newer revision does not inherit the failure count of an older one; it starts from zero.
- An uncounted release neither raises nor clears
attemptsandretry_age_ms.
retry_age_ms is not the time since the first attempt but the sum of actual processing time and scheduled delays. A long outage therefore does not drain the budget: outage-shaped failures are releases that raise no count, and time spent waiting during an outage is not added to retry_age_ms. A first attempt long ago does not by itself lead to quarantine.
Cooldown
Infrastructure-shaped failures start a cooldown for a scope: request-level failures for the whole client, item-level failures for that target, and projection-side outages for the database. No work in that scope is claimed during the cooldown. Its length isretryBaseDelayMs × 2^consecutive failures (at most retryMaxDelayMs) with a random reduction; 401 and 403 start at retryMaxDelayMs. A successful response in the same scope clears it.
A release never carries this worker’s cooldown over to the document. The releasing worker does not take the document again right away because of its own cooldown, but other workers can take it at once unless the release left a shared delay on the runtime row. That delay depends on the cause:
Slow documents
One projection call must finish withinprojectionTimeoutMs. When it times out, the worker splits the IDs in halves and reruns each half in a new snapshot. A document that times out on its own uses budget only if one of these holds:
- Another document in the same call finished its projection.
- Another projection completed on the same primary after this document’s previous timeout.
SearchTimeout, details.reason projection-timeout-unproven). If two or more halves split at one step all time out without evidence, splitting stops there. A document that is always slow therefore uses up its budget and is eventually quarantined while other work shows the database is healthy, and no document is quarantined when the whole database is slow. When a single slow document is all that is pending, no evidence appears and each worker tries it once per database cooldown (known limits).
Target fence
The store binding check recognizes a template copy or a dump restored elsewhere, but not a physical copy (base backup, snapshot restore, point-in-time recovery, replica promotion), which is byte-identical to its source, recorded origin included. The target fence covers that case. Each target’s index holds one reserved document (__sonamu_fence__) whose OpenSearch version is the fence epoch. This database records the epoch it owns in target_fences, and the workers advance the epoch every fenceRenewIntervalMs. A store that finds the fence moved by someone else stops sending to that target.
How it works:
- Every bulk to a target starts with a fence action that writes the committed
(epoch, nonce)withexternal_gte. The action is at most 245 bytes, reserved in advance frommaxBulkBytesandmaxInFlightBytes. If the fence item in the response is 200, nothing changed. If it is 409, the remote is ahead, and the worker reads the fence again and compares (an advance by another worker of the same database is not a loss). If it is 201, the fence document was missing, so the index was recreated, and the target is lost asregressed. - Before a process first sends to its targets, it reads the fences of the targets that need checking with one
POST /_mget. A target this process has neither verified nor sent to for longer thanfenceRenewIntervalMsis read again before the next send. - Renewal: when a target’s fence is due (interval × (1 + j), with j fixed per process in [0, 0.25)), one worker among all workers of this database takes the renewal in PostgreSQL, writes epoch + 1 to OpenSearch, and commits. Renewal runs on drains with no work too, and covers targets with no work and targets this worker cannot project. That is how an idle production database still defeats a copy that starts later.
- A target with no fence on either side (an index created while the schema was at version 1, or a new target) starts at epoch 1 before its first send. An advance whose response was lost is completed with the same nonce, so anyone may resend it safely.
When a fence is lost, the worker records the loss in
target_fences, emits a target-fence-lost event once per process per target per loss, and adds the target to status().fenceLostTargets. It releases the target’s claimed documents without retry budget or delay and stops claiming and renewing that target; other targets keep indexing. This lasts until confirmStoreOwnership runs on the rightful owner or adoptCopiedStore on the copy (Recovery runbooks).
How much the losing side still writes
A process that is not sending learns of the loss at its next renewal or when it reads the fence again before its next send, whichever comes first.
Cost
The integration tests count the requests and fence statements for the first three rows. The renewal cost does not depend on the number of workers, but it means the workers of a database write to OpenSearch once per target per renewal interval even with no work. While OpenSearch is down, that write is a request-level failure that enters the client cooldown, so a worker running only empty drains also goes into cooldown and the
degraded state.
Next steps
Searching
Query handles, cursors, permission re-checks
Recovery runbooks
Handling paused targets and quarantined documents