Real-Time

Cross-Process Events

Deliver @axiljs/events emits to other processes with { broadcast: true }: ClusterTransport and installClusterEventRelay for node:cluster workers, in-memory transports for tests, and custom transports.

7 min readUpdated DocumentationEdit this page
On this page11

An EventBus is in-process by default. With @axiljs/scale cluster mode each worker has its own bus, so an event emitted in one worker never reaches the others. Attach a transport to deliver selected events to buses in other processes.

Note

New in 0.3.4: the transport and broadcast options, ClusterTransport, installClusterEventRelay(), InMemoryTransport and createLinkedTransports().

Cluster workers

TypeScript
TS
1import { EventBus, ClusterTransport, installClusterEventRelay } from '@axiljs/events'
2
3// Top level of the entry file, so it runs in the primary as well.
4// No-op in workers and in single-process mode.
5installClusterEventRelay()
6
7const bus = new EventBus({ transport: new ClusterTransport() })
8
9bus.on('cache.*', (event) => cache.delete(event.payload.key))
10
11await bus.emit('cache.invalidate', { key: 'users' }, { broadcast: true })  // all workers
12await bus.emit('cache.warmed', { key: 'users' })                           // this worker only

With serve() from @axiljs/scale, install the relay in the onPrimary hook instead:

TypeScript
TS
1import { serve } from '@axiljs/scale'
2import { installClusterEventRelay } from '@axiljs/events'
3
4serve(createApp, {
5  port: 3000,
6  onPrimary: () => installClusterEventRelay()   // the returned disposer runs after the workers stop
7})

The same code runs unchanged with one worker: without an IPC channel ClusterTransport is inert and broadcast only delivers locally.

Delivery rules

  • Only emits with { broadcast: true } leave the process. new EventBus({ transport, broadcast: true }) makes broadcasting the default, and an emit can then opt out with { broadcast: false }.
  • Local handlers run exactly once per emit, whether or not it is broadcast. The event is published before the local handlers run, so slow local handlers do not delay remote delivery.
  • Events received from the transport run local handlers, middleware, once and waitFor, and are recorded in history, but are never re-published, so relays cannot loop.
  • Each bus has a random originId. Messages carrying the bus's own id are dropped, so a transport that echoes publishes back does not cause double delivery.
  • Without a transport, broadcast only delivers locally.
  • A transport publish failure is reported to the bus's onError as Transport publish failed: <message> and does not reject emit(), because local delivery has already happened.

Emit options

emit(type, payload, options) accepts the event metadata (source, correlationId, causationId, version) plus broadcast:

TypeScript
TS
await bus.emit('user.updated', { id: 42 }, { broadcast: true, correlationId: req.locals.requestId })

Bus options

OptionTypeDefaultDescription
transportEventTransportnoneCarrier to other processes
broadcastbooleanfalseBroadcast every emit unless it passes { broadcast: false }

bus.useTransport(transport) attaches or replaces the transport at runtime, and useTransport(null) detaches it. getTransport() returns the current one. Detaching does not call the transport's close(); the caller owns its lifecycle.

Payload rules

Broadcast payloads must be plain JSON data:

AllowedRejected
null, booleans, strings, finite numbersNaN, Infinity
Arrays and plain objects (prototype Object or null)Class instances: Map, Set, Buffer, Error, ...
Date (received as an ISO string)Functions, symbols, bigint
Object properties set to undefined (dropped, as JSON does)undefined elsewhere, e.g. array items
A missing payload (top-level undefined)Circular references

A rejected payload makes emit() throw a TypeError naming the path (for example Event 'order.placed' payload is not JSON-serializable: payload.items is a Map instance (use plain objects and arrays)) before any handler runs. The check runs on every broadcast emit, also when no transport is attached, so a bad payload fails the same way in development and in production. Non-broadcast emits are not checked.

The check is exported:

TypeScript
TS
1import { assertJsonSafe } from '@axiljs/events'
2
3assertJsonSafe({ at: new Date(), tags: ['a'] })      // ok
4assertJsonSafe({ ids: new Set([1]) }, 'Job data')    // throws TypeError

ClusterTransport

ClusterTransport sends { __axil: 'events', v: 1, origin, event } over the worker's IPC channel (process.send) and ignores every other message, so it coexists with your own IPC messages and with @axiljs/scale's control messages.

MemberDescription
new ClusterTransport({ channel? })channel defaults to the current process's IPC channel; inject a fake for tests
activetrue when there is an IPC channel to publish to
close()Remove the transport's IPC listeners (lets an otherwise idle worker exit). Later publishes reject

Without an IPC channel, publish() does nothing and nothing is received. If the channel has been closed, publish() rejects, which the bus reports to onError.

installClusterEventRelay

Call it in the primary. It forwards each envelope from a worker to every other connected worker, including workers forked after it was installed. It never sends an event back to the worker it came from.

TypeScript
TS
const stop = installClusterEventRelay({
  onError: (error, worker) => log.warn(`relay to worker ${worker.id} failed: ${error.message}`)
})
OptionDefaultDescription
hostnode:clusterThe cluster to relay on. With the default, the call is a no-op in any process that is not the primary
onErrorignoreCalled when relaying to a worker fails, e.g. because it just exited

It is idempotent per host: extra calls share one relay (the first call's onError is kept). Each call returns a disposer, and the relay is removed when every disposer has been called.

Delivery guarantees

Delivery is fire-and-forget, with no persistence and no acknowledgement. A worker that is restarting misses the events sent meanwhile. The relay covers the workers of one machine; it does not reach other servers.

Use events for signals that may be lost without harm, such as cache invalidation. When delivery must be guaranteed, or must reach other servers, use a queue with a SQL backend or an external broker.

In-memory transports

For tests, or several buses in one process, link buses in memory:

TypeScript
TS
1import { EventBus, createLinkedTransports } from '@axiljs/events'
2
3const [ta, tb] = createLinkedTransports(2)
4const a = new EventBus({ transport: ta })
5const b = new EventBus({ transport: tb })
6
7b.on('user.*', handler)
8await a.emit('user.created', { id: 1 }, { broadcast: true })

InMemoryTransport mirrors real IPC:

  • Delivery is asynchronous (next microtask), and each subscriber receives its own JSON round-tripped copy, with no shared references.
  • publish() resolves once every subscriber has been called. If a subscriber throws, the others still receive the message and the first error is rethrown.
  • new InMemoryTransport(existing) joins the group of an existing transport; new InMemoryTransport() starts a new group. size is the number of transports in the group.
  • close() leaves the group and drops all subscribers; later publishes throw.

createLinkedTransports(n) throws a RangeError unless n is a positive integer.

Custom transports

A transport for Redis, NATS or another broker implements EventTransport:

TypeScript
TS
1import type { EventTransport, EventTransportMessage } from '@axiljs/events'
2
3interface EventTransport {
4  publish(message: EventTransportMessage): void | Promise<void>
5  subscribe(handler: (message: EventTransportMessage) => void): () => void   // returns unsubscribe
6  close?(): void | Promise<void>
7}
8
9// EventTransportMessage: { origin: string; event: axilEvent }

origin is the sending bus's originId, and event is a JSON-safe copy of the emitted event. A transport may deliver a bus's own messages back to it; the bus drops them.

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY