{"id":"6b09aa815a5e2dbc3f20a499","slug":"nestjs-microservices","title":"Mikroserwisy w NestJS 12 – transporty, wzorce wiadomości i zdarzeń, outbox i idempotentni konsumenci","summary":"Budujemy trzy usługi pierogarni w NestJS 12 (ESM): menu odpowiadające przez TCP, zamówienia jako aplikację hybrydową HTTP + RabbitMQ z transakcyjnym outboxem i kuchnię jako idempotentnego konsumenta z ręcznym potwierdzaniem. Porównujemy transporty (TCP, Redis, RabbitMQ, Kafka) i sprawdzamy, co się dzieje, gdy broker albo usługa leży – na prawdziwych logach.","servedLang":"pl","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":20,"stats":{"views":1,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T16:06:25.401Z","updatedAt":"2026-11-27T16:08:49.631Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"green","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"NestJS 12 microservices krok po kroku – @MessagePattern vs @EventPattern, ClientProxy send i emit, transport TCP, Redis, RabbitMQ i Kafka, aplikacja hybrydowa connectMicroservice, transactional outbox, idempotent consumer, ręczny ack, prefetch, dead-letter queue i typowe błędy.","wordCount":3913,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Rozbicie aplikacji na usługi to nie tylko kilka procesów zamiast jednego. To przede wszystkim decyzje o tym, "},{"type":"text","text":"jak usługi rozmawiają","marks":[{"type":"bold"}]},{"type":"text","text":": czy pytanie wymaga natychmiastowej odpowiedzi, czy wystarczy ogłosić fakt; co się stanie, gdy odbiorca leży; czy wiadomość może dotrzeć dwa razy. NestJS daje wspólne API dla wielu transportów, ale nie zwalnia z tych decyzji. W tym poradniku zbudujesz trzy usługi pierogarni i przetestujesz je w scenariuszach awarii – wszystkie logi w artykule pochodzą z prawdziwych uruchomień NestJS 12.6 z RabbitMQ 4."}]},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"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":" to zapytanie z odpowiedzią (jak RPC) – zawsze z limitem czasu. "},{"type":"text","text":"@EventPattern","marks":[{"type":"code"}]},{"type":"text","text":" + ","marks":[{"type":"bold"}]},{"type":"text","text":"client.emit()","marks":[{"type":"code"}]},{"type":"text","text":" ogłasza fakt i nie czeka na wynik – do tego potrzebujesz trwałego brokera."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Transakcyjny outbox","marks":[{"type":"bold"}]},{"type":"text","text":" zapisuje zdarzenie w tej samej transakcji co zmianę danych, a osobny proces je publikuje. Dzięki temu zamówienie nigdy nie „zgubi” zdarzenia, nawet gdy broker leży."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Dostarczanie „co najmniej raz” oznacza duplikaty.","marks":[{"type":"bold"}]},{"type":"text","text":" Konsument musi być idempotentny: zapisuje identyfikator przetworzonej wiadomości razem z efektem i potwierdza ("},{"type":"text","text":"ack","marks":[{"type":"code"}]},{"type":"text","text":") dopiero po zatwierdzeniu transakcji."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"Co zbudujesz"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Trzy usługi w jednym repozytorium NestJS 12 (ESM, TypeScript 6): "},{"type":"text","text":"menu","marks":[{"type":"bold"}]},{"type":"text","text":" (mikroserwis TCP wyceniający zamówienie), "},{"type":"text","text":"orders","marks":[{"type":"bold"}]},{"type":"text","text":" (aplikacja hybrydowa: REST API + konsument RabbitMQ, SQLite z tabelą outbox i przekaźnikiem zdarzeń) oraz "},{"type":"text","text":"kitchen","marks":[{"type":"bold"}]},{"type":"text","text":" (konsument RabbitMQ z deduplikacją, ręcznym "},{"type":"text","text":"ack","marks":[{"type":"code"}]},{"type":"text","text":" i odsyłaniem zdarzenia „gotowe”). Broker uruchamiasz przez "},{"type":"text","text":"docker compose","marks":[{"type":"code"}]},{"type":"text","text":", a bazy to wbudowany "},{"type":"text","text":"node:sqlite","marks":[{"type":"code"}]},{"type":"text","text":", więc nie potrzebujesz innych usług. Kod pobierzesz jako ZIP."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Wymagania wstępne:","marks":[{"type":"bold"}]},{"type":"text","text":" "},{"type":"text","text":"NestJS w praktyce","marks":[{"type":"link","attrs":{"href":"/pl/articles/nestjs"}}]},{"type":"text","text":" (moduły, providery, kontrolery), Node.js 24 LTS, Docker. Warto znać "},{"type":"text","text":"styl mikroserwisów","marks":[{"type":"link","attrs":{"href":"/pl/topics/microservices"}}]},{"type":"text","text":" i "},{"type":"text","text":"architekturę sterowaną zdarzeniami","marks":[{"type":"link","attrs":{"href":"/pl/topics/event-driven-architecture"}}]},{"type":"text","text":"."}]},{"type":"stats","attrs":{"items":[{"value":"3","label":"usługi","hint":"menu (TCP), orders (HTTP + RMQ), kitchen (RMQ)"},{"value":"2","label":"style komunikacji","hint":"zapytanie z odpowiedzią i zdarzenie"},{"value":"1","label":"transakcja","hint":"zamówienie + outbox razem albo wcale"},{"value":"0","label":"utraconych zamówień","hint":"przy wyłączonym brokerze i kuchni (logi poniżej)"}]}},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  C[\"Klient / frontend\"] -->|\"POST /orders\"| O[\"orders<br/>HTTP + konsument RMQ\"]\n  O -->|\"menu.quote (TCP, send)<br/>timeout 2 s\"| M[\"menu<br/>@MessagePattern\"]\n  O --> DB[(\"orders.db<br/>orders + outbox\")]\n  DB -.->|\"OutboxRelay co 500 ms\"| R1[[\"RabbitMQ<br/>kolejka kitchen\"]]\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/>kolejka orders\"]]\n  R2 --> O","caption":"Usługi pierogarni i przepływ wiadomości"}},{"type":"heading","attrs":{"level":2,"id":"wiadomosc-czy-zdarzenie"},"content":[{"type":"text","text":"Wiadomość czy zdarzenie?"}]},{"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":"Semantyka"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"„policz mi wycenę” – pytanie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"„zamówienie złożone” – fakt"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Odpowiedź"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak, "},{"type":"text","text":"Observable","marks":[{"type":"code"}]},{"type":"text","text":" z wynikiem lub błędem"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Gdy odbiorca leży"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"błąd lub limit czasu u wywołującego"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wiadomość czeka w kolejce (jeśli broker jest trwały)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Sprzężenie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"czasowe – obie usługi muszą działać naraz"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"luźne – odbiorca przetworzy, gdy wstanie"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Przykład"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"menu, ceny, sprawdzenie dostępności"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"kuchnia, powiadomienia, program lojalnościowy"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Zasada praktyczna: zapytań używaj tam, gdzie wywołujący "},{"type":"text","text":"nie może kontynuować","marks":[{"type":"bold"}]},{"type":"text","text":" bez odpowiedzi (nie złożysz zamówienia bez ceny). Wszystko, co może wydarzyć się chwilę później, ogłaszaj zdarzeniem. Łańcuch synchronicznych wywołań A → B → C sumuje opóźnienia i mnoży ryzyko awarii."}]},{"type":"heading","attrs":{"level":2,"id":"transporty-co-naprawde-gwarantuja"},"content":[{"type":"text","text":"Transporty: co naprawdę gwarantują"}]},{"type":"paragraph","content":[{"type":"text","text":"Handlery wyglądają tak samo dla każdego transportu – zmieniają się tylko opcje. Różnią się jednak gwarancje dostarczenia, a to one decydują o wyborze."}]},{"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":"Gwarancja"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kiedy"}]}]}]},{"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":"bezpośrednie połączenie"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"brak trwałości"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zapytania wewnątrz klastra, prosto i szybko"}]}]}]},{"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":"publikuj/subskrybuj"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"co najwyżej raz – offline = stracone"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"powiadomienia „nice to have”, unieważnianie cache"}]}]}]},{"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":"publikuj/subskrybuj, request-reply"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"co najwyżej raz (JetStream: trwałe strumienie)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"niskie opóźnienia, wiele usług"}]}]}]},{"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":"kolejki i wymiany (exchange)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"co najmniej raz z "},{"type":"text","text":"ack","marks":[{"type":"code"}]},{"type":"text","text":" i trwałą kolejką"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zadania i zdarzenia biznesowe, 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":"partycjonowany log"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"co najmniej raz, kolejność w partycji, odtwarzanie historii"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"strumienie zdarzeń, duża skala, wielu konsumentów, analityka"}]}]}]},{"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":"jak TCP, z kontraktem "},{"type":"text","text":".proto","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"zapytania między zespołami i językami"}]}]}]}]},{"type":"codeGroup","attrs":{"title":"Te same handlery, różne transporty"},"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":"O Kafce warto wiedzieć jedno: transport Nest korzysta z biblioteki KafkaJS, której ostatnie wydanie pochodzi z lutego 2023. Działa, ale przy dużym ruchu rozważ "},{"type":"text","text":"@confluentinc/kafka-javascript","marks":[{"type":"code"}]},{"type":"text","text":" – klienta opartego na librdkafka z API zgodnym z KafkaJS – i własny transport albo bezpośrednie użycie klienta w serwisie."}]},{"type":"heading","attrs":{"level":2,"id":"krok-1-projekt-w-nestjs-12-esm"},"content":[{"type":"text","text":"Krok 1. Projekt w NestJS 12 (ESM)"}]},{"type":"paragraph","content":[{"type":"text","text":"NestJS 12 (wydany w sierpniu 2026) publikuje pakiety jako ESM. Aplikacje CommonJS nadal działają dzięki "},{"type":"text","text":"require(esm)","marks":[{"type":"code"}]},{"type":"text","text":" w Node, ale nowy projekt warto od razu ustawić jako ESM: "},{"type":"text","text":"\"type\": \"module\"","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"module: \"nodenext\"","marks":[{"type":"code"}]},{"type":"text","text":" i importy względne z rozszerzeniem "},{"type":"text","text":".js","marks":[{"type":"code"}]},{"type":"text","text":". Nest CLI 12 wymaga TypeScriptu 6, a do uruchamiania aplikacji potrzebny jest Node 20.19+ lub 22.12+ (my używamy 24). W tym projekcie wystarcza zwykłe "},{"type":"text","text":"tsc","marks":[{"type":"code"}]},{"type":"text","text":" – trzy usługi kompilują się do "},{"type":"text","text":"dist/","marks":[{"type":"code"}]},{"type":"text","text":" i startują osobnymi skryptami."}]},{"type":"codeGroup","attrs":{"title":"Konfiguracja, broker i wspólny kontrakt"},"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":" to jedyne miejsce, które znają wszystkie usługi: nazwy wzorców, kształt wiadomości i opcje kolejek. Kontrakt wersjonuj ostrożnie: dodawanie pól jest bezpieczne, zmiana znaczenia albo usunięcie pola wymaga nowej wersji zdarzenia ("},{"type":"text","text":"order.placed.v2","marks":[{"type":"code"}]},{"type":"text","text":") i okresu przejściowego."}]},{"type":"heading","attrs":{"level":2,"id":"krok-2-menu-zapytanie-z-odpowiedzia-przez-tcp"},"content":[{"type":"text","text":"Krok 2. Menu: zapytanie z odpowiedzią przez TCP"}]},{"type":"codeGroup","attrs":{"title":"Kontroler i start mikroserwisu menu"},"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":"wiadomosc-czy-zdarzenie","text":"Wiadomość czy zdarzenie?","level":2,"locked":false},{"id":"transporty-co-naprawde-gwarantuja","text":"Transporty: co naprawdę gwarantują","level":2,"locked":false},{"id":"krok-1-projekt-w-nestjs-12-esm","text":"Krok 1. Projekt w NestJS 12 (ESM)","level":2,"locked":false},{"id":"krok-2-menu-zapytanie-z-odpowiedzia-przez-tcp","text":"Krok 2. Menu: zapytanie z odpowiedzią przez TCP","level":2,"locked":false},{"id":"krok-3-orders-aplikacja-hybrydowa","text":"Krok 3. Orders: aplikacja hybrydowa","level":2,"locked":true},{"id":"krok-4-transakcyjny-outbox","text":"Krok 4. Transakcyjny outbox","level":2,"locked":true},{"id":"krok-5-kuchnia-idempotentny-konsument-z-recznym-ack","text":"Krok 5. Kuchnia: idempotentny konsument z ręcznym ack","level":2,"locked":true},{"id":"kiedy-zdarzenia-a-kiedy-zapytania","text":"Kiedy zdarzenia, a kiedy zapytania","level":2,"locked":true},{"id":"typowe-bledy","text":"Typowe błędy","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true},{"id":"co-dalej","text":"Co dalej","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":"Bezpiecznik przed bramką płatności","summary":"Circuit breaker ze stanami zamknięty, otwarty i półotwarty, wstrzykiwanym zegarem, progiem prób testowych i filtrem błędów biznesowych – żeby awaria bramki płatności nie położyła całego sklepu.","servedLang":"pl","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":"Magazyn z CQRS – osobny model zapisu i odczytu","summary":"Komendy magazynowe walidowane na własnym modelu zapisu, zdarzenia na szynie i projekcja budująca model odczytu z raportem niskich stanów. Model odczytu da się odtworzyć z samych zdarzeń.","servedLang":"pl","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":"Autorytet","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":46}]}}