In a NestJS 12 microservice, what is the difference between a @MessagePattern() handler and an @EventPattern() handler?
answer
- two message styles
- reply expected or not
- request packets carry an id
- one handler versus many per pattern
basics
~10 sA @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 sBoth 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 linesimport { 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
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.
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.
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.
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.