Skip to content

NestJS Microservices

NestJS supports microservice architectures with first-class transporters (TCP, Redis, NATS, Kafka, MQTT, gRPC, RabbitMQ). This lesson introduces creating microservice and hybrid applications.

Creating a Microservice App

Instead of (or in addition to) HTTP, a Nest microservice listens for messages on a transporter. Controllers use @MessagePattern / @EventPattern instead of HTTP route decorators.

const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
  transport: Transport.TCP,
  options: { host: '127.0.0.1', port: 8877 },
});
await app.listen();

Hybrid apps use NestFactory.create() then app.connectMicroservice() so one process can speak HTTP and a message bus.

Hybrid Application Skeleton

const app = await NestFactory.create(AppModule);
app.connectMicroservice<MicroserviceOptions>({
  transport: Transport.REDIS,
  options: { host: 'localhost', port: 6379 },
});
await app.startAllMicroservices();
await app.listen(3000);
  • Choose transporters based on requirements: reliability, ordering, fan-out, or RPC semantics.
  • Keep service boundaries aligned with domain ownership.
  • Use ClientProxy to send messages from HTTP APIs to workers.
  • Design idempotent consumers—message delivery can be at-least-once.

Microservices Cheatsheet

Common Nest transporters.

Transport Typical Use
TCP Simple RPC between Nest services
Redis Lightweight pub/sub and queues
NATS Cloud-native messaging
Kafka High-throughput event streams
RMQ Work queues with acknowledgements
gRPC Strongly typed contract RPC

Talking to Microservices

Inject ClientProxy (configured via ClientsModule.register) and call send() for request-response or emit() for fire-and-forget events.

this.client.send({ cmd: 'sum' }, [1, 2]).subscribe();
this.client.emit('order.created', { orderId });

Service Boundaries

Avoid a distributed monolith: do not share one database blindly across services. Prefer clear APIs and events between bounded contexts.

Common Mistakes

  • Turning every method call into a network hop without measuring latency cost.
  • Assuming messages arrive exactly once.
  • Sharing TypeORM entities across services instead of explicit contracts.
  • Missing timeouts and retries on ClientProxy calls.

Key Takeaways

  • Nest microservices use transporters and message/event patterns.
  • Hybrid apps can expose HTTP and microservice endpoints together.
  • ClientProxy.send / emit call other services.
  • Design for at-least-once delivery and clear service boundaries.

Pro Tip

Start with a modular monolith when the team is small; introduce Nest microservices when scaling, ownership, or deploy independence truly requires separate processes.