Home / Articles

When a Moleculer event is not enough on NATS, Redis, or Kafka

Learn how Moleculer balances emit across NATS, Redis, and Kafka, why a down subscriber drops the event, and when sendToChannel is the call that keeps it.

Publisher: REACTAPP.TOP19 min read4378 words

This article is published in English.

Sources: Event-driven architecture in Node.js: pub/sub with NATS, Kafka and Redis — and when an event is not enough

A system of services usually starts with calls that wait for a reply. Publishing is what stops that system from acting like one program that merely happens to be split across processes. Look at checkout. The moment orders has to invoke mailer, then analytics, then inventory before a sale can finish, the order service has memorized three names it should never have stored. The call is only as quick as the slowest of those three, and the sale fails if any of them is offline. Reverse the direction. orders announces that a sale exists. Whoever needs to react listens. The producer no longer names its listeners.

Two questions still sit under every pub/sub design, and short tutorials usually skip both. When a listener runs as three copies, which copy receives the message? When no copy is running, does the message wait, or is it gone? The demos that follow answer both, on three different buses, and they end where a bare event cannot do the job and you need a payload that stays until someone acknowledges it.

Each sample was actually run. The logs were lifted from the processes, not reconstructed afterward. Fetch the services from this folder. A shell script called run.sh replays the five demos.

Moleculer in one paragraph, if you have not used it yet. A service is an ordinary object. Actions are the methods that accept a call and return a reply. Events are the handlers that listen. A broker starts the services and links nodes through a transporter, the bus that sits between them. You can aim that bus at Kafka, at NATS, at Redis, at AMQP, at MQTT, or at raw TCP. Publishing is broker.emit("order.created", payload). Listening is an events entry whose key is "order.created" and whose function receives ctx. Moleculer, not the bus, decides which subscriber instance is addressed, and that decision does not move when you change the bus. The comparison of three buses later on is possible only because of that.

Checkout without three downstream calls

orders keeps a counter and two actions. created sets this.seq to 0. create takes a string sku and a number qty that defaults to 1, builds an order whose total is qty * 10, and logs the id, the sku, the first eight characters of ctx.requestID, and ctx.level. It then publishes with ctx.emit("order.created", order) and returns the order. The comment on that line says the payload reaches one live instance of every service that is listening at that moment. cancel takes a numeric id, publishes with ctx.broadcast("order.cancelled", { id }), and returns the id flagged cancelled: true. Its comment says broadcast hits every instance of every listener.

// services/orders.service.js
module.exports = {
  name: "orders",
  created() { this.seq = 0; },

  actions: {
    create: {
      params: { sku: "string", qty: { type: "number", default: 1 } },
      async handler(ctx) {
        const order = { id: ++this.seq, sku: ctx.params.sku, qty: ctx.params.qty, total: ctx.params.qty * 10 };
        log(this, `orders.create #${order.id} (${order.sku}) - requestID ${ctx.requestID.slice(0, 8)}, level ${ctx.level}`);
        // event: delivered to ONE instance of every subscriber service that is online right now
        await ctx.emit("order.created", order);
        return order;
      },
    },
    cancel: {
      params: { id: "number" },
      async handler(ctx) {
        // broadcast: delivered to EVERY instance of every subscriber service
        await ctx.broadcast("order.cancelled", { id: ctx.params.id });
        return { id: ctx.params.id, cancelled: true };
      },
    },
  },
};

mailer is the first consumer. The order.created handler declares a params schema in the same fastest-validator form you would put on an action: id must be a number, sku a string, total a number. The handler logs the id, the sku, those eight request characters, ctx.meta.user, and the level, then publishes email.sent with orderId and a to built as the user plus @example.com. Events can chain from inside a handler, and the context keeps that request id as the level steps down. order.cancelled only logs that queued mail for the id is being dropped.

// services/mailer.service.js
module.exports = {
  name: "mailer",
  events: {
    "order.created": {
      // event payloads can be validated like action params (same fastest-validator schema)
      params: { id: "number", sku: "string", total: "number" },
      async handler(ctx) {
        const { id, sku } = ctx.params;
        log(this, `order.created #${id} (${sku}) — requestID ${ctx.requestID.slice(0, 8)}, meta.user ${ctx.meta.user}, level ${ctx.level}`);
        // events can chain: the context carries the same requestID one level deeper
        await ctx.emit("email.sent", { orderId: id, to: `${ctx.meta.user}@example.com` });
      },
    },
    "order.cancelled"(ctx) {
      log(this, `order.cancelled #${ctx.params.id} — dropping queued emails for it`);
    },
  },
};

analytics is the second consumer. A wildcard order.* logs ctx.eventName, the id, ctx.eventType, the sending ctx.nodeID, and the level. A separate email.sent handler logs the order id, the recipient, the short request id, and the level.

// services/analytics.service.js
module.exports = {
  name: "analytics",
  events: {
    "order.*"(ctx) {
      log(this, `${ctx.eventName} #${ctx.params.id} — ${ctx.eventType} from ${ctx.nodeID}, level ${ctx.level}`);
    },
    "email.sent"(ctx) {
      log(this, `email.sent for #${ctx.params.orderId} to ${ctx.params.to} — requestID ${ctx.requestID.slice(0, 8)}, level ${ctx.level}`);
    },
  },
};

log stamps a clock time and the node id onto the front of each line. That stamp is the whole helper. It exists so output from four processes can be sorted into one timeline.

The broker file has two settings that matter, and the bus is an environment variable so you can retarget the same file. nodeID is process.env.NODE_NAME when that is set, otherwise node- plus process.pid. transporter is process.env.TRANSPORTER when that is set, otherwise nats://localhost:4222. Comments in the file show the other URLs, redis://localhost:6379 and kafka://localhost:9092. The services do not change.

// moleculer.config.js
module.exports = {
  nodeID: process.env.NODE_NAME || `node-${process.pid}`,
  transporter: process.env.TRANSPORTER || "nats://localhost:4222",
  // "redis://localhost:6379"  or  "kafka://localhost:9092" — nothing else changes
};

Four processes are launched with moleculer-runner, each narrowed by a SERVICES= filter. app-1 runs orders. mailer-1 and mailer-2 run mailer. analytics-1 runs analytics. A fifth, disposable broker in client.js invokes orders.create four times, every call carrying meta: { user: "alice" }, then invokes orders.cancel once. The cancel in the log is for id 2.

emit picks one instance, broadcast hits all of them

The trace covers four creates, and each create publishes order.created, followed by that cancel.

--- 4× orders.create (each one emits order.created)
[app-1] orders.create #1 (SKU-1) — requestID 3b5d9c00, level 1
[analytics-1] order.created #1 — emit from app-1, level 2
[mailer-2] order.created #1 (SKU-1) — requestID 3b5d9c00, meta.user alice, level 2
[analytics-1] email.sent for #1 to alice@example.com — requestID 3b5d9c00, level 3
[app-1] orders.create #2 (SKU-2) — requestID 128071b0, level 1
[analytics-1] order.created #2 — emit from app-1, level 2
[mailer-1] order.created #2 (SKU-2) — requestID 128071b0, meta.user alice, level 2
[analytics-1] email.sent for #2 to alice@example.com — requestID 128071b0, level 3
[app-1] orders.create #3 (SKU-3) — requestID ab6b4a4f, level 1
[analytics-1] order.created #3 — emit from app-1, level 2
[mailer-2] order.created #3 (SKU-3) — requestID ab6b4a4f, meta.user alice, level 2
[analytics-1] email.sent for #3 to alice@example.com — requestID ab6b4a4f, level 3
[app-1] orders.create #4 (SKU-4) — requestID e1966cc6, level 1
[mailer-1] order.created #4 (SKU-4) — requestID e1966cc6, meta.user alice, level 2
[analytics-1] order.created #4 — emit from app-1, level 2
[analytics-1] email.sent for #4 to alice@example.com — requestID e1966cc6, level 3
--- orders.cancel #2 (broadcasts order.cancelled)
[mailer-2] order.cancelled #2 — dropping queued emails for it
[analytics-1] order.cancelled #2 — broadcast from app-1, level 2
[mailer-1] order.cancelled #2 — dropping queued emails for it

Three things in the trace tend to surprise people. Take them in the order they usually do.

Each order.created hit one mailer, never both. emit is a balanced publish. Every service that subscribed gets the event a single time. If that service has several instances, the registry on the emitting node selects one. The picks here alternate: mailer-2 handles #1, mailer-1 handles #2, mailer-2 handles #3, mailer-1 handles #4. Action calls already use that round-robin, and events reuse it. Analytics is another service, so it receives a copy of its own on every sale, which is why analytics-1 logs order.created for #1 through #4 even though only one mailer did. The broker treats the service name as an event group. One copy of an emit goes to each group. A queue group in NATS, or a consumer group in Kafka, splits work in a similar way. The difference is who chooses. Here the emitting broker chooses, which is why the split looks identical no matter which transporter you started. One consequence is easy to miss. Should the publishing node also be running a copy of that listener, registry.preferLocal hands the event to the local copy every time. The flag covers events as well as action calls.

Both mailer processes logged order.cancelled. A broadcast is delivered to each instance of each subscriber. Reach for that verb when every process has to act on its own: drop a local cache, reload configuration, notice that a node came online. Point it at "someone should send the confirmation" and you will send the mail twice. broadcastLocal is the narrower form. It only reaches services inside the same process, and it is how the broker publishes its own $node.connected and $services.changed events. In the log both mailers drop queued mail for #2, and analytics records the cancel as a broadcast from app-1 at level 2.

The request id crossed two hops, and alice crossed with it. orders.create for #1 ran at level 1 under request 3b5d9c00. The mailer handler ran at level 2 with that same id, and with the meta.user the client had attached to the action call, so the line shows alice and the follow-up address is alice@example.com. From inside the handler the mailer published email.sent, and analytics received it at level 3, still under 3b5d9c00. Creates #2, #3, and #4 repeat the pattern under 128071b0, ab6b4a4f, and e1966cc6. A handler is given a full context. You can read ctx.meta, inspect ctx.params, publish again through ctx.emit, call an action through ctx.call, and still see ctx.requestID. An event does not cut a trace short, and it does not strip the user or the tenant. Enable the tracing middleware and this chain is a single trace made of three spans. Nothing has to be copied across by hand.

Naming a group, or joining one

The publisher can name the group as well. The call below sends order.created only toward the group mailer, with id 99, sku SKU-99, and a total of 0:

await broker.emit("order.created", { id: 99, sku: "SKU-99", total: 0 }, ["mailer"]);

What came back:

=== 2. Event groups: emit only to the mailer group ===
[mailer-1] order.created #99 (SKU-99) — requestID dccf0532, meta.user undefined, level 1
[analytics-1] email.sent for #99 to undefined@example.com — requestID dccf0532, level 2

Analytics never recorded order.created for #99. It only recorded the email.sent that the mailer published afterward, and that second publish carried no group list, so analytics was eligible again. The logged address is undefined@example.com because this call set no meta.user. The request id is dccf0532, level 1 on mailer-1 and level 2 on analytics. Filtering on the way out is how you replay without double counting: hand order 99 to the mailer again, and do not let analytics tally it a second time. The opposite join works too. An event definition can set group: "mailer". That handler then shares the mailer's round-robin, and each event reaches only one of the two.

The schema is checked on the handler that declared it

The mailer put a params schema on its handler. Send a payload that does not match.

await broker.emit("order.created", { id: "oops" });

The two nodes do not agree about that payload:

== 3. Event payload validation ===
[analytics-1] order.created #oops — emit from client-3557966, level 1
--- and on the mailer node that rejected it:
[19:39:50.367Z] ERROR TRANSIT: ValidationError: Parameters validation error!
    at processCheckResponse (…/node_modules/moleculer/src/validators/base.js:103:6)
  data: [ { type: 'number', message: "The 'id' field must be a number.", field: 'id', actual: 'oops', nodeID: 'client-3557966', event: 'order.created' }, { type: 'required', message: "The 'sku' field is required.", field: 'sku', … }, { type: 'required', message: "The 'total' field is required.", field: 'total', … } ]

There are two consequences. The schema is enforced on the handler that declared it, and nowhere else. Analytics subscribed with order.* and declared no schema, so it logged #oops happily, noting an emit from client-3557966 at level 1. On the mailer the transit logger printed ValidationError: Parameters validation error!. The data lists three failures: id must be a number and the actual value was oops, sku is required, and total is required. That error was written on the mailer node and traveled no further. The client's broker.emit had already resolved. An event works like this: emit returns once the transporter has accepted the packet. It does not wait until a handler finishes. If a handler throws, for a bad payload or for any other reason, the broker that received it logs the error, and that is the end of the story. When the publisher must learn the outcome, the call you wanted was an action. Remember that contract when the mailer is taken offline in the later demo.

One set of services, three transporters

Two thousand events, one node publishing, one node subscribed, services left untouched:

=== 4. Same code, three transporters: 2 000 events, one emitter node → one subscriber node ===
--- TRANSPORTER=nats
  awaited each emit: 2000 events in 346 ms (5780 events/s) — received 2000, latency p50 2 ms, p99 8 ms, max 9 ms
  fire-and-forget: 2000 events in 305 ms (6557 events/s) — received 2000, latency p50 29 ms, p99 72 ms, max 72 ms
--- TRANSPORTER=redis
  awaited each emit: 2000 events in 287 ms (6969 events/s) — received 2000, latency p50 2 ms, p99 14 ms, max 16 ms
  fire-and-forget: 2000 events in 249 ms (8032 events/s) — received 2000, latency p50 3 ms, p99 20 ms, max 20 ms
--- TRANSPORTER=kafka
  awaited each emit: 2000 events in 5983 ms (334 events/s) — received 2000, latency p50 4 ms, p99 19 ms, max 96 ms
  fire-and-forget: 2000 events in 2105 ms (950 events/s) — received 2000, latency p50 1186 ms, p99 1936 ms, max 1955 ms

"Awaited each emit" means the loop waits for one broker.emit(...) to settle before it starts another. The fire-and-forget path launches the full set of 2,000 publishes first, and only then waits on the promises, so those latency numbers include sitting in line behind the previous 1,999. One computer, the brokers in Docker, a single pass. Treat the figures as shapes. They are not a benchmark. From run to run the NATS and Redis figures shifted by about 50 percent in either direction.

NATS and Redis land in the same band: a few thousand events a second out of one publishing loop, and delivery in the low milliseconds. On the awaited path NATS finished 2,000 events in 346 ms (5,780 a second), with p50 at 2 ms, p99 at 8 ms, and a max of 9 ms. Fire-and-forget there was 305 ms (6,557 a second), but p50 rose to 29 ms and p99 to 72 ms. Redis awaited was 287 ms (6,969 a second), p50 2 ms, p99 14 ms, max 16 ms. Its fire-and-forget run was 249 ms (8,032 a second), p50 3 ms, p99 20 ms, max 20 ms. Kafka on this path is 10 to 20 times slower, because the path asks it to do a job it was not shaped for. Awaited Kafka took 5,983 ms (334 a second), p50 4 ms, p99 19 ms, max 96 ms. Fire-and-forget finished the sends in 2,105 ms (950 a second) while p50 latency jumped to 1,186 ms, p99 to 1,936 ms, and the max to 1,955 ms. Every run still received all 2,000. How each transporter actually carries an event explains both the timings and the durability question that follows.

  • NATS (nats://) is core NATS pub/sub. Every node subscribes on a subject reserved for itself, MOL.EVENT.<nodeID>. The emitter's registry picks the destination node and publishes to that subject. You get at-most-once delivery, nothing is written to disk, and this is the fastest of the three. NATS also offers queue groups. With disableBalancer: true, Moleculer no longer selects the node on its own and leaves the spread to NATS inside the group. Of these three transporters, NATS is the only one that can take that job.
  • Redis (redis://) is Redis pub/sub: PUBLISH on one channel per node, with nodes registered as listeners on that channel. The meaning matches NATS. A publish that happens while no listener is attached is discarded. No queue sits behind the channel. Throughput is close to NATS, and a lot of stacks already run Redis for something else.
  • Kafka (kafka://) uses one topic for each node. The name is MOL.EVENT.<nodeID>, and the topic is created automatically. Every message goes to partition 0. Each Moleculer process is a consumer group by itself, groupId equal to that broker's unique instance id. Kafka's own group rebalancing, and replay from stored offsets, are left unused on purpose. The registry already chose an instance and aimed at a node, so the topic is only a pipe toward that node. Each emit is a round trip from the producer that does not return until the broker has acked, and that wait is where the roughly 3 ms on each event is spent.

Picking Kafka as the transporter because you want messages to survive a crash is the wrong reason. A transporter moves a packet from one node to another. The registry, the balancing, and the event routing live above that packet, and they act the same way on all three buses. Choose the bus for how you operate: which one is already installed, which one the operators can keep healthy, and how much latency you can spend. Durability belongs to the layer that was built to store messages. The next run is the one that makes that concrete.

The listener is restarting

This is the situation an event-driven deploy hits first. orders is up. mailer is mid-restart. Two orders come in.

=== 5. What happens when the subscriber is down ===
--- events: orders runs, mailer is NOT running; create 2 orders, then start the mailer
  → orders.create returned #1
  → orders.create returned #2
--- mailer log:
(nothing — the two events were delivered to nobody and are gone)

Both calls to emit resolved without complaint. orders.create returned #1 and then #2. No mailer endpoint was registered as online, so the registry had an empty destination list and transmitted nothing. The mailer process was back about three seconds later, and its log stayed empty. No copy had been kept. NATS stored nothing, Redis stored nothing, and Kafka would not play the event back either, for the reason in the notes above. That is at-most-once delivery. For a large share of events it is the contract you actually want. A hint that a user is typing, a sample of a metric, a push into a UI, a cache drop. Missing one is cheap, because the record behind it can be fetched again.

Mail that confirms an order is a different kind of message. So is a payment webhook, a reservation against stock, and any line that has to show up in an audit log. Those need a payload that remains stored until a consumer acknowledges it, that is attempted again when the handler throws, and that is parked where you can see it when the failures keep coming. Moleculer ships that behavior as @moleculer/channels, its own module. Adapters exist for AMQP, for NATS JetStream, for Kafka, and for Redis Streams. You add it as one middleware:

// moleculer.config.js (with CHANNELS=1)
const { Middleware: ChannelsMiddleware } = require("@moleculer/channels");

module.exports = {
  transporter: "nats://localhost:4222",   // still the transporter for calls and events
  middlewares: [
    ChannelsMiddleware({
      adapter: {
        type: "Redis",
        options: {
          maxRetries: 3,                                              // then dead-letter (or drop, if dead-lettering is off)
          deadLettering: { enabled: true, queueName: "FAILED_MESSAGES" },
          redis: {
            url: "redis://localhost:6379",
            consumerOptions: { minIdleTime: 1000, claimInterval: 200, processingAttemptsInterval: 500 },
            // minIdleTime: an unacked message is retried after 1 s (default: 1 hour)
          },
        },
      },
    }),
  ],
};

Calls and ordinary events still ride the transporter, which stays nats://localhost:4222. ChannelsMiddleware, required from @moleculer/channels, is pointed at a Redis adapter. maxRetries is 3, and after that the message is dead-lettered, or dropped if dead-lettering is turned off. deadLettering is enabled, and queueName is "FAILED_MESSAGES". The Redis URL is redis://localhost:6379. Under consumerOptions, minIdleTime is 1000, so an unacknowledged message is retried after 1 second rather than the default of 1 hour. claimInterval is 200 and processingAttemptsInterval is 500.

On the producer the change is a single branch. When process.env.CHANNELS equals "1", the create handler calls sendToChannel instead of emit:

// services/orders.service.js — create handler
if (process.env.CHANNELS === "1") {
  await this.broker.sendToChannel("order.created", order); // stored in the stream until a consumer acknowledges it
} else {
  await ctx.emit("order.created", order);
}

this.broker.sendToChannel("order.created", order) leaves the order in the stream until a consumer acknowledges it. The other branch still does ctx.emit("order.created", order).

The consumer grows a channels block next to events. Its handler is given the raw payload and no Moleculer context, because the stream may have been written by anything, not only by a broker. Pass context: true when headers should include ctx.meta and the trace. In the mailer, the handler logs a [channel] line with the id and the sku, and it throws when payload.id equals FAIL_ORDER. The thrown message says SMTP is down and names the order.

// services/mailer.service.js
channels: {
  "order.created": {
    async handler(payload) {
      log(this, `[channel] order.created #${payload.id} (${payload.sku})`);
      if (payload.id === FAIL_ORDER) throw new Error(`SMTP is down, could not mail order #${payload.id}`);
    },
  },
},

A support service reads the dead-letter queue. context: true is on, so the error the adapter attached can be read from ctx.headers, specifically x-error-name and x-error-message.

// services/support.service.js
channels: {
  FAILED_MESSAGES: {
    context: true,
    async handler(ctx) {
      log(this, `[dead-letter] order #${ctx.params.id} — ${ctx.headers["x-error-name"]}: ${ctx.headers["x-error-message"]}`);
    },
  },
},

The outage is staged again, plus a failure after recovery. Bring the mailer up long enough that its consumer group gets registered, then stop it. Create two orders during the gap. Start it once more. Only after that, create order #3, which this instance is configured to reject through FAIL_ORDER=3.

--- channels (CHANNELS=1, Redis Streams): same scenario
mailer-1 stopped
  → orders.create returned #1
  → orders.create returned #2
messages waiting in the stream: 2
--- order #3 makes the mailer throw: retries, then dead-letter
  → orders.create returned #3
[app-1] orders.create #1 (SKU-1) — requestID bf278ea3, level 1
[app-1] orders.create #2 (SKU-2) — requestID a68bf01b, level 1
[mailer-1] [channel] order.created #1 (SKU-1)
[mailer-1] [channel] order.created #2 (SKU-2)
[app-1] orders.create #3 (SKU-1) — requestID a7031da1, level 1
[mailer-1] [channel] order.created #3 (SKU-1)
[mailer-1] [channel] order.created #3 (SKU-1)
[mailer-1] [channel] order.created #3 (SKU-1)
[support-1] [dead-letter] order #3 — Error: SMTP is down, could not mail order #3
WARN  CHANNELS: Moved message to 'FAILED_MESSAGES' 1788550869933-0

While the mailer was stopped, XLEN on the Redis stream read 2, which was orders #1 and #2 waiting. Both were handed over as soon as that consumer attached again. Order #3 got three attempts, spaced one second apart. The throw meant the message stayed unacked. Once minIdleTime elapsed, the adapter took it back and sent it again. maxRetries then moved it onto FAILED_MESSAGES. Support picked it up there, original payload included, with the error text in the headers: Error: SMTP is down, could not mail order #3. The channels warning names the stream id 1788550869933-0. If several mailer instances were running they would share that consumer group, so the work would be spread the way emit spreads it, while the stream kept a record of what was still outstanding.

Events, channels, or just the wire

You get two verbs, and they do not promise the same thing. Treating them as one verb is the mistake.

  • emit and broadcast are events. The registry routes them to processes that are online at that moment. emit gives you one copy for the service. broadcast gives you one copy for each instance. Delivery is at most once, it does not depend on the transporter, and the hop stays under 10 ms. Use them to loosen coupling wherever a missed message is acceptable or can be rebuilt: metrics, a live update, a cache drop, or a signal that something changed and the reader should load it again. An ordinary system uses this path more often than people assume.
  • sendToChannel is the channels path. The payload sits in AMQP, JetStream, Kafka, or Redis Streams until a consumer acknowledges it. Failures are retried, then dead-lettered, and a consumer group balances the readers. Use it wherever loss has a cost: a confirmation email, a payment, a stock movement, an outbox, or a handoff to producers and consumers that are not Moleculer services.
  • The transporter is neither verb. It is the wire between nodes, carrying action calls and events together. Changing it does not change what emit guarantees. Choose NATS when the choice is open. Stay on Redis when Redis is already deployed. Run Kafka as a transporter only for a reason other than durability. When durability is the requirement, point Kafka at the channel adapter instead.

The logs make one comparison sharp. While the mailer process was up, it received every event. While that process was down, it received none. The service code was the same code. What changed was whether it was running. Write event handlers so that outcome is acceptable. When it is not, use a channel.

The services for these demos are in the same folder. From that folder, run.sh replays all five against local containers of Kafka, Redis, and NATS. The process versions were Node 22, Moleculer 0.15.2, and @moleculer/channels 0.3.1.