Tutorial · NestJS · Microservices
Microservices in NestJS 12 – transports, message and event patterns, outbox and idempotent consumers
We build three dumpling-shop services in NestJS 12 (ESM): a menu that answers over TCP, orders as a hybrid HTTP + RabbitMQ app with a transactional outbox, and a kitchen as an idempotent consumer with manual acknowledgements. We compare transports (TCP, Redis, RabbitMQ, Kafka) and check what happens when the broker or a service is down – with real logs.
Splitting an application into services is not just several processes instead of one. Above all, it is a set of decisions about how services talk: does a question need an immediate answer, or is announcing a fact enough; what happens when the receiver is down; can a message arrive twice. NestJS gives you a common API for many transports, but it does not make those decisions for you. In this tutorial you will build three dumpling-shop services and test them under failure scenarios – every log in the article comes from real runs of NestJS 12.6 with RabbitMQ 4.
Prerequisites: NestJS in practice (modules, providers, controllers), Node.js 24 LTS, Docker. Knowing the microservices style and event-driven architecture helps.
- 3
- services – menu (TCP), orders (HTTP + RMQ), kitchen (RMQ)
- 2
- communication styles – request-response and events
- 1
- transaction – order + outbox together or not at all
- 0
- lost orders – with the broker and the kitchen switched off (logs below)
Message or event?
@MessagePattern + send() | @EventPattern + emit() | |
|---|---|---|
| Semantics | "price this for me" – a question | "order placed" – a fact |
| Response | yes, an Observable with a result or an error | no |
| When the receiver is down | error or timeout for the caller | the message waits in the queue (if the broker is durable) |
| Coupling | temporal – both services must run at the same time | loose – the receiver processes it when it is back |
| Example | menu, prices, availability checks | kitchen, notifications, loyalty programme |
Rule of thumb: use requests where the caller cannot continue without the answer (you cannot place an order without a price). Anything that can happen a moment later should be announced with an event. A chain of synchronous calls A → B → C adds up latencies and multiplies failure risk.
Transports: what they actually guarantee
Handlers look the same for every transport – only the options change. But delivery guarantees differ, and they drive the choice.
| Transport | Model | Guarantee | When |
|---|---|---|---|
| TCP | direct connection | no persistence | requests inside a cluster, simple and fast |
| Redis (pub/sub) | publish/subscribe | at most once – offline means lost | "nice to have" notifications, cache invalidation |
| NATS | publish/subscribe, request-reply | at most once (JetStream: durable streams) | low latency, many services |
| RabbitMQ | queues and exchanges | at least once with ack and a durable queue | business jobs and events, routing, DLQ |
| Kafka | partitioned log | at least once, ordering per partition, history replay | event streams, large scale, many consumers, analytics |
| gRPC | HTTP/2 + Protobuf | like TCP, with a .proto contract | requests across teams and languages |
The same handlers, different transports
import { Transport, type MicroserviceOptions } from "@nestjs/microservices";
// The same handlers (@MessagePattern / @EventPattern) work with any transport –
// only the options change. What changes in behaviour is delivery semantics.
// TCP: request-response inside a cluster, no broker, no persistence.
export const tcp: MicroserviceOptions = {
transport: Transport.TCP,
options: { host: "0.0.0.0", port: 4001 },
};
// Redis pub/sub: simple and fast, but at-most-once – a subscriber that is down misses messages.
export const redis: MicroserviceOptions = {
transport: Transport.REDIS,
options: { host: "redis", port: 6379 },
};
// RabbitMQ with a topic exchange: every service binds its own queue → fan-out of one event.
export const rabbitFanOut: MicroserviceOptions = {
transport: Transport.RMQ,
options: {
urls: ["amqp://rabbitmq:5672"],
queue: "notifications",
queueOptions: { durable: true, arguments: { "x-dead-letter-exchange": "pierogi.dlx" } },
exchange: "pierogi.events",
exchangeType: "topic",
routingKey: "order.*",
noAck: false,
prefetchCount: 10,
},
};
// Kafka: a partitioned log. Order is kept per partition (per key), consumers in a group
// share partitions, and a new consumer group can replay history.
export const kafka: MicroserviceOptions = {
transport: Transport.KAFKA,
options: {
client: { clientId: "kitchen", brokers: ["kafka:9092"] },
consumer: { groupId: "kitchen-consumers" },
subscribe: { fromBeginning: false },
run: { partitionsConsumedConcurrently: 3 },
},
};
// Producing to Kafka with a key: all events of one order land in the same partition, in order.
export const kafkaMessage = (orderId: string, payload: object) => ({ key: orderId, value: JSON.stringify(payload) });One thing worth knowing about Kafka: Nest's transport uses the KafkaJS library, whose last release dates from February 2023. It works, but under heavy traffic consider @confluentinc/kafka-javascript – a librdkafka-based client with a KafkaJS-compatible API – with a custom transport or by using the client directly in a service.
Step 1. A NestJS 12 project (ESM)
NestJS 12 (released in August 2026) ships its packages as ESM. CommonJS apps still run thanks to Node's require(esm), but a new project is best set up as ESM right away: "type": "module", module: "nodenext" and relative imports with a .js extension. Nest CLI 12 requires TypeScript 6, and running apps needs Node 20.19+ or 22.12+ (we use 24). In this project plain tsc is enough – the three services compile to dist/ and start with separate scripts.
Configuration, broker and the shared contract
{
"name": "pierogi-microservices",
"private": true,
"version": "1.0.0",
"type": "module",
"engines": { "node": ">=24" },
"scripts": {
"build": "tsc -p tsconfig.json",
"start:menu": "node dist/menu/main.js",
"start:kitchen": "node dist/kitchen/main.js",
"start:orders": "node dist/orders/main.js",
"broker": "docker compose up -d rabbitmq"
},
"dependencies": {
"@nestjs/common": "^12.6.3",
"@nestjs/core": "^12.6.3",
"@nestjs/microservices": "^12.6.3",
"@nestjs/platform-express": "^12.6.3",
"amqp-connection-manager": "^5.0.1",
"amqplib": "^2.4.2",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.2",
"zod": "^4.6.7"
},
"devDependencies": {
"@types/express": "^5.0.6",
"@types/node": "^24.19.4",
"typescript": "~6.0.3"
}
}{
"compilerOptions": {
"target": "es2023",
"module": "nodenext",
"moduleResolution": "nodenext",
"types": ["node"],
"outDir": "dist",
"rootDir": "src",
"strict": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"sourceMap": true
},
"include": ["src"]
}services:
rabbitmq:
image: rabbitmq:4-management-alpine
ports:
- "5672:5672" # AMQP
- "15672:15672" # management UI (guest/guest, local only)
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 10s
retries: 5import type { RmqOptions } from "@nestjs/microservices";
// Shared contract between services: pattern names and message shapes.
// In a monorepo this lives in a package (e.g. libs/contracts) versioned with care.
export const MENU_SERVICE = Symbol("MENU_SERVICE");
export const KITCHEN_QUEUE = Symbol("KITCHEN_QUEUE");
export const ORDERS_QUEUE = Symbol("ORDERS_QUEUE");
export const Patterns = { quote: "menu.quote" } as const; // request-response
export const Events = { orderPlaced: "order.placed", orderReady: "order.ready" } as const; // fire-and-forget
export type OrderItem = { dishId: string; quantity: number };
export type QuoteRequest = { items: OrderItem[] };
export type QuoteLine = OrderItem & { name: string; priceCents: number };
export type QuoteResponse = { lines: QuoteLine[]; totalCents: number };
export type OrderPlacedEvent = { eventId: string; orderId: string; lines: QuoteLine[]; placedAt: string };
export type OrderReadyEvent = { eventId: string; orderId: string; readyAt: string };
export const MENU_TCP = { host: process.env.MENU_HOST ?? "127.0.0.1", port: Number(process.env.MENU_PORT ?? 4001) };
// Durable queue + persistent messages: survive a broker restart.
export function rmq(queue: string): NonNullable<RmqOptions["options"]> {
return {
urls: [process.env.RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672"],
queue,
queueOptions: { durable: true },
persistent: true,
};
}contracts.ts is the only place all services know about: pattern names, message shapes and queue options. Version the contract carefully: adding fields is safe; changing the meaning of a field or removing it requires a new event version (order.placed.v2) and a transition period.
Step 2. Menu: request-response over TCP
The menu controller and microservice bootstrap
import { Controller, Logger } from "@nestjs/common";
import { MessagePattern, Payload, RpcException } from "@nestjs/microservices";
import { Patterns, type QuoteRequest, type QuoteResponse } from "../contracts.js";
const MENU: Record<string, { name: string; priceCents: number }> = {
ruskie: { name: "Ruskie", priceCents: 2400 },
meat: { name: "With meat", priceCents: 2700 },
spinach: { name: "Spinach & feta", priceCents: 2600 },
};
@Controller()
export class MenuController {
private readonly log = new Logger(MenuController.name);
// Request-response: the caller waits for the returned value (or an error).
@MessagePattern(Patterns.quote)
quote(@Payload() req: QuoteRequest): QuoteResponse {
const lines = req.items.map((item) => {
const dish = MENU[item.dishId];
if (!dish) throw new RpcException({ code: "UNKNOWN_DISH", message: `Unknown dish: ${item.dishId}` });
return { ...item, ...dish };
});
const totalCents = lines.reduce((sum, l) => sum + l.priceCents * l.quantity, 0);
this.log.log(`quote for ${lines.length} line(s): ${totalCents} cents`);
return { lines, totalCents };
}
}import "reflect-metadata";
import { Module } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { Transport, type MicroserviceOptions } from "@nestjs/microservices";
import { MENU_TCP } from "../contracts.js";
import { MenuController } from "./menu.controller.js";
@Module({ controllers: [MenuController] })
class MenuModule {}
// A pure microservice (no HTTP) listening on TCP – fine for request-response inside a cluster.
const app = await NestFactory.createMicroservice<MicroserviceOptions>(MenuModule, {
transport: Transport.TCP,
options: { host: "0.0.0.0", port: MENU_TCP.port },
});
app.enableShutdownHooks();
await app.listen();The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Step 3. Orders: a hybrid application
- Step 4. The transactional outbox
- Step 5. Kitchen: an idempotent consumer with manual ack
- When events and when requests
- Common mistakes
- Check yourself
- What next