Skip to content

NestJS Message Patterns

Message patterns implement request-response communication between Nest microservices. This lesson covers @MessagePattern handlers and ClientProxy.send().

Request-Response With @MessagePattern

A consumer decorates a method with @MessagePattern({ cmd: 'sum' }). A producer calls client.send({ cmd: 'sum' }, payload) and receives an Observable/Promise reply. This is Nest's RPC style over the configured transporter.

@Controller()
export class MathController {
  @MessagePattern({ cmd: 'sum' })
  sum(data: number[]): number {
    return data.reduce((a, b) => a + b, 0);
  }
}

The pattern object { cmd: 'sum' } must match exactly between sender and receiver.

Sending a Message

@Inject('MATH_SERVICE') private client: ClientProxy;

add() {
  return this.client.send<number>({ cmd: 'sum' }, [1, 2, 3]);
}
  • send() expects a response; use it when the caller needs a result.
  • Register clients with ClientsModule.register([{ name: 'MATH_SERVICE', ... }]).
  • Patterns can be strings or objects; objects help namespace commands.
  • Handle errors and timeouts explicitly on the caller side.

Message Pattern Cheatsheet

RPC-style Nest microservice messaging.

API Purpose
@MessagePattern(pattern) Handle request-response messages
client.send(pattern, data) Send and wait for a reply
ClientsModule.register Configure ClientProxy providers
@Payload() Explicitly read message payload
@Ctx() Access transporter context / metadata

Timeouts and Resilience

Network calls fail. Pipe RxJS timeout() on send() Observables and decide retry vs fail policies. Circuit breaking may belong at the gateway.

Versioning Commands

Include version in patterns ({ cmd: 'sum', v: 2 }) when breaking payload changes, so old and new consumers can coexist during migrations.

Common Mistakes

  • Using emit when you needed a response (or send for fire-and-forget fan-out).
  • Mismatched pattern objects between services.
  • Blocking the event loop with heavy CPU work inside message handlers.
  • Ignoring transporter-specific message sizes and serialization limits.

Key Takeaways

  • @MessagePattern + send() provide RPC over Nest transporters.
  • Pattern identity must match exactly.
  • Configure ClientProxy via ClientsModule.
  • Add timeouts and versioning for production robustness.

Pro Tip

Centralize message pattern constants in a shared package so producers and consumers never drift due to typo'd string commands.