{"id":"6b09aa815a5e2dbc3f20a499","slug":"nestjs-microservices","title":"Microservices in NestJS 12 – transports, message and event patterns, outbox and idempotent consumers","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"topics":["nestjs","microservices","event-driven-architecture"],"techs":["node","typescript"],"tags":["nestjs-12","microservices","rabbitmq","kafka","redis","transactional-outbox","idempotent-consumer","message-patterns","hybrid-app","esm"],"level":"advanced","kind":"tutorial","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":21,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T16:06:25.401Z","updatedAt":"2026-11-27T17:24:12.632Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"green","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"NestJS 12 microservices step by step – @MessagePattern vs @EventPattern, ClientProxy send and emit, TCP, Redis, RabbitMQ and Kafka transports, hybrid apps with connectMicroservice, transactional outbox, idempotent consumer, manual ack, prefetch, dead-letter queue and common mistakes.","wordCount":4162,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Splitting an application into services is not just several processes instead of one. Above all, it is a set of decisions about "},{"type":"text","text":"how services talk","marks":[{"type":"bold"}]},{"type":"text","text":": 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."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"@MessagePattern","marks":[{"type":"code"}]},{"type":"text","text":" + ","marks":[{"type":"bold"}]},{"type":"text","text":"client.send()","marks":[{"type":"code"}]},{"type":"text","text":" is a request with a response (like RPC) – always with a timeout. "},{"type":"text","text":"@EventPattern","marks":[{"type":"code"}]},{"type":"text","text":" + ","marks":[{"type":"bold"}]},{"type":"text","text":"client.emit()","marks":[{"type":"code"}]},{"type":"text","text":" announces a fact and does not wait for a result – for that you need a durable broker."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A transactional outbox","marks":[{"type":"bold"}]},{"type":"text","text":" stores the event in the same transaction as the data change, and a separate process publishes it. An order can never \"lose\" its event, even when the broker is down."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"\"At least once\" delivery means duplicates.","marks":[{"type":"bold"}]},{"type":"text","text":" The consumer must be idempotent: it records the processed message ID together with the effect and acknowledges ("},{"type":"text","text":"ack","marks":[{"type":"code"}]},{"type":"text","text":") only after the transaction commits."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you will build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Three services in one NestJS 12 repository (ESM, TypeScript 6): "},{"type":"text","text":"menu","marks":[{"type":"bold"}]},{"type":"text","text":" (a TCP microservice that prices an order), "},{"type":"text","text":"orders","marks":[{"type":"bold"}]},{"type":"text","text":" (a hybrid app: REST API + RabbitMQ consumer, SQLite with an outbox table and an event relay) and "},{"type":"text","text":"kitchen","marks":[{"type":"bold"}]},{"type":"text","text":" (a RabbitMQ consumer with deduplication, manual "},{"type":"text","text":"ack","marks":[{"type":"code"}]},{"type":"text","text":" and a \"ready\" event sent back). You start the broker with "},{"type":"text","text":"docker compose","marks":[{"type":"code"}]},{"type":"text","text":", and the databases use built-in "},{"type":"text","text":"node:sqlite","marks":[{"type":"code"}]},{"type":"text","text":", so no other services are needed. You can download the code as a ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"NestJS in practice","marks":[{"type":"link","attrs":{"href":"/en/articles/nestjs"}}]},{"type":"text","text":" (modules, providers, controllers), Node.js 24 LTS, Docker. Knowing the "},{"type":"text","text":"microservices style","marks":[{"type":"link","attrs":{"href":"/en/topics/microservices"}}]},{"type":"text","text":" and "},{"type":"text","text":"event-driven architecture","marks":[{"type":"link","attrs":{"href":"/en/topics/event-driven-architecture"}}]},{"type":"text","text":" helps."}]},{"type":"stats","attrs":{"items":[{"value":"3","label":"services","hint":"menu (TCP), orders (HTTP + RMQ), kitchen (RMQ)"},{"value":"2","label":"communication styles","hint":"request-response and events"},{"value":"1","label":"transaction","hint":"order + outbox together or not at all"},{"value":"0","label":"lost orders","hint":"with the broker and the kitchen switched off (logs below)"}]}},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  C[\"Client / frontend\"] -->|\"POST /orders\"| O[\"orders<br/>HTTP + RMQ consumer\"]\n  O -->|\"menu.quote (TCP, send)<br/>2 s timeout\"| M[\"menu<br/>@MessagePattern\"]\n  O --> DB[(\"orders.db<br/>orders + outbox\")]\n  DB -.->|\"OutboxRelay every 500 ms\"| R1[[\"RabbitMQ<br/>kitchen queue\"]]\n  R1 -->|\"order.placed (emit)\"| K[\"kitchen<br/>@EventPattern, ack\"]\n  K --> KDB[(\"kitchen.db<br/>processed_messages + tickets\")]\n  K -->|\"order.ready (emit)\"| R2[[\"RabbitMQ<br/>orders queue\"]]\n  R2 --> O","caption":"The dumpling-shop services and the message flow"}},{"type":"heading","attrs":{"level":2,"id":"message-or-event"},"content":[{"type":"text","text":"Message or event?"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph"}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"@MessagePattern","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"send()","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"@EventPattern","marks":[{"type":"code"}]},{"type":"text","text":" + "},{"type":"text","text":"emit()","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Semantics"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"price this for me\" – a question"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"order placed\" – a fact"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Response"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes, an "},{"type":"text","text":"Observable","marks":[{"type":"code"}]},{"type":"text","text":" with a result or an error"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"When the receiver is down"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"error or timeout for the caller"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the message waits in the queue (if the broker is durable)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Coupling"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"temporal – both services must run at the same time"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"loose – the receiver processes it when it is back"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Example"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"menu, prices, availability checks"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"kitchen, notifications, loyalty programme"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Rule of thumb: use requests where the caller "},{"type":"text","text":"cannot continue","marks":[{"type":"bold"}]},{"type":"text","text":" 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."}]},{"type":"heading","attrs":{"level":2,"id":"transports-what-they-actually-guarantee"},"content":[{"type":"text","text":"Transports: what they actually guarantee"}]},{"type":"paragraph","content":[{"type":"text","text":"Handlers look the same for every transport – only the options change. But delivery guarantees differ, and they drive the choice."}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Transport"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Model"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Guarantee"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"When"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"TCP"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"direct connection"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no persistence"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"requests inside a cluster, simple and fast"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Redis (pub/sub)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"publish/subscribe"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"at most once – offline means lost"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"nice to have\" notifications, cache invalidation"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"NATS"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"publish/subscribe, request-reply"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"at most once (JetStream: durable streams)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"low latency, many services"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"RabbitMQ"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"queues and exchanges"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"at least once with "},{"type":"text","text":"ack","marks":[{"type":"code"}]},{"type":"text","text":" and a durable queue"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"business jobs and events, routing, DLQ"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kafka"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"partitioned log"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"at least once, ordering per partition, history replay"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"event streams, large scale, many consumers, analytics"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"gRPC"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"HTTP/2 + Protobuf"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"like TCP, with a "},{"type":"text","text":".proto","marks":[{"type":"code"}]},{"type":"text","text":" contract"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"requests across teams and languages"}]}]}]}]},{"type":"codeGroup","attrs":{"title":"The same handlers, different transports"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/examples/transports.ts"},"content":[{"type":"text","text":"import { Transport, type MicroserviceOptions } from \"@nestjs/microservices\";\n\n// The same handlers (@MessagePattern / @EventPattern) work with any transport –\n// only the options change. What changes in behaviour is delivery semantics.\n\n// TCP: request-response inside a cluster, no broker, no persistence.\nexport const tcp: MicroserviceOptions = {\n  transport: Transport.TCP,\n  options: { host: \"0.0.0.0\", port: 4001 },\n};\n\n// Redis pub/sub: simple and fast, but at-most-once – a subscriber that is down misses messages.\nexport const redis: MicroserviceOptions = {\n  transport: Transport.REDIS,\n  options: { host: \"redis\", port: 6379 },\n};\n\n// RabbitMQ with a topic exchange: every service binds its own queue → fan-out of one event.\nexport const rabbitFanOut: MicroserviceOptions = {\n  transport: Transport.RMQ,\n  options: {\n    urls: [\"amqp://rabbitmq:5672\"],\n    queue: \"notifications\",\n    queueOptions: { durable: true, arguments: { \"x-dead-letter-exchange\": \"pierogi.dlx\" } },\n    exchange: \"pierogi.events\",\n    exchangeType: \"topic\",\n    routingKey: \"order.*\",\n    noAck: false,\n    prefetchCount: 10,\n  },\n};\n\n// Kafka: a partitioned log. Order is kept per partition (per key), consumers in a group\n// share partitions, and a new consumer group can replay history.\nexport const kafka: MicroserviceOptions = {\n  transport: Transport.KAFKA,\n  options: {\n    client: { clientId: \"kitchen\", brokers: [\"kafka:9092\"] },\n    consumer: { groupId: \"kitchen-consumers\" },\n    subscribe: { fromBeginning: false },\n    run: { partitionsConsumedConcurrently: 3 },\n  },\n};\n\n// Producing to Kafka with a key: all events of one order land in the same partition, in order.\nexport const kafkaMessage = (orderId: string, payload: object) => ({ key: orderId, value: JSON.stringify(payload) });"}]}]},{"type":"paragraph","content":[{"type":"text","text":"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 "},{"type":"text","text":"@confluentinc/kafka-javascript","marks":[{"type":"code"}]},{"type":"text","text":" – a librdkafka-based client with a KafkaJS-compatible API – with a custom transport or by using the client directly in a service."}]},{"type":"heading","attrs":{"level":2,"id":"step-1-a-nestjs-12-project-esm"},"content":[{"type":"text","text":"Step 1. A NestJS 12 project (ESM)"}]},{"type":"paragraph","content":[{"type":"text","text":"NestJS 12 (released in August 2026) ships its packages as ESM. CommonJS apps still run thanks to Node's "},{"type":"text","text":"require(esm)","marks":[{"type":"code"}]},{"type":"text","text":", but a new project is best set up as ESM right away: "},{"type":"text","text":"\"type\": \"module\"","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"module: \"nodenext\"","marks":[{"type":"code"}]},{"type":"text","text":" and relative imports with a "},{"type":"text","text":".js","marks":[{"type":"code"}]},{"type":"text","text":" extension. Nest CLI 12 requires TypeScript 6, and running apps needs Node 20.19+ or 22.12+ (we use 24). In this project plain "},{"type":"text","text":"tsc","marks":[{"type":"code"}]},{"type":"text","text":" is enough – the three services compile to "},{"type":"text","text":"dist/","marks":[{"type":"code"}]},{"type":"text","text":" and start with separate scripts."}]},{"type":"codeGroup","attrs":{"title":"Configuration, broker and the shared contract"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-microservices\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"type\": \"module\",\n  \"engines\": { \"node\": \">=24\" },\n  \"scripts\": {\n    \"build\": \"tsc -p tsconfig.json\",\n    \"start:menu\": \"node dist/menu/main.js\",\n    \"start:kitchen\": \"node dist/kitchen/main.js\",\n    \"start:orders\": \"node dist/orders/main.js\",\n    \"broker\": \"docker compose up -d rabbitmq\"\n  },\n  \"dependencies\": {\n    \"@nestjs/common\": \"^12.6.3\",\n    \"@nestjs/core\": \"^12.6.3\",\n    \"@nestjs/microservices\": \"^12.6.3\",\n    \"@nestjs/platform-express\": \"^12.6.3\",\n    \"amqp-connection-manager\": \"^5.0.1\",\n    \"amqplib\": \"^2.4.2\",\n    \"reflect-metadata\": \"^0.2.2\",\n    \"rxjs\": \"^7.8.2\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@types/express\": \"^5.0.6\",\n    \"@types/node\": \"^24.19.4\",\n    \"typescript\": \"~6.0.3\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"es2023\",\n    \"module\": \"nodenext\",\n    \"moduleResolution\": \"nodenext\",\n    \"types\": [\"node\"],\n    \"outDir\": \"dist\",\n    \"rootDir\": \"src\",\n    \"strict\": true,\n    \"experimentalDecorators\": true,\n    \"emitDecoratorMetadata\": true,\n    \"skipLibCheck\": true,\n    \"sourceMap\": true\n  },\n  \"include\": [\"src\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"yaml","filename":"docker-compose.yml"},"content":[{"type":"text","text":"services:\n  rabbitmq:\n    image: rabbitmq:4-management-alpine\n    ports:\n      - \"5672:5672\"   # AMQP\n      - \"15672:15672\" # management UI (guest/guest, local only)\n    healthcheck:\n      test: [\"CMD\", \"rabbitmq-diagnostics\", \"-q\", \"ping\"]\n      interval: 10s\n      retries: 5"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/contracts.ts"},"content":[{"type":"text","text":"import type { RmqOptions } from \"@nestjs/microservices\";\n\n// Shared contract between services: pattern names and message shapes.\n// In a monorepo this lives in a package (e.g. libs/contracts) versioned with care.\nexport const MENU_SERVICE = Symbol(\"MENU_SERVICE\");\nexport const KITCHEN_QUEUE = Symbol(\"KITCHEN_QUEUE\");\nexport const ORDERS_QUEUE = Symbol(\"ORDERS_QUEUE\");\n\nexport const Patterns = { quote: \"menu.quote\" } as const; // request-response\nexport const Events = { orderPlaced: \"order.placed\", orderReady: \"order.ready\" } as const; // fire-and-forget\n\nexport type OrderItem = { dishId: string; quantity: number };\nexport type QuoteRequest = { items: OrderItem[] };\nexport type QuoteLine = OrderItem & { name: string; priceCents: number };\nexport type QuoteResponse = { lines: QuoteLine[]; totalCents: number };\n\nexport type OrderPlacedEvent = { eventId: string; orderId: string; lines: QuoteLine[]; placedAt: string };\nexport type OrderReadyEvent = { eventId: string; orderId: string; readyAt: string };\n\nexport const MENU_TCP = { host: process.env.MENU_HOST ?? \"127.0.0.1\", port: Number(process.env.MENU_PORT ?? 4001) };\n\n// Durable queue + persistent messages: survive a broker restart.\nexport function rmq(queue: string): NonNullable<RmqOptions[\"options\"]> {\n  return {\n    urls: [process.env.RABBITMQ_URL ?? \"amqp://guest:guest@localhost:5672\"],\n    queue,\n    queueOptions: { durable: true },\n    persistent: true,\n  };\n}"}]}]},{"type":"paragraph","content":[{"type":"text","text":"contracts.ts","marks":[{"type":"code"}]},{"type":"text","text":" 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 ("},{"type":"text","text":"order.placed.v2","marks":[{"type":"code"}]},{"type":"text","text":") and a transition period."}]},{"type":"heading","attrs":{"level":2,"id":"step-2-menu-request-response-over-tcp"},"content":[{"type":"text","text":"Step 2. Menu: request-response over TCP"}]},{"type":"codeGroup","attrs":{"title":"The menu controller and microservice bootstrap"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/menu/menu.controller.ts"},"content":[{"type":"text","text":"import { Controller, Logger } from \"@nestjs/common\";\nimport { MessagePattern, Payload, RpcException } from \"@nestjs/microservices\";\nimport { Patterns, type QuoteRequest, type QuoteResponse } from \"../contracts.js\";\n\nconst MENU: Record<string, { name: string; priceCents: number }> = {\n  ruskie: { name: \"Ruskie\", priceCents: 2400 },\n  meat: { name: \"With meat\", priceCents: 2700 },\n  spinach: { name: \"Spinach & feta\", priceCents: 2600 },\n};\n\n@Controller()\nexport class MenuController {\n  private readonly log = new Logger(MenuController.name);\n\n  // Request-response: the caller waits for the returned value (or an error).\n  @MessagePattern(Patterns.quote)\n  quote(@Payload() req: QuoteRequest): QuoteResponse {\n    const lines = req.items.map((item) => {\n      const dish = MENU[item.dishId];\n      if (!dish) throw new RpcException({ code: \"UNKNOWN_DISH\", message: `Unknown dish: ${item.dishId}` });\n      return { ...item, ...dish };\n    });\n    const totalCents = lines.reduce((sum, l) => sum + l.priceCents * l.quantity, 0);\n    this.log.log(`quote for ${lines.length} line(s): ${totalCents} cents`);\n    return { lines, totalCents };\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/menu/main.ts"},"content":[{"type":"text","text":"import \"reflect-metadata\";\nimport { Module } from \"@nestjs/common\";\nimport { NestFactory } from \"@nestjs/core\";\nimport { Transport, type MicroserviceOptions } from \"@nestjs/microservices\";\nimport { MENU_TCP } from \"../contracts.js\";\nimport { MenuController } from \"./menu.controller.js\";\n\n@Module({ controllers: [MenuController] })\nclass MenuModule {}\n\n// A pure microservice (no HTTP) listening on TCP – fine for request-response inside a cluster.\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(MenuModule, {\n  transport: Transport.TCP,\n  options: { host: \"0.0.0.0\", port: MENU_TCP.port },\n});\napp.enableShutdownHooks();\nawait app.listen();"}]}]}]},"toc":[{"id":"message-or-event","text":"Message or event?","level":2,"locked":false},{"id":"transports-what-they-actually-guarantee","text":"Transports: what they actually guarantee","level":2,"locked":false},{"id":"step-1-a-nestjs-12-project-esm","text":"Step 1. A NestJS 12 project (ESM)","level":2,"locked":false},{"id":"step-2-menu-request-response-over-tcp","text":"Step 2. Menu: request-response over TCP","level":2,"locked":false},{"id":"step-3-orders-a-hybrid-application","text":"Step 3. Orders: a hybrid application","level":2,"locked":true},{"id":"step-4-the-transactional-outbox","text":"Step 4. The transactional outbox","level":2,"locked":true},{"id":"step-5-kitchen-an-idempotent-consumer-with-manual-ack","text":"Step 5. Kitchen: an idempotent consumer with manual ack","level":2,"locked":true},{"id":"when-events-and-when-requests","text":"When events and when requests","level":2,"locked":true},{"id":"common-mistakes","text":"Common mistakes","level":2,"locked":true},{"id":"check-yourself","text":"Check yourself","level":2,"locked":true},{"id":"what-next","text":"What next","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":55,"visibleBlocks":20,"resources":[{"id":"6b0857bf3c96f2d34d0b4281","type":"article","provider":"web","url":"https://microservices.io/patterns/data/transactional-outbox.html","embedUrl":null,"title":"Microservices Pattern: Pattern: Transactional outbox","description":"First, write the message/event to a database OUTBOX table as part of the transaction that updates business objects, and then publish it to a message broker.","author":"Chris Richardson (microservices.io)","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["event-driven-architecture","microservices"],"techs":["general"],"tags":["databases","messaging","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":65,"verifiedAt":"2026-11-26T11:25:55.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857bf3c96f2d34d0b42c4","type":"article","provider":"web","url":"https://learn.microsoft.com/en-us/azure/architecture/patterns/idempotent-consumer","embedUrl":null,"title":"Idempotent Consumer Pattern","description":"Use the Idempotent Consumer pattern to safely process duplicate messages from at-least-once deliveries so that repeated processing has the same effects as processing once.","author":"Microsoft Azure Architecture Center","thumbnailUrl":"https://learn.microsoft.com/en-us/media/open-graph-image.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["azure","cloud"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":60,"verifiedAt":"2026-11-26T11:07:52.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857b33c96f2d34d0b36f0","type":"repo","provider":"github","url":"https://github.com/meysamhadeli/booking-microservices-nestjs","embedUrl":null,"title":"meysamhadeli/booking-microservices-nestjs","description":"Practical microservices, built with Nestjs, CQRS, Vertical Slice Architecture, Event-Driven Architecture, Postgres, RabbitMQ and the latest technologies.","author":"meysamhadeli","thumbnailUrl":"https://opengraph.githubassets.com/1/meysamhadeli/booking-microservices-nestjs","durationSec":null,"lang":"en","topics":["vertical-slice-architecture","event-driven-architecture","clean-architecture","cqrs","microservices"],"techs":["node","javascript","typescript"],"tags":["boilerplate","clean-architecture","cqrs","docker","event-driven-architecture","jwt","software-architecture","testing","databases","messaging"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2023-11-23T13:54:09.000Z","popularity":48,"verifiedAt":"2026-11-26T10:58:26.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:51.220Z","updatedAt":"2026-11-26T16:00:51.220Z"},{"id":"6b0857c03c96f2d34d0b4400","type":"article","provider":"web","url":"https://event-driven.io/en/deduplication-in-distributed-systems","embedUrl":null,"title":"Deduplication in Distributed Systems: Myths, Realities, and Practical Solutions - Event-Driven.io","description":"Last week, we discussed how to use queuing to guarantee idempotency. What’s idempotency? It’s when we ensure that no matter how often we run the same operation, we’ll…","author":"Oskar Dudycz (event-driven.io)","thumbnailUrl":"https://event-driven.io/_astro/2024-11-25-cover.CXdKto9X_1KuQVR.png","durationSec":null,"lang":"en","topics":["event-driven-architecture"],"techs":["general"],"tags":["event-sourcing","system-design","distributed-systems","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2024-11-25T00:00:00.000Z","popularity":50,"verifiedAt":"2026-11-26T11:28:21.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857c03c96f2d34d0b440b","type":"article","provider":"web","url":"https://devstyle.pl/devtalk-146-o-outbox-i-spektrum-wzorcow-at-least-once-z-jackiem-milewskim","embedUrl":null,"title":"DevTalk #146 – O outbox i spektrum wzorców “at least once” z Jackiem Milewskim | devstyle.pl","description":"Jacek Milewski o wzorcach dostarczania wiadomości: od fire-and-forget przez Outbox i Inbox po CDC.","author":"devstyle.pl","thumbnailUrl":"https://cms.devstyle.pl/wp-content/uploads/2026/07/feature-image_devstyle_devtalk.png","durationSec":null,"lang":"pl","topics":[],"techs":["general"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":50,"verifiedAt":"2026-11-26T11:28:06.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T16:01:02.417Z"},{"id":"6b0857c23c96f2d34d0b4570","type":"article","provider":"web","url":"https://event-driven.io/en/understanding-kafkas-consumer-protocol","embedUrl":null,"title":"Understanding Kafka's Consumer Protocol: A Deep Dive into How Consumers Talk to Brokers - Event-Driven.io","description":"Last week, we explored how Kafka consumers work in consumer groups and how rebalancing ensures partition distribution. That sparked an interesting question about how…","author":"Oskar Dudycz (event-driven.io)","thumbnailUrl":"https://event-driven.io/_astro/2025-01-27-cover.WoCoPnGW_2biuXL.png","durationSec":null,"lang":"en","topics":["event-driven-architecture"],"techs":["general"],"tags":["event-sourcing","messaging","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2025-01-27T00:00:00.000Z","popularity":50,"verifiedAt":"2026-11-26T11:28:20.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"}],"challenges":[{"id":"6b093dc291bd8fbaf2a0c8d8","slug":"payment-circuit-breaker","title":"Circuit breaker for a payment gateway","summary":"A circuit breaker with closed, open and half-open states, an injected clock, a trial-success threshold and a business-error filter – so a payment gateway outage does not take the whole shop down.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"architecture","status":"published","difficulty":"hard","topics":["circuit-breaker","microservices"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["circuit-breaker","resilience","fault-tolerance","state-machine","payments"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":40,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:26.251Z"},{"id":"6b093dc191bd8fbaf2a0c8d0","slug":"inventory-cqrs","title":"Inventory with CQRS – separate write and read models","summary":"Warehouse commands validated on their own write model, events on a bus and a projection building a read model with a low-stock report. The read model can be rebuilt from events alone.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"architecture","status":"published","difficulty":"medium","topics":["cqrs","event-driven-architecture"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["cqrs","read-model","projection","events","inventory"],"languages":["typescript","javascript","python","csharp","java","go"],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:25.519Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":104,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":46}]}}