Skip to main content

What are microservices in NestJS?

What microservices are in NestJS

A microservice in NestJS is a separate application (or part of a system) that talks to other services not over HTTP, but through a message-based transport layer (a message broker).

Every microservice:

  • is independent of the others;
  • has its own data store;
  • performs a tightly scoped function (e.g. Auth, Orders, Payments);
  • communicates via transport protocols (TCP, Redis, RabbitMQ, Kafka, NATS, and others).

The core idea

Instead of direct HTTP requests like:

javascript
AuthUsersOrdersPayments

NestJS microservices interact through messages:

javascript
[Client] (send message)[Microservice]

Each service listens for certain message patterns, and responds without knowing anything about how the other services are implemented.

A simple diagram

javascript
┌───────────────────┐ ┌────────────────────┐ Auth Microservice │◀────▶│ Users Microservice└───────────────────┘ └────────────────────┘ ▲ ▲ │ │ ▼ ▼ [Gateway API][Message Broker]

Every service is wired together through a broker (e.g. Redis, RabbitMQ, or Kafka). If one of them goes down, the others keep working.

A microservice example in NestJS

The service

javascript
// math.service.ts import { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class MathController { @MessagePattern({ cmd: 'sum' }) accumulate(data: number[]): number { return (data || []).reduce((a, b) => a + b); } }

The module

javascript
import { Module } from '@nestjs/common'; import { MathController } from './math.controller'; @Module({ controllers: [MathController], }) export class MathModule {}

Bootstrapping the microservice

javascript
import { NestFactory } from '@nestjs/core'; import { Transport, MicroserviceOptions } from '@nestjs/microservices'; import { MathModule } from './math.module'; async function bootstrap() { const app = await NestFactory.createMicroservice<MicroserviceOptions>( MathModule, { transport: Transport.TCP, // RabbitMQ, Kafka, Redis, etc. can be chosen instead options: { port: 4001 }, }, ); await app.listen(); } bootstrap();

The client (calling the microservice)

javascript
import { Controller, Get, Inject } from '@nestjs/common'; import { ClientProxy, ClientProxyFactory, Transport } from '@nestjs/microservices'; @Controller() export class AppController { private client: ClientProxy; constructor() { this.client = ClientProxyFactory.create({ transport: Transport.TCP, options: { port: 4001 }, }); } @Get() async getSum() { const result = await this.client.send({ cmd: 'sum' }, [1, 2, 3]).toPromise(); return { result }; // { result: 6 } } }

Here client.send() sends the { cmd: 'sum' } message, and the microservice listens for it via @MessagePattern({ cmd: 'sum' }).

Transport layers

NestJS supports several mechanisms for microservices to communicate:

TransportPurpose
TCPA simple way to connect services within a network
RedisA fast message broker with pub/sub
NATSA lightweight, high-throughput message broker
RabbitMQMessage queues, acknowledgments, routing
KafkaStreaming data transfer
MQTTIoT, lightweight devices
gRPCHigh-performance RPC communication (protobuf)

Principles of microservices in NestJS

PrincipleDescription
IsolationEach service is autonomous (has its own code, DB, config)
Message-based interactionAsynchronous communication instead of HTTP
ResilienceOne service failing doesn't break the whole system
ScalingA specific microservice can be scaled independently
Clear responsibilityEach microservice handles a narrow business function

An interaction pattern

Request-response (send / @MessagePattern)

The client sends a request and waits for a response.

javascript
client.send({ cmd: 'sum' }, [1, 2, 3])

Event-based (emit / @EventPattern)

The client just fires an event, with no response expected.

javascript
client.emit('user_created', { id: 1, name: 'John' })
javascript
@EventPattern('user_created') handleUserCreated(data: any) { console.log('New user:', data); }

When to use microservices

They're a good fit if:

  • the project is large and spans different business domains;
  • high scalability is needed;
  • it matters to be able to deploy services independently;
  • you want to use different technologies for different services;
  • the system needs to stay resilient when individual components fail.

They're not a good fit if:

  • the project is small, or a monolith is simpler to maintain;
  • the added network complexity isn't justified;
  • the team is small and doesn't need domains split apart.

An architecture example

javascript
┌─────────────┐ ┌─────────────┐ API Gateway │──────▶│ Auth Service│ (HTTP) (JWT/Auth)└─────────────┘ └─────────────┘ │ │ ▼ ▼ ┌─────────────┐ ┌─────────────┐ Orders Svc │◀────▶│ Payments Svc│ └─────────────┘ └─────────────┘

They all communicate through a message broker, not directly.

Summary

ConceptDescription
Microservices in NestJSIndependent parts of an application that communicate through messages
Main interface@MessagePattern() / @EventPattern()
Transport layersTCP, Redis, RabbitMQ, Kafka, NATS, MQTT, gRPC
Main advantagesScalability, fault tolerance, isolation
Core principleAsynchronous communication and loose coupling
Key classesClientProxy, ClientProxyFactory, MicroserviceOptions

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.