Docs for the next release (prerelease). Install it with npm i @meghjs/cli@next. Latest release docs →

Next release (prerelease) · Latest docs →

Skip to content

Messaging ​

Messaging carries events between processes. One part of the system publishes an event, and listeners in any replica, or any other service, handle it.

The same transport layer carries distributed events, raw messages, and, on RabbitMQ, queue jobs. Retries, dead letters, dedupe and the outbox work the same on every transport.

Transports ​

TransportRuns onUse it for
memoryThis processDevelopment and tests. The default.
redisRedis StreamsProduction, when you already run Redis
rabbitmqA RabbitMQ brokerProduction, when you run RabbitMQ

The Redis client (@redis/client) and the RabbitMQ client (amqplib) ship with @meghjs/core. There is nothing to install.

The memory transport never leaves the process, and loses messages on restart. Use it to run the app without a broker. Kafka is not supported.

Configuration ​

Pick the transport with app.useMessaging():

ts
import { Megh } from '@meghjs/core';

const app = Megh.createApplication();

app.useMessaging({
  transport: 'redis',
  url: process.env.REDIS_URL, // redis:// or rediss://
});

Or leave it to the environment:

sh
MEGH_MESSAGING_TRANSPORT=rabbitmq
MEGH_MESSAGING_URL=amqps://user:pass@rabbit.internal
ts
app.useMessaging(); // reads MEGH_MESSAGING_TRANSPORT and MEGH_MESSAGING_URL

Options passed to useMessaging() win over the environment. Without either, Megh uses memory.

VariableDefaultDescription
MEGH_MESSAGING_TRANSPORTmemorymemory, redis or rabbitmq
MEGH_MESSAGING_URLBroker URL. Required for rabbitmq
MEGH_MESSAGING_SOURCEmegh://<package name>The CloudEvents source of messages this app publishes

All options:

OptionDefaultDescription
transportenv, then 'memory''memory', 'redis', 'rabbitmq', or your own Transport object
urlMEGH_MESSAGING_URLBroker URL
redisRedis connection and stream options, see Redis
rabbitmqRabbitMQ options, see RabbitMQ
memory{ sync: true } delivers inside publish(). For tests
sourceMEGH_MESSAGING_SOURCECloudEvents source
retry{ retries: 3, backoff: 1000, maxBackoff: 60000 }Default retry policy for every listener
dedupe{ window: 24h, store: 'auto' }Default dedupe for every listener, or false
maxPayloadBytes262144 (256 KiB)Largest encoded message
allowInsecurefalseAllow a non-TLS URL to a remote broker in production
outboxfalseTurn on the transactional outbox

useMessaging() also adds a messaging check to GET /ready (see Health Checks), and closes the transport when the app shuts down.

Distributed events ​

An event becomes distributed when you mark its class with @DistributedEvent. Dispatching it then publishes it on the transport:

ts
import { DistributedEvent, MeghEvent } from '@meghjs/core';

@DistributedEvent('order.placed')
export class OrderPlaced extends MeghEvent<{ orderId: number; total: number }> {}
ts
await new EventDispatcher().dispatch(new OrderPlaced({ orderId: 7, total: 42 }));

The argument is the type on the wire. It defaults to the class name. Give it explicitly when other services consume the event, so renaming the class doesn't break them.

dispatch() resolves once the transport has accepted the event. It does not wait for listeners.

Listeners ​

A listener is a class marked with @Listener. It is resolved through dependency injection, so it can inject services:

ts
import { Listener, MeghEventListener } from '@meghjs/core';
import { OrderPlaced } from '../events/order-placed.event';
import { PaymentService } from '../services/payment.service';

@Listener(OrderPlaced, { group: 'billing' })
export class ChargeCustomer extends MeghEventListener<OrderPlaced> {
  constructor(private readonly payments: PaymentService) {
    super();
  }

  async handler(event: OrderPlaced) {
    await this.payments.charge(event.payload.orderId, event.payload.total);
  }
}

Listeners start in app.run() and stop in app.close(). Importing the file is enough to register one; no use* call is needed.

OptionDefaultDescription
groupthe class nameConsumer group, see below
retrythe bus default{ retries?, backoff?, maxBackoff? } for this listener
dedupethe bus default{ window?, store? }, or false for a handler that is safe to run twice
concurrency1Events this listener handles at once, per replica

The listener receives an instance of the event class, rebuilt from the message. Its constructor does not run, and the payload went through JSON, so a Date arrives as a string.

Groups ​

Every group receives each event once. Replicas in the same group share the work: each event goes to one of them.

With three replicas of a billing service and two of a mail service:

  • @Listener(OrderPlaced, { group: 'billing' }) runs once per order, on one billing replica.
  • @Listener(OrderPlaced, { group: 'mail' }) runs once per order, on one mail replica.

Give two listeners for the same event different groups. The default group is the class name, which is usually what you want.

Local events ​

@Listener works on an event without @DistributedEvent too. The listener then joins the in-process event registry at app.run(), and group, retry, dedupe and concurrency don't apply.

Listeners registered by hand with EventRegistry.getInstance().register() always run in the process that dispatches, distributed event or not.

Delays ​

delay publishes the event now and delivers it later:

ts
await dispatcher.dispatch(new OrderPlaced({ orderId: 7, total: 42 }), { delay: '10m' });

All three transports support delays. See the limitations for Redis Cluster.

Raw messages ​

Without event classes, publish and listen on the bus directly:

ts
import { Messaging } from '@meghjs/core';

await Messaging.publish('invoice.paid', { invoiceId: 12 });
await Messaging.publish('invoice.reminder', { invoiceId: 12 }, { delay: 86_400_000 });

const subscription = await Messaging.listen(
  'invoice.paid',
  async (data, envelope) => {
    console.log(data.invoiceId, envelope.id);
  },
  { group: 'accounting' },
);

await subscription.close();

publish() takes { delay?, id?, outbox? } and resolves to the envelope it sent. listen() takes the same options as @Listener, but group is required.

The envelope ​

Every message travels as a CloudEvents 1.0 JSON envelope, so services not written with Megh can produce and consume it:

json
{
  "id": "5f1c…",
  "type": "order.placed",
  "source": "megh://shop-api",
  "time": "2026-11-28T10:00:00.000Z",
  "specversion": "1.0",
  "datacontenttype": "application/json",
  "traceparent": "00-…",
  "meghrequestid": "…",
  "data": { "name": "OrderPlaced", "timestamp": 1764324000000, "payload": { "orderId": 7, "total": 42 } }
}
  • traceparent is set when the app uses OpenTelemetry, and meghrequestid when the event was dispatched during a request.
  • A distributed event's data is { name, timestamp, payload }.
  • The redis and rabbitmq transports refuse a message larger than maxPayloadBytes (256 KiB). Store large data elsewhere and send a reference.

Delivery guarantees ​

Delivery is at least once. A message that was published reaches every group, but a group can see it twice: a replica can crash after the handler ran and before it acknowledged the message, and the broker hands it out again.

Dedupe catches most of those copies. Before a handler runs, Megh claims the message ID for the group. A second copy with the same ID is skipped, and counted in stats() as a duplicate. IDs are remembered for 24 hours by default.

Where the IDs are kept:

dedupe.storeShared by replicasNeeds
'auto' (default)dependsredis with the redis transport, else database when the outbox is on, else memory
'redis'YesThe redis transport
'database'YesMegh ORM and the messaging tables
'memory'No: one process only
ts
app.useMessaging({
  transport: 'rabbitmq',
  dedupe: { store: 'database', window: 7 * 24 * 60 * 60 * 1000 }, // a week
});

Dedupe narrows the window for duplicates; it doesn't close it. Make handlers that move money or send mail safe to run twice, for example by checking whether the work was already done. Turn dedupe off with dedupe: false on a listener whose handler already is.

Retries and dead letters ​

A handler that throws is retried, waiting backoff milliseconds before the first retry and twice as long before each next one, up to maxBackoff. The default is 3 retries, 1, 2 and 4 seconds apart.

ts
@Listener(OrderPlaced, { group: 'billing', retry: { retries: 5, backoff: 2000 } })

A message that still fails is dead-lettered: stored with the error, the group and the number of attempts, and logged at error level. The other groups are not affected.

List, retry and discard dead letters from the CLI:

sh
npx megh messaging:failed                  # list them
npx megh messaging:failed --json --limit 20
npx megh messaging:failed retry <id>       # publish it again
npx megh messaging:failed retry --all
npx megh messaging:failed discard <id>     # drop it for good

The CLI connects from MEGH_MESSAGING_TRANSPORT and MEGH_MESSAGING_URL in the environment or .env. With memory there is nothing to inspect: dead letters live inside the app process.

Retrying sends the message to the one group that failed. The other groups don't see it twice.

The same operations are on the bus, for an admin page or a script:

ts
const letters = await Messaging.deadLetters(50); // DeadLetter[], oldest first
await Messaging.retryDeadLetter(letters[0].id);
await Messaging.discardDeadLetter(letters[1].id);

Outbox ​

Saving a row and publishing an event are two steps. A crash between them loses the event, or publishes one for a write that rolled back.

The outbox closes that gap. Inside a database transaction, a distributed event is stored in the megh_outbox table with your data, and published after the transaction commits. If the transaction rolls back, the event goes with it.

It needs Megh ORM and the messaging tables. Turn it on:

ts
app
  .useMeghORM()
  .useMessaging({ transport: 'redis', url: process.env.REDIS_URL, outbox: true });

Then dispatch inside a transaction as usual:

ts
await Order.transaction(async () => {
  const order = await Order.create({ customer_id: 3, total: 42 });
  await dispatcher.dispatch(new OrderPlaced({ orderId: order.id, total: 42 }));
});

A relay in every replica publishes what the outbox holds. Each row is claimed before it is published, so replicas don't publish it twice. A failed publish is tried again, 2 seconds later at first and at most 5 minutes apart, until the broker takes it.

  • Outside a transaction, events are published directly.

  • outbox: true on a dispatch or publish stores it in the outbox anyway, and outbox: false publishes directly inside a transaction:

    ts
    await dispatcher.dispatch(event, { outbox: false });
    await Messaging.publish('audit.logged', data, { outbox: true });
  • On RabbitMQ, queue jobs added inside a transaction go through the outbox too.

  • { outbox: { pollInterval: 1000, batchSize: 100 } } changes how often the relay looks for rows, and how many it publishes per round.

  • await Messaging.flushOutbox() publishes one batch now. For tests and scripts.

With the outbox on, the default dedupe store is the database, so replicas share it.

The messaging tables ​

The outbox, scheduler locks and the database dedupe store use three tables: megh_outbox, megh_locks and megh_dedupe. Create them with a migration:

sh
npx megh make:messaging
npx megh migrate

make:messaging writes:

ts
import { createMessagingTables, defineMigration, dropMessagingTables } from "@meghjs/core";

export default defineMigration({
  up: (schema) => createMessagingTables(schema),
  down: (schema) => dropMessagingTables(schema),
});

Security ​

  • TLS in production. With NODE_ENV=production, a redis:// or amqp:// URL to a host other than localhost, 127.0.0.1 or ::1 is refused at startup, whether it comes from url, redis.url, rabbitmq.url, a redis.host without tls: true, or the queue's MEGH_REDIS_URL. Use rediss:// or amqps://. On a private network you trust, set allowInsecure: true or MEGH_ALLOW_INSECURE_BROKER=true.
  • No memory transport for distributed listeners in production. A @Listener for a distributed event fails at startup when the transport is memory, since other replicas would never see the events.
  • Payload limit. Messages over 256 KiB are refused, so one large event can't fill the broker.
  • Broker URLs are logged with their passwords removed.

Stats ​

Messaging.stats() returns counters since the process started:

ts
const { published, processed, retried, failed, duplicates } = Messaging.stats();

failed counts dead letters; duplicates counts copies skipped by dedupe. Expose them on a metrics route, or log them.

Testing ​

Messaging.fake() records events, messages and jobs instead of sending them. See Testing.

Redis ​

Each message type is a stream, megh:stream:<type>. Each group is a consumer group on it. A message a crashed consumer never acknowledged is handed to another one after claimAfter.

Delayed messages wait in the sorted set megh:delayed, which every replica checks once a second. Dead letters are in the stream megh:dlq.

ts
app.useMessaging({
  transport: 'redis',
  redis: {
    url: process.env.REDIS_URL,
    prefix: 'shop',          // keys start with shop: instead of megh:
    maxStreamLength: 100_000, // messages kept per type, roughly
    claimAfter: 60_000,       // redeliver unacknowledged messages after a minute
  },
});

redis also takes host, port, username, password, db, tls, blockFor and delayPollInterval. Streams keep up to maxStreamLength processed messages, so you can read them again with Redis tools.

RabbitMQ ​

Events are published to the durable topic exchange megh.events, routed by type. Each group gets a durable queue, megh.<group>.<type>, bound to the types it handles. Dead letters go to the queue megh.dlq.

Delays use a queue per type and delay, megh.delay.<type>.<ms>, whose messages expire into the exchange. No broker plugin is needed. RabbitMQ deletes a delay queue after a minute without use.

ts
app.useMessaging({
  transport: 'rabbitmq',
  url: process.env.RABBITMQ_URL,
  rabbitmq: {
    exchange: 'shop.events', // default megh.events
    prefetch: 10,            // messages fetched ahead per listener
    heartbeat: 30,           // seconds
  },
});

Megh reconnects after a dropped connection and restores its listeners.

Limitations ​

  • Kafka is not supported.
  • Delays on Redis Cluster. Delayed messages move from megh:delayed to their streams in one Lua script, which touches keys in different slots. That works on a single Redis server or a replicated one, but not on Redis Cluster.
  • Dedupe on RabbitMQ is per process unless you use the database store. Without the outbox, 'auto' picks memory, and Megh logs a warning in production. Set dedupe: { store: 'database' } to share it.
  • Retries wait inside the consumer. While a message waits for its next attempt, it holds one of the listener's concurrency slots. A long backoff with many retries slows that listener down. For long waits, dead-letter early and retry with megh messaging:failed retry.
  • Ordering. Redis keeps the order of messages of one type, but retries and concurrency above 1 can still change the order handlers see. RabbitMQ guarantees no order. Don't rely on it.

Released under the MIT License.