NATS JetStream
The optional Level 3+ durable event transport — how Anvio's EventBus wires into a single JetStream stream.
4 min read
NATS is opt-in, Level 3+. Anvio's default event transport (Level 1–2) is the in-process Local Event Bus — no NATS server, no network hop, no external dependency. Only switch to NATS when you need durable, replayable, or multi-process event delivery (e.g. a separate worker process consuming events from the api process). See Progressive Enhancement.
Why NATS
Per ADR 0005: NATS JetStream was chosen for being lightweight, Kubernetes-native, and providing durable messaging without the operational weight of Kafka. It backs Level 3 ("multi-user production") and Level 4 ("organization scale, distributed") in Anvio's progressive enhancement model.
Enabling it
Set events.provider: nats in workspace/anvio.yaml:
spec:
events:
provider: nats
# url: nats://localhost:4222 # optional override; falls back to NATS_URLAnd set the connection string:
NATS_URL=nats://localhost:4222createEventBus() (packages/events/src/local-event-bus.ts) is the single switch point:
export async function createEventBus(
provider: string,
options: { url?: string; source: string },
): Promise<EventBusLike> {
if (provider === 'nats') {
const { EventBus } = await import('@anvio/events');
const bus = new EventBus({ url: options.url ?? 'nats://localhost:4222', source: options.source });
await bus.connect();
return bus;
}
return new LocalEventBus(options.source);
}Everything downstream — every controller, every channel adapter, every event publisher in the platform — talks to the EventBusLike interface, so switching providers requires zero code changes elsewhere. This is exactly how createPlatform() (packages/platform/src/index.ts) wires it:
const eventBus = await createEventBus(spec.events.provider, {
url: spec.events.url ?? process.env.NATS_URL,
source: '/anvio/platform',
});Stream topology
Anvio uses a single JetStream stream named ANVIO, subscribed to the entire anvio.> wildcard subject space:
// packages/events/src/event-bus.ts
const STREAM_NAME = 'ANVIO';
private async ensureStream(): Promise<void> {
const jsm = await this.nc.jetstreamManager();
try {
await jsm.streams.info(STREAM_NAME);
} catch {
await jsm.streams.add({ name: STREAM_NAME, subjects: ['anvio.>'] });
}
}The stream is created lazily on first connect() if it doesn't already exist (streams.info() throws → streams.add()). Every event subject in Event Model (anvio.session.started.v1, anvio.agent.run.requested.v1, etc.) is captured by the single anvio.> wildcard — there's no per-domain stream split.
Two delivery modes
EventBus (packages/events/src/event-bus.ts) exposes both a durable, JetStream-backed path and a fire-and-forget core NATS path:
Durable: publish() / subscribe()
async publish<T>(subject: EventSubject, type: string, data: T): Promise<void> {
const event = createEvent(type, this.source, data);
await this.js.publish(subject, serializeEvent(event));
}Subscriptions create (or reuse) a durable consumer per durableName, with explicit ack and full replay from the start of the stream:
async subscribe<T>(subject: EventSubject, durableName: string, handler: EventHandler<T>) {
const jsm = await this.nc.jetstreamManager();
try {
await jsm.consumers.info(STREAM_NAME, durableName);
} catch {
await jsm.consumers.add(STREAM_NAME, {
durable_name: durableName,
filter_subject: subject,
ack_policy: AckPolicy.Explicit,
deliver_policy: DeliverPolicy.All,
});
}
const consumer = await this.js.consumers.get(STREAM_NAME, durableName);
const messages = await consumer.consume();
for await (const msg of messages) {
try {
await handler(deserializeEvent(msg.data));
msg.ack();
} catch (error) {
console.error('Event handler error:', error);
msg.nak();
}
}
}Key properties:
ack_policy: Explicit— the handler must succeed before the message is acked; a thrown error triggersmsg.nak()(negative-ack), and JetStream redelivers.deliver_policy: All— a new durable consumer starts from the beginning of the stream's retained history, not just new messages.- Durable by name — reconnecting with the same
durableNameresumes exactly where that consumer left off. This is the main reason to choose NATS over the local bus: a worker process can crash and restart without losing queued work.
Fire-and-forget: publishCore() / subscribeCore()
async publishCore<T>(subject: EventSubject, type: string, data: T): Promise<void> {
const event = createEvent(type, this.source, data);
this.nc.publish(subject, serializeEvent(event)); // core NATS, not JetStream
}No persistence, no ack, no redelivery. Used for high-frequency, low-stakes traffic where losing a message occasionally is acceptable — e.g. anvio.agent.run.chunk.v1 streaming deltas, where a dropped chunk during a network blip isn't worth the overhead of durable redelivery.
publish() / subscribe() | publishCore() / subscribeCore() | |
|---|---|---|
| Transport | JetStream | Core NATS |
| Persistence | Yes (stream-retained) | No |
| Ack/replay | Explicit ack, durable consumer, replays from start | None |
| Use case | Work that must not be lost (agent run requests, approvals) | High-frequency streaming (chunks, progress) |
Connection lifecycle
async connect(): Promise<void> {
this.nc = await connect({ servers: this.options.url });
this.js = this.nc.jetstream();
await this.ensureStream();
}
async close(): Promise<void> {
if (this.nc) {
await this.nc.drain(); // graceful drain, not an abrupt disconnect
this.nc = null;
this.js = null;
}
}close() is called from AppService.onModuleDestroy() (apps/api/src/app.service.ts) on API shutdown, and drains rather than force-closes the connection — in-flight messages get a chance to complete.
Environment variables
| Variable | Purpose | Default |
|---|---|---|
NATS_URL | NATS server connection string | nats://localhost:4222 (only used if events.provider: nats) |
See Environment Variables for the complete list.
Running NATS locally
docker run -d --name anvio-nats -p 4222:4222 nats:2 -jsThe -js flag enables JetStream on the server — without it, streams.add() in ensureStream() will fail.
Last updated on