Microservices Architecture & Transporters
Microservices Architecture & Transporters
Microservices decompose a monolithic application into small, independently deployable services that communicate over a network. NestJS has first-class support for building microservices through @nestjs/microservices, which provides a uniform API over several underlying transporters — the communication channels between services.
Why Microservices?
- Independent scaling — scale only the services under load, not the whole app.
- Fault isolation — a crash in one service does not bring down the entire system.
- Technology freedom — each service can use a different language or database.
- Team autonomy — separate teams can own and deploy individual services.
Creating a Microservice with NestFactory.createMicroservice
Instead of NestFactory.create(), you call NestFactory.createMicroservice(), passing your root module and a transport options object. The microservice listens for messages rather than HTTP requests:
Message Patterns & Handlers
Controllers in a microservice use @MessagePattern() to register handlers for incoming messages. The pattern is a contract between the caller and the service — a string, number, or object:
For fire-and-forget notifications (no response expected), use @EventPattern() instead of @MessagePattern().
TCP Transporter
TCP is the simplest transporter — direct socket communication between services on the same network. It is reliable and low-latency but requires both services to be reachable by hostname/IP. Use it for internal, co-located services.
Redis Transporter
The Redis transporter uses Redis pub/sub to relay messages. The caller and the handler do not need direct network access to each other — they both connect to the Redis server. This decouples services and enables fan-out (multiple subscribers to one event):
Hybrid Applications (HTTP + Microservice)
A single NestJS process can act as both an HTTP server and a microservice listener. Call app.connectMicroservice() before app.startAllMicroservices() and app.listen():
Summary
NestJS microservices are bootstrapped with NestFactory.createMicroservice() and a transporter configuration. The TCP transporter provides direct socket communication; the Redis transporter decouples services through a broker. Handlers are decorated with @MessagePattern() (request-response) or @EventPattern() (fire-and-forget). Hybrid applications run HTTP and a microservice listener in the same process, enabling gradual decomposition of a monolith.