Packages / Events / Overview

Overview

Decorator-driven event bus with typed event contracts, exponential backoff retry, auto-DLQ, and pluggable transports.

@miiajs/messaging is a decorator-driven event bus for MiiaJS. Define an event once with defineEvent(topic, schema), mark any method on any provider or controller with @On(Event), inject MessageBus somewhere else, and call bus.publish(Event, payload) - handlers are wired automatically at startup. No central registry, no manual subscription list. The handler's parameter and the published payload are typed from the event's schema, and every consumer validates the payload before its handler runs.

The package ships with an in-memory transport for development and tests. For production, swap in Redis Streams - same API, just one line in MessagingModule.configure. The discovery side is built on top of DiscoveryService and the onReady lifecycle hook, so the wiring story is the same as any other ambient-discovery package.

Installation

bun add @miiajs/messaging

No peer dependencies for the in-memory transport. Event schemas are optional; any schema with a safeParse() method works - the examples use zod.

Setup

typescript
import { Module, Injectable, inject } from '@miiajs/core'
import { MessagingModule, MessageBus, On, defineEvent, inMemoryTransport, type EventPayload } from '@miiajs/messaging'
import { z } from 'zod'

const UserCreated = defineEvent('user.created', z.object({ id: z.string(), email: z.email() }))
type UserCreated = EventPayload<typeof UserCreated>

@Injectable()
class EmailService {
  @On(UserCreated)
  async sendWelcome(user: UserCreated) {
    console.log(`welcome → ${user.email}`)
  }
}

@Injectable()
class SignupController {
  private bus = inject(MessageBus)

  async createUser(input: { email: string }) {
    const user = { id: crypto.randomUUID(), ...input }
    await this.bus.publish(UserCreated, user)
    return user
  }
}

@Module({
  imports: [MessagingModule.configure({ transport: inMemoryTransport() })],
  providers: [EmailService, SignupController],
})
class AppModule {}

@On works on providers and controllers - DiscoveryService finds both, so a controller method can react to an event the same way a service can. A handler class behind a factory provider (provider(token, () => new Handlers())) is found too. Provide each handler class once: the same class on two instances would subscribe twice under one consumer group, so the bus fails at startup. Handler signature is (payload, meta?) => void | Promise<void>, with payload typed by the event (see Event contracts); throwing nacks the message.

Event contracts

An event contract is the one definition both ends of a topic share. defineEvent(topic, schema?) returns a frozen { topic, schema }, and @On and MessageBus.publish() take only contracts - a string topic does not compile, and in plain JavaScript @On throws (and publish() rejects) with a TypeError that names the fix: define it with defineEvent('order.placed', schema).

typescript
import { defineEvent, type EventPayload } from '@miiajs/messaging'
import { z } from 'zod'

export const OrderPlaced = defineEvent(
  'order.placed',
  z.object({
    orderId: z.string(),
    total: z.number().positive(),
    placedAt: z.coerce.date(),
  }),
)
export type OrderPlaced = EventPayload<typeof OrderPlaced>

export const CacheCleared = defineEvent('cache.cleared') // no schema: the payload is `unknown`

The topic is a non-empty free-form string, and the schema is anything with a safeParse() method (zod or compatible); defineEvent() throws a TypeError on an empty topic or on a schema without safeParse(). Contracts are not memoized - an event is identified by its topic, so two contracts with the same topic are the same event on the wire.

The examples on the rest of this page use contracts defined this way (UserCreated, OrderPlaced, ...), each with a type of the same name.

Typed handlers and payloads

Two types extract the payload types from a contract:

TypeWhat it is
EventPayload<typeof E>What an @On(E) handler receives: the schema's output, with transforms and coercions applied. unknown for an event without a schema.
EventInput<typeof E>What bus.publish(E, payload) takes: the schema's input type when the schema declares one through Standard Schema (zod 3.24+ and zod 4 do), otherwise its output. unknown for an event without a schema.

A type exported under the contract's name, as above, lets one import serve both the decorator and the parameter. The handler's first parameter is checked against the event: a parameter of another type is a compile error, and so is a concrete type on an event without a schema, whose handlers get unknown. One method can carry several @On when its parameter fits the payload of each event.

typescript
@Injectable()
class Billing {
  private bus = inject(MessageBus)

  @On(OrderPlaced)
  async onPlaced(order: OrderPlaced, meta: MessageMeta) {
    order.placedAt.getFullYear() // a Date: the schema coerced it
  }

  @On(OrderPlaced)
  async onWrong(order: { id: number }) {} // compile error: not the event's payload

  async replay() {
    await this.bus.publish(OrderPlaced, { orderId: 'o-1', total: 42, placedAt: new Date() })
  }
}

Validation on consume

Every @On handler validates the payload against the event's schema before it runs, and before an @Idempotent claim. The handler and the idempotency key() get the schema's output, not the raw payload. A payload that does not match is rejected: the handler is not called, nothing is claimed, and the transport moves the message to <topic>.dlq at once, without retries - a retry cannot fix a payload. The dead letter carries meta.attempt: 1 and the reason in meta.lastError, one <path>: <message> per issue:

Payload validation failed for 'order.placed': orderId: Invalid input: expected string, received undefined; total: Too small: expected number to be >0

With retry: { dlq: false } a rejected message is dropped with an error log (rejected without retry) instead. A schema whose safeParse() throws is a reject too.

Each handler is its own subscription and validates on its own, so an invalid message on a topic with three handlers leaves three DLQ records, one per consumer group - the same as three handlers each running out of retries.

The schema runs where the message is consumed because that is the side it protects: it also covers producers that never saw the contract's types - a service in another language, an older deployment, an entry written by hand. publish() runs no schema; its payload is checked by the compiler only. To validate before publishing, call OrderPlaced.schema.safeParse(order) yourself.

Schemas describe the JSON form

A broker transport delivers the JSON of what was published: the Redis transport hands the handler JSON.parse of the stored envelope, so a Date arrives as an ISO string and a class instance as a plain object. The in-memory transport hands over the published object itself. Write the schema for what a broker delivers - z.coerce.date(), not z.date(). With z.date() every message passes in development and tests on the in-memory transport and lands in the DLQ on Redis.

Schemas are synchronous

The bus calls safeParse() and does not await it. Zod throws from safeParse() on an async refine or transform, and the bus treats that as a reject, so every message of the event would go to the DLQ. Keep async checks (a database lookup, a remote call) in the handler.

Sharing contracts between services

Contracts are plain values, so they can live in a package that the producing and the consuming services both depend on - a workspace package in a monorepo, or a published one - next to @miiajs/messaging and the schema library:

typescript
// packages/contracts/src/orders.ts
export const OrderPlaced = defineEvent('order.placed', OrderSchema)
export type OrderPlaced = EventPayload<typeof OrderPlaced>

// services/api - the producer
await this.bus.publish(OrderPlaced, order)

// services/billing - a consumer
@On(OrderPlaced, { group: 'billing' })
async charge(order: OrderPlaced) { /* ... */ }

Both sides then compile against one definition: a renamed or retyped field is a type error in each service that uses it and builds against the new version. Messages already in a stream when a consumer deploys a new schema are validated against it too, so change a schema the way you change a public API - add optional fields first, and drop a field only once no producer sends it.

The @On decorator

typescript
@On(event: EventContract, options?: OnOptions)

interface OnOptions {
  group?: string
  concurrency?: number
  mode?: 'batch' | 'sliding'
  bus?: string
  broadcast?: boolean
  initialPosition?: 'latest' | 'earliest' | { since: number }
}

event is a contract from defineEvent(); the handler's first parameter is typed by it, and topic below means the event's topic.

OptionTypeDescription
groupstringExplicit broker group for a competing-consumers worker pool. Without it, an auto-derived per-handler group ${topic}__${Class}_${method} is used. See Subscriptions and fan-out.
concurrencynumberPer-handler subscription concurrency. In 'batch' mode this is the XREADGROUP COUNT prefetch; in 'sliding' mode it is the number of parallel lanes. Ignored by the in-memory transport.
mode'batch' | 'sliding'Per-handler override of the dispatch mode. Defaults to the bus default, which defaults to the transport default. See Dispatch modes.
busstringTarget bus name for multi-bus setups. Omit to target the default bus.
broadcastbooleanCluster-wide fan-out (every replica gets a copy). Mutually exclusive with group. See Subscriptions and fan-out.
initialPosition'latest' | 'earliest' | { since: number }Where the subscription starts reading when its broker-side group is created for the first time. Defaults to the bus default, which defaults to 'latest'. See Initial position.

Discovery happens in the MessageBus.onReady() hook - see Discovery Service for how that scan works under the hood. You don't need to know the internals to use @On, but it's the same pattern you'd write for your own custom decorators.

Publishing at startup. Publish from onReady(), not onInit(). The bus subscribes the @On handlers in its onReady(), which runs after every provider's onInit(), so a message published from onInit() finds none of this app's handlers subscribed: the in-memory transport drops it, and on Redis a handler whose group this startup creates (a first deploy, a new handler) starts reading after it under the default 'latest' initial position. A provider that injects the bus it publishes on (inject(MessageBus), inject(messageBus(name))) gets its onReady() after that bus's - hooks run in dependency order - so by then the bus's handlers are subscribed.

Subscriptions and fan-out

Each @On becomes its own broker subscription with an auto-derived consumer group ${topic}__${ClassName}_${methodName} (or ${appName}:${topic}__... when MessagingModule.configure({ appName }) is set). ClassName is the class of the handler instance, not the token it is registered under - a factory that returns a subclass for a class token subscribes under the subclass name. Three layered behaviors result:

Within one process: fan-out across handlers (automatic)

Two handlers on the same event = two subscriptions = each gets its own copy:

typescript
@Injectable()
class EmailService {
  @On(UserCreated)
  async sendWelcome(user: UserCreated) { /* always runs */ }
}

@Injectable()
class AnalyticsService {
  @On(UserCreated)
  async track(user: UserCreated) { /* always runs - independent group */ }
}

Each handler has its own retry/ack lifecycle - one throwing does not affect the other. To deduplicate side effects on retry, pair with @Idempotent.

Across replicas: load balance per handler (automatic)

When N replicas of the same code run, they share the auto-derived group:

publish(UserCreated, payload)   (topic 'user.created')
   ↓
group "user.created__EmailService_sendWelcome"  (5 consumers, one per replica)
   broker round-robin → ONE replica handles email exactly once cluster-wide
group "user.created__AnalyticsService_track"    (5 consumers, one per replica)
   broker round-robin → ONE replica handles analytics exactly once

Add replicas → throughput scales linearly per handler. No coordination needed.

Cluster-wide fan-out (broadcast: true)

Sometimes every replica must run the handler (cache invalidation, websocket broadcast). Set broadcast: true:

typescript
@On(CacheInvalidate, { broadcast: true })
async refreshCache(msg: CacheInvalidate) { /* runs on every replica */ }

The auto-derived group is suffixed with __<hostname>_<pid>_<token>, where <token> is random per process, so each process gets a unique broker group - replicas that share hostname and pid (host-network containers running as pid 1) included - and the broker delivers a copy to every replica's subscription. On the Redis transport, the group a crashed replica leaves behind is removed by the next replica that starts, on any host - see Broadcast group lifecycle.

Worker pool: explicit group (competing consumers)

For competing-consumers semantics across multiple handler classes, pass group: 'pool-name':

typescript
@Injectable()
class FastWorker {
  @On(JobQueued, { group: 'job-pool' })
  async run(job: JobQueued) { ... }
}

@Injectable()
class SlowWorker {
  @On(JobQueued, { group: 'job-pool' })
  async run(job: JobQueued) { ... }
}

All handlers in job-pool join the same broker group; the broker round-robins each message to exactly one of them. Requires a transport with supportsCompetingConsumers: true (Redis Streams, Kafka, RabbitMQ, NATS). The in-memory transport rejects explicit group at startup.

Multi-service deployments (appName)

When several services share a broker, pass MessagingModule.configure({ appName: 'my-service' }). Auto-derived groups become my-service:topic__Class_method, so two services with overlapping handler class names do not collide. Topics and explicit group values are NOT prefixed - they remain shared cross-service contracts (see Sharing contracts between services).

Dispatch modes

Where group controls fan-out between replicas, dispatch mode controls how a single subscription pulls messages off the broker:

  • 'batch' - the consumer reads up to concurrency messages, runs them through Promise.allSettled, then reads again. The slowest handler in a batch holds back the next read (head-of-line blocking). Best for high-throughput uniform workloads where per-message variance is small.
  • 'sliding' - each in-flight message progresses independently; the subscription pulls the next message as soon as a slot frees, without waiting for the rest of the batch. Best when handler runtimes vary - one slow message no longer blocks the others.
TransportSupported modesDefault
InMemoryTransport['sliding']'sliding'
RedisStreamsTransport['batch', 'sliding']'batch'

In-memory has no broker prefetch primitive and concurrency is meaningless within a single process, so emulating batch would just add an artificial barrier with no value. Redis Streams supports both - sliding spawns concurrency parallel XREADGROUP COUNT 1 lanes on dedicated connections (BullMQ-style); batch is the single-loop path with COUNT=concurrency.

Resolution

Mode and concurrency resolve through three levels - more specific wins:

  1. Per-handler - @On(event, { mode, concurrency }).
  2. Per-bus - MessagingModule.configure({ dispatch: { mode, concurrency } }).
  3. Transport default - whatever transport.defaultMode says, with concurrency falling back to 1.
typescript
MessagingModule.configure({
  transport: redisStreamsTransport({ url: process.env.REDIS_URL! }),
  dispatch: { mode: 'sliding', concurrency: 4 }, // default for handlers on this bus
})

@On(OrderPlaced)                                     // uses bus default: sliding/4
@On(AuditLogged, { mode: 'batch', concurrency: 32 }) // override: batch/32

Each @On is its own subscription with its own mode/concurrency - validation runs per handler at startup (unsupported mode against transport.supportedModes, concurrency <= 0). Different handlers on the same topic can have different mode/concurrency without conflict.

Initial position

A consumer group created after entries were published does not see them: it starts at the end of the topic and reads only what arrives next. That bites on a first deploy (the API publishes before the worker has ever started), on a new topic, and on a new or renamed handler - each of them creates a brand new group. initialPosition decides what that new group does with the entries already there:

  • 'latest' (default) - only entries published after the group is created. Same as RabbitMQ (an exchange drops messages no queue is bound to) and Kafka auto.offset.reset=latest.
  • 'earliest' - everything the broker still retains for the topic.
  • { since: ms } - entries published in the last since milliseconds, plus everything after. since must be a positive integer.
typescript
@Injectable()
class Onboarding {
  @On(UserCreated) // 'latest': a welcome email for a signup from last week is worse than none
  async sendWelcome(user: UserCreated) { /* ... */ }
}

@Injectable()
class MediaWorker {
  @On(VideoUploaded, { initialPosition: { since: 60 * 60 * 1000 } }) // a new group picks up the last hour
  async probe(video: VideoUploaded) { /* ... */ }
}

It resolves like dispatch mode - more specific wins:

  1. Per-handler - @On(event, { initialPosition }).
  2. Per-bus - MessagingModule.configure({ initialPosition }).
  3. 'latest'.

The position applies only when the group is created. An existing group is never moved - changing initialPosition on a handler whose group already exists has no effect, and restarts and redeploys pick up where the group left off as before.

Broadcast handlers always start at 'latest'. Their group belongs to one process and dies with it, so history means nothing to them: the bus default does not reach them, and an explicit 'earliest' or { since } on a broadcast handler throws at startup.

Explicit group. Handlers on one bus that share a group must resolve to the same position, or the bus throws at startup - whichever handler created the group first would otherwise decide silently. Across replicas or separate apps sharing a group there is no such check: the first one to create the group decides, and later settings have no effect.

Transport support is checked at startup, like dispatch modes:

TransportSupported positions
RedisStreamsTransport'latest', 'earliest', { since } - see the Redis page
InMemoryTransportall three accepted - it retains nothing, so every position means "from now"
A transport that does not declare supportedInitialPositions'latest' only - anything else fails at startup instead of silently starting at the end

Retry and DLQ

When a handler throws (or returns { status: 'nack' } from a low-level transport-level call), the transport retries with exponential backoff. After maxAttempts failures, the message is republished to <topic>.dlq with the last error captured in meta.lastError.

A payload that does not match the event's schema skips the retries: the bus rejects it and the transport moves it to <topic>.dlq on its first delivery - see Validation on consume.

Retries are scoped to the single handler that nacked. Sibling handlers on the same topic (each their own subscription) are unaffected - if EmailService.send throws while AnalyticsService.track succeeded, only the email handler retries; analytics is not re-run.

Retry delay between attempt N and N+1: backoffMs * backoffMultiplier^(attempt - 1). With the defaults (backoffMs: 1000, multiplier: 2) attempts fire at 1s, 2s, 4s, 8s, 16s.

Subscribe to a DLQ with dlqEvent(event), a contract for <topic>.dlq. It has no schema - dead letters include payloads that failed the event's schema - so its handlers get the payload as unknown, with the reason in meta.lastError:

typescript
import { Injectable } from '@miiajs/core'
import { dlqEvent, On, type MessageMeta } from '@miiajs/messaging'

@Injectable()
class DlqAlerts {
  @On(dlqEvent(UserCreated))
  async onDeadLetter(payload: unknown, meta: MessageMeta) {
    await alertOps(`user.created dead-lettered after ${meta.attempt} attempt(s): ${meta.lastError}`)
  }
}

To read the fields, run the event's schema on the payload yourself: UserCreated.schema.safeParse(payload) succeeds for a message that ran out of retries and fails for one that was rejected.

FieldTypeDefaultDescription
maxAttemptsnumber5Total delivery attempts before a message is moved to the DLQ.
backoffMsnumber1000Base delay (ms) for the first retry.
backoffMultipliernumber2Exponential multiplier applied per attempt.
dlqbooleantrueWhen false, exhausted and rejected messages are dropped with an error log instead of routed to <topic>.dlq.

The default is max-attempts + DLQ, not infinite retry, because infinite retry creates "poison pill" queues that silently block live traffic behind a single broken message - same reason Kafka, RabbitMQ, and NATS JetStream all standardise on bounded retry plus a dead-letter destination.

Distributed tracing

Every MessageEnvelope carries optional meta.traceparent and meta.tracestate fields that follow the W3C Trace Context spec. They are pure data - the bus does not auto-inject anything from your tracing library, but the fields are preserved across publish, retry, and DLQ so a span context populated at the producer survives the network hop to any consumer (Node.js, Go, Python - JSON envelopes work cross-language).

typescript
import { trace } from '@opentelemetry/api'

const span = trace.getActiveSpan()
const ctx = span?.spanContext()

await bus.publish(OrderPlaced, order, {
  traceparent: ctx
    ? `00-${ctx.traceId}-${ctx.spanId}-${ctx.traceFlags.toString(16).padStart(2, '0')}`
    : undefined,
})

In a consumer, restore the span context with whatever tracing library you use:

typescript
@On(OrderPlaced)
async onOrderPlaced(order: OrderPlaced, meta: MessageMeta) {
  if (meta.traceparent) {
    // restore span context via OpenTelemetry / Datadog / Sentry SDK
    // continue the distributed trace inside this handler
  }
  // business logic
}

Graceful drain

When app.destroy() runs (SIGTERM, deploy, restart), shutdown goes in two phases. First every provider's onShutdown(): the bus unsubscribes its handlers and each transport stops consuming and waits up to drainTimeoutMs (default 5000) for in-flight handlers to finish. Only then does any provider's onDestroy() release its resources - the transport's connections, the idempotency store, and the database your handlers write to, wherever its module sits. Without drain, a handler interrupted mid-execution leaves the message un-acked - it stays pending on the broker until something redelivers it, and the work runs twice. On the Redis transport that redelivery comes from a housekeeping pass on any replica, once the entry crosses the retry horizon.

typescript
inMemoryTransport({
  drainTimeoutMs: 5000, // default; set 0 to skip drain
})

The drain phase blocks new deliveries (including scheduled retries) and awaits all currently-running handlers. When the timeout is reached the transport logs a warning and continues with cleanup; pending handlers will keep running but their results are discarded.

Idempotency

@miiajs/messaging delivers messages at least once (for messages published while the subscription exists, see Initial position), so duplicates are inevitable - consumer crash before XACK, network blip, broker reclaim. Most handlers should be idempotent by design (UPDATE WHERE id = ?, cache invalidations, state syncs). For handlers with non-idempotent side effects - charging cards, sending emails, calling rate-limited external APIs - use @Idempotent to skip duplicate executions:

typescript
import { Injectable } from '@miiajs/core'
import { On, Idempotent } from '@miiajs/messaging'

@Injectable()
class PaymentService {
  @On(OrderPlaced)
  @Idempotent({ ttl: 24 * 60 * 60 * 1000 }) // dedupe within 24h
  async chargeCard(order: OrderPlaced) {
    await this.payments.charge(order.cardId, order.total)
  }
}

Default key is ${envelope.id}:${ClassName}.${methodName}, with ClassName the class of the handler instance - per-handler scope, so two @Idempotent handlers on the same topic do not conflict. Override key to widen scope or to dedupe on a business identifier from the payload:

typescript
@On(PaymentReceived)
@Idempotent({ ttl: 24 * 60 * 60 * 1000, key: (p: PaymentReceived) => `payment:${p.transactionId}` })
async onPayment(payment: PaymentReceived) { ... }

key() gets the payload after the event's schema, like the handler. A payload that fails the schema is rejected before the claim, so it never takes a key.

Configure the store in MessagingModule.configure:

typescript
import { MessagingModule, inMemoryTransport, memoryIdempotencyStore } from '@miiajs/messaging'

MessagingModule.configure({
  transport: inMemoryTransport(),
  idempotency: memoryIdempotencyStore(), // dev / single-process
})

For production with multiple replicas, use redisIdempotencyStore - claims must be visible across processes, which an in-memory Map cannot provide.

Decorator optionTypeDefaultDescription
ttlnumberrequiredClaim lifetime in milliseconds. After expiry, the same key can be claimed and processed again.
key(payload, meta) => string${envelope.id}:${ClassName}.${methodName}Custom claim key. Useful when the upstream may republish the same business event with different envelope IDs, or when handlers should share a claim.

If any handler is annotated with @Idempotent but no idempotency store is configured, MessageBus throws at startup so the misconfiguration cannot reach production silently.

Multiple buses

For apps that need more than one transport - Kafka for legacy reads + Redis Streams for new writes, an internal in-memory bus + an external Redis bus, separate buses per tenant - call MessagingModule.configure(opts, { name }) once per bus. The name keeps the buses apart in DI, so each bus gets its own transport, idempotency store, and MessageBus instance.

typescript
import { Module } from '@miiajs/core'
import { MessagingModule, inMemoryTransport } from '@miiajs/messaging'
import { redisStreamsTransport, redisIdempotencyStore } from '@miiajs/messaging-redis'

@Module({
  imports: [
    // Default bus - used when @On has no `bus` option
    MessagingModule.configure(
      {
        transport: redisStreamsTransport({ url: process.env.REDIS_URL! }),
        idempotency: redisIdempotencyStore({ keyPrefix: 'primary:idem:' }),
      },
      { global: true },
    ),

    // Named bus for legacy Kafka reads
    MessagingModule.configure(
      { transport: kafkaTransport({ /* ... */ }) },
      { name: 'kafka', global: true },
    ),

    // Internal in-memory bus for domain events between services in the monolith
    MessagingModule.configure({ transport: inMemoryTransport() }, { name: 'internal', global: true }),
  ],
})
class AppModule {}

{ global: true } lets a provider in any module inject the bus. A named bus is not reachable through a bare imports: [MessagingModule], which resolves to the default bus only: without global, its configure() result is imported by one module that re-exports it.

Inject the bus you need. The default bus is the MessageBus class; a named bus is the typed token messageBus(name), which returns the same token for the same name:

typescript
import { MessageBus, messageBus } from '@miiajs/messaging'

@Injectable()
class OrderService {
  private primary = inject(MessageBus)                // default
  private kafka = inject(messageBus('kafka'))         // named, typed as MessageBus
  private internal = inject(messageBus('internal'))
}

Target a specific bus from @On via the bus option:

typescript
@Injectable()
class Handlers {
  @On(OrderPlaced)                            // default bus
  async onOrder(o: OrderPlaced) { ... }

  @On(LegacyUserCreated, { bus: 'kafka' })    // kafka bus
  async onLegacyUser(u: LegacyUserCreated) { ... }

  @On(CartUpdated, { bus: 'internal' })
  async onCart(c: CartUpdated) { ... }
}

An empty name is the default bus: @On(event, { bus: '' }) subscribes like @On(event), the same way MessagingModule.configure(opts, { name: '' }) configures the default bus.

MessagingModule.configure

MessagingModule.configure() returns a ConfiguredModule with the transport and MessageBus registered as singletons. Two forms - same shape as JwtModule.configure and DrizzleModule.configure.

Static options:

typescript
MessagingModule.configure({
  transport: inMemoryTransport(),
})

Factory with DI access (use this when the transport depends on ConfigService or another provider):

typescript
import { ConfigService } from '@miiajs/config'
import { redisStreamsTransport } from '@miiajs/messaging-redis'

MessagingModule.configure((resolve) => ({
  transport: redisStreamsTransport({
    url: resolve(ConfigService).getOrThrow('REDIS_URL'),
    retry: { maxAttempts: 10 },
  }),
}))

The factory runs once per app, so the transport and idempotency store it creates are built once and are the ones the bus uses. Two apps built from the same configure() result (two TestApps, say) each run it and get their own.

FieldTypeDescription
transportMessageTransportRequired. The transport instance the bus publishes through and subscribes against.
idempotencyIdempotencyStoreOptional. Required when any handler uses @Idempotent - the bus throws at startup otherwise. See Idempotency.
dispatch{ mode?: DispatchMode; concurrency?: number }Optional. Bus-wide dispatch defaults applied to every subscription on this bus. Overridden per-handler via @On({ mode, concurrency }). See Dispatch modes.
appNamestringOptional namespace prefix for auto-derived consumer groups. Use to avoid collisions when multiple services share a broker. Does NOT affect topic names or explicit @On({ group }) values. See Multi-service deployments.
initialPosition'latest' | 'earliest' | { since: number }Optional. Bus default for where a newly created subscription starts reading. Overridden per-handler via @On({ initialPosition }); ignored by broadcast handlers. Default 'latest'. See Initial position.

MessagingModule.configure() accepts an optional second argument { name?: string; global?: boolean }. Without name it registers the default bus, injected as inject(MessageBus). With name it registers a named bus, injected as inject(messageBus(name)) - see multi-bus setups. The transport and idempotency store tokens of each bus are internal. Configuring the same name twice throws at startup.

The configured module exports its bus. With global: true every module sees it; without it, a module that injects the default bus imports MessagingModule bare. @On handlers do not need to see a bus: the startup check and the subscriptions cover every bus of the app, wherever its module sits.

InMemoryTransport options

typescript
inMemoryTransport({
  retry: { backoffMs: 100, maxAttempts: 3 },
  cloneOnPublish: false,
})
OptionTypeDefaultDescription
retryPartial<RetryConfig>DEFAULT_RETRYOverride individual retry fields.
cloneOnPublishbooleanfalseWhen true, payload is structuredCloned before each handler sees it - prevents accidental cross-handler mutation at the cost of one clone per delivery.
drainTimeoutMsnumber5000Max time onShutdown() waits for in-flight handlers before forcing cleanup. Set 0 to skip drain. See Graceful drain.

The in-memory transport is not persistent. Messages live in memory only; a process crash mid-retry loses any in-flight or scheduled retries. It's ideal for tests, local dev, and single-process apps where event loss on crash is acceptable. For production reach for the Redis transport.

Testing

Use TestApp to replace the app's MessagingModule.configure(...) with a fast-retry in-memory one and resolve MessageBus directly:

typescript
import { TestApp } from '@miiajs/testing'
import { MessageBus, MessagingModule, inMemoryTransport } from '@miiajs/messaging'

const app = await TestApp.create(AppModule)
  .override(MessagingModule, MessagingModule.configure({ transport: inMemoryTransport({ retry: { backoffMs: 5 } }) }))
  .compile()

const bus = app.resolve(MessageBus)
await bus.publish(UserCreated, { id: '1', email: '[email protected]' })

// In-memory delivery is asynchronous - handlers run via queueMicrotask.
// Wait a tick before asserting on the result.
await new Promise((r) => setTimeout(r, 10))

expect(handler.received).toEqual([{ id: '1', email: '[email protected]' }])

The in-memory transport hands handlers the published object itself, while a broker transport hands them its JSON, so a schema that passes in tests can still reject every message on Redis - see Schemas describe the JSON form.

A named bus is replaced the same way, by a configuration with the same name; the default bus stays as the graph configures it: .override(MessagingModule, MessagingModule.configure({ transport: inMemoryTransport() }, { name: 'kafka' })).

The startup check of @On bus names counts the MessageBus instances of the app. A bus token overridden with a plain object - .override(messageBus('kafka'), { publish: async () => {} }) - is not one, so the other buses fail at startup on an @On that targets it. Replace a bus through its configuration, as above, or override the token with a factory that builds a MessageBus (or a subclass) under the same name.

A handler replaced with a plain object - .override(EmailService, { sendWelcome() {} }) - has no class for DiscoveryService to read, so its @On methods are not subscribed. To keep them, override with an instance of a named subclass without decorators of its own (class FakeEmailService extends EmailService {}); its consumer groups are then named after FakeEmailService.

Lower backoffMs to single-digit milliseconds in tests so retry paths complete inside the test timeout.

Exports

typescript
import {
  MessageBus,
  MessagingModule,
  Idempotent,
  IDEMPOTENT,
  InMemoryTransport,
  inMemoryTransport,
  MemoryIdempotencyStore,
  memoryIdempotencyStore,
  On,
  ON,
  defineEvent,
  dlqEvent,
  DEFAULT_RETRY,
  dlqTopic,
  messageBus,
  nextBackoffMs,
  deriveGroupName,
  type DeriveGroupNameInput,
  type DispatchDefaults,
  type DispatchMode,
  type EventContract,
  type EventInput,
  type EventPayload,
  type MessageEnvelope,
  type MessageMeta,
  type MessageTransport,
  type MessagingModuleOptions,
  type HandlerResult,
  type IdempotencyStore,
  type IdempotentMeta,
  type InitialPosition,
  type InitialPositionKind,
  type InMemoryTransportOptions,
  type MemoryIdempotencyStoreOptions,
  type OnMeta,
  type OnOptions,
  type RetryConfig,
  type SubscribeOptions,
  type Subscription,
} from '@miiajs/messaging'
Edit this page on GitHub