skip to content

Microservices and Messaging

Nest serves handlers over TCP, Redis, NATS, Kafka or gRPC with message and event patterns, and runs hybrid HTTP apps. Interviewers ask why send() is request-reply and emit() fire-and-forget.

on this pageshow

explore

questions

6

In a NestJS 12 microservice, what is the difference between a @MessagePattern() handler and an @EventPattern() handler?

level: juniorimportance: should knowfreq 30%

answer

  1. two message styles
  2. reply expected or not
  3. request packets carry an id
  4. one handler versus many per pattern

basics

~10 s

A @MessagePattern() handler serves request-response: its return value goes back to whoever called ClientProxy.send(). An @EventPattern() handler serves fire-and-forget events from emit(): nothing is returned, and several handlers may share one pattern.

solid answer

~40 s

Both decorators come from `@nestjs/microservices` and only work on methods of a `@Controller()` class; Nest ignores them on providers. `@MessagePattern()` marks a request-response handler: whatever it returns (a value, a Promise, or an Observable that may reply several times) is sent back to the client that called `ClientProxy.send()`. `@EventPattern()` marks an event handler for `ClientProxy.emit()`: there is no reply channel, so its return value is not delivered, and several handlers may share one event pattern, which Nest runs in parallel. They also fail differently: on the TCP transporter a `send()` with no matching handler errors with "There is no matching message handler defined in the remote service.", while an unmatched event is only logged by the consumer.

code

typescript · 17 lines
typescript
import { Controller } from '@nestjs/common';
import { EventPattern, MessagePattern, Payload } from '@nestjs/microservices';

@Controller()
export class AuditController {
  // a second handler for the same event: both run in parallel
  @EventPattern('order_placed')
  record(@Payload() order: { id: string }) {
    console.log(`audit: order ${order.id} placed`);
  }

  // request-response: the returned object is the reply
  @MessagePattern({ cmd: 'audit_count' })
  async count(): Promise<{ total: number }> {
    return { total: 42 };
  }
}

go deeper

for a junior

Recall which decorator pairs with send() and which with emit(), that both go on controller methods, and that only the message pattern produces a reply.

for a middle

Explain what a message handler may return (value, Promise, Observable with several replies), how @Payload() and @Ctx() expose the data and the transport context, and why several event handlers may share one pattern.

for a senior

Show the failure modes: a send() to an unhandled pattern errors loudly on the caller, while an unhandled or failing event never reaches the producer, so event handlers need their own monitoring on the consumer.

for a principal

Treat the choice per interaction: request-response ties the caller to the callee's availability and latency, an event does not. Set a team rule for which cross-service calls must be events and who watches unhandled ones.

## Two message styles behind one transport layer In Nest, a **microservice** is an application whose controllers listen on a transport other than HTTP: TCP by default, or Redis, NATS, MQTT, RabbitMQ, Kafka or gRPC. Messages are routed by a **pattern**, a plain value such as the string `'order_placed'` or the object `{ cmd: 'check_stock' }`, which travels over the wire together with the data. Nest supports two message styles, and each has its own decorator from `@nestjs/microservices`: - **Request-response**, declared with `@MessagePattern()`. The caller sends with `ClientProxy.send()` and waits for an answer. - **Event-based**, declared with `@EventPattern()`. The caller publishes with `ClientProxy.emit()` and waits for nothing. Both decorators belong on methods of a `@Controller()` class. Controllers are the entry points of a Nest application, and the runtime ignores these decorators on ordinary providers, so a handler written on an `@Injectable()` service never receives a message and nothing reports the mistake. ## @MessagePattern(): the handler that answers A message handler's return value **is** the reply. Nest accepts three shapes: 1. A plain value, sent back once. 2. A `Promise` (an `async` method), whose resolved value is sent back. 3. An `Observable`, in which case each emitted value is sent back until the stream completes, so one request can receive several replies. To carry replies, Nest keeps a second logical channel for responses. Some transports provide one natively; for others Nest builds it, which adds overhead. On the TCP transporter the difference is visible in the packet itself: a request carries an `id` that matches the reply to its caller, while an event carries none. Nest keeps one message handler per pattern. If two methods register the same message pattern, the later registration replaces the earlier one in the handler map. ## @EventPattern(): the handler that only listens An event handler runs for its side effects. Its return value goes nowhere, because the producer is not waiting for a reply. Two consequences follow: - You may register **several handlers for one event pattern**, and Nest triggers all of them in parallel. In the order scenario, an inventory controller can reserve stock on `'order_placed'` while an audit controller records the same event. - Failures stay on the consumer. An error thrown by an event handler has no response stream to travel on, so the producer never learns about it. ## Reading the message: @Payload() and @Ctx() A handler's first argument is the data portion of the message. The parameter decorators make that explicit and add the transport details: - `@Payload()` injects the data, and `@Payload('sku')` extracts a single property of it. - `@Ctx()` injects a transport-specific context object: `TcpContext`, `RedisContext`, `NatsContext` (whose `getSubject()` returns the concrete subject behind a wildcard pattern), `MqttContext`, `RmqContext` or `KafkaContext` (with `getTopic()` and `getMessage()`). ```ts import { Controller } from '@nestjs/common'; import { Ctx, EventPattern, MessagePattern, Payload, TcpContext } from '@nestjs/microservices'; @Controller() export class InventoryController { @MessagePattern({ cmd: 'check_stock' }) checkStock(@Payload('sku') sku: string) { return { sku, available: 3 }; // sent back to the send() caller } @EventPattern('order_placed') reserve(@Payload() order: { id: string; sku: string }, @Ctx() ctx: TcpContext) { console.log(`reserving stock for ${order.id} (${ctx.getPattern()})`); } } ``` ## Side by side, including failure | | `@MessagePattern()` with `send()` | `@EventPattern()` with `emit()` | |---|---|---| | Caller waits for | a reply, or several | nothing | | Handler return value | sent back to the caller | not delivered | | Handlers per pattern | one (a later one replaces it) | several, run in parallel | | No matching handler (TCP) | the caller's Observable errors with "There is no matching message handler defined in the remote service." | the consumer logs "There is no matching event handler defined in the remote service." | | Handler throws | an error object reaches the caller | the producer never sees it | The last two rows are where production surprises come from. A typo in a message pattern breaks the caller loudly; the same typo in an event pattern leaves a log line on the consuming service while the events go unhandled. ## Choosing between them Use `@MessagePattern()` when the caller needs an answer before it can continue, such as the order service asking inventory whether stock is available. Use `@EventPattern()` to announce something that has already happened, such as an order being placed, so that any number of consumers can react without the producer waiting for them, or even knowing they exist.

  • Can a NestJS @MessagePattern() handler reply more than once to a single request?
    Yes. If the handler returns an `Observable`, Nest sends each emitted value back until the stream completes, so `from([1, 2, 3])` replies three times. On the caller, subscribing to the `send()` Observable sees every value, while `firstValueFrom()` keeps only the first and `lastValueFrom()` waits for completion and keeps the last.
  • In NestJS, what happens when two controller methods declare the same pattern?
    It depends on the style. Several `@EventPattern()` handlers for one pattern are all kept and triggered in parallel, which is how one event can update stock and write an audit record. For `@MessagePattern()`, Nest keeps a single handler per pattern, so the later registration replaces the earlier one: a request has exactly one responder.
  • Does the key order of an object pattern such as { cmd: 'check_stock', v: 1 } matter in NestJS?
    No. Nest normalises an object pattern into a string with its keys sorted before matching, so `{ v: 1, cmd: 'check_stock' }` and `{ cmd: 'check_stock', v: 1 }` reach the same handler. The values must still match exactly, and a different key set is a different pattern.

  • An @EventPattern() handler's return value is sent back to the service that emitted it.
  • @MessagePattern() works on any injectable service, not only on controller methods.
  • Only one @EventPattern() handler can exist for a given event pattern.
  • emit() waits for the consumer to finish, just as send() waits for a reply.
  • An event sent to a pattern nobody handles makes the producer's emit() fail.
open as a page

In a NestJS 12 order service, why does ClientProxy.send() deliver nothing until subscribed, while emit() publishes immediately?

level: middleimportance: should knowfreq 35%

basics

~10 s

ClientProxy.send() returns a cold Observable: the request is published only when something subscribes, and again for each subscription. emit() returns a hot Observable that dispatches the event immediately, whether or not anyone subscribes.

open as a page

A NestJS 12 hybrid app's global ValidationPipe and auth guard work on HTTP routes but never run for its message handlers. Why, and what fixes it?

level: seniorimportance: should knowfreq 25%

basics

~20 s

connectMicroservice() gives each connected listener its own empty config, so useGlobal*() enhancers and APP_GUARD or APP_PIPE providers stay HTTP-only. Pass { inheritAppConfig: true } as its second argument, after the useGlobal*() calls, to share them.

open as a page

In a NestJS 12 microservice, why does a NotFoundException thrown in a @MessagePattern() handler reach the caller as 'Internal server error'?

level: seniorimportance: should knowfreq 25%

basics

~10 s

Message handlers are served by Nest's base RPC exception filter, which only understands RpcException. Any other error, NotFoundException included, is replaced by { status: 'error', message: 'Internal server error' }. Throw RpcException instead.

open as a page

In NestJS 12, what must change when an order service's microservice transport moves from TCP to NATS or Kafka?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

The transport and options objects change on both sides: createMicroservice() or connectMicroservice() on the consumer, ClientsModule on the producer, plus the transporter's driver package. Handlers and patterns mostly stay; @Ctx() types and quirks such as Kafka reply topics change.

open as a page

As the lead for a NestJS 12 order service that serves a REST API and consumes broker messages, would you run one hybrid app or a separate microservice, and what does each commit the team to?

level: principalimportance: nice to knowfreq 15%

basics

~20 s

A hybrid app (NestFactory.create plus connectMicroservice) shares one process, container and release, so it is cheap but couples scaling, failure and configuration. A standalone createMicroservice app scales and fails on its own but adds a second deployable. Start hybrid while handlers are light; split on a written trigger.

open as a page