Skip to content

The Mechanic: NestJS Microservices

🏗️ The Mechanic: NestJS Microservices

In a standard application, we communicate via HTTP. In a distributed system, we use Message Brokers like RabbitMQ, Kafka, or NATS. NestJS provides a “Transporter” abstraction that makes this seamless.

1. The Mechanic: Message Handlers

Instead of @Get() or @Post(), microservices use @MessagePattern() or @EventPattern().

🧩 The Difference: Request/Response vs Event

  • Message Pattern: The sender waits for a reply (like an HTTP request).
  • Event Pattern: The sender “emits” the event and doesn’t wait (like “fire and forget”).

The Microservice Pattern:

@Controller()
export class OrderController {
  @EventPattern('order_created') // 🟦 Emitted by another service
  handleOrderCreated(data: any) {
    console.log('Processing order...', data);
  }
}

2. The Abstraction: ClientsModule

NestJS allows you to interact with remote services as if they were local providers.

@Module({
  imports: [
    ClientsModule.register([
      { name: 'ORDER_SERVICE', transport: Transport.RMQ, ... },
    ]),
  ],
})

🧪 Professor’s Challenge: The Distributed Logger

Task: Build two services that communicate via a message broker.

  1. Service A (The Producer): Emits a log_message event every 5 seconds.
  2. Service B (The Consumer): Listens for log_message and prints it to the console.
  3. Shut down Service B and notice how Service A keeps emitting. Then start Service B and see it catch up on all the “backlogged” messages.