Microservices: @MessagePattern(), TCP, Redis, and Kafka Transporters
- Last updated
- Prerequisites:
- NestJS Controllers and Services
- Message Brokers / RPC concepts
- nestjs
- microservices
- message-pattern
- event-pattern
- redis
- kafka
- tcp
Read at your depth
The practical view
NestJS Microservices use transport layers (TCP, Redis, NATS, MQTT, RabbitMQ, Kafka, gRPC) instead of HTTP. Services receive messages using `@MessagePattern('cmd')` (Request-Response pattern) or `@EventPattern('event')` (Event-driven / Fire-and-Forget). Clients connect and emit messages using `ClientProxy` (`client.send('cmd', data)` for request-response, `client.emit('event', data)` for events).
The same idea in other frameworks
`@MessagePattern({ cmd: 'get_user' })` and `client.send({ cmd: 'get_user' }, id)`.Spring Cloud Stream / Spring Kafka `@KafkaListener` and `KafkaTemplate.send()`.FastAPI background tasks or Celery `@app.task` RPC worker queues.Go gRPC protobuf services with `pb.RegisterUserServiceServer()`.Legacy vs modern
HTTP REST Service-to-Service vs NestJS Microservice MessagePattern
HTTP REST introduces DNS and header serialization overhead; Microservice transports use binary framing and message brokers.
await axios.post('http://billing-service:3000/charge', data); // ❌ Tight HTTP couplingreturn this.client.send({ cmd: 'charge' }, orderData); // ✅ NEW: Transport-agnostic RPCInterview gotchas
Context
Interviewers test your knowledge of communication patterns (RPC vs Event-driven).
The mechanical answer
`client.send('pattern', data)` implements the **Request-Response pattern**: it returns an `Observable` and waits for the remote service to process the message and return a response. `client.emit('event', data)` implements the **Event-Driven / Fire-and-Forget pattern**: it returns an `Observable` that completes immediately once the message is published to the broker, without waiting for any response.
Trap
Using `client.send()` on an endpoint decorated with `@EventPattern()` will hang indefinitely because `@EventPattern` handlers do not send replies.
Context
Checks understanding of asynchronous message matching over brokers like RabbitMQ or Redis.
The mechanical answer
When `client.send()` executes, NestJS generates a unique UUID `correlationId` and attaches it to the message header along with a `replyTo` queue name. The client subscribes to the reply queue. When the receiver finishes processing, it publishes the result back to `replyTo` with the same `correlationId`. The client matches the incoming response's `correlationId` to the active Observable and resolves it.
Trap
If a broker payload strips header metadata, correlation ID matching will fail and the client Observable will time out.