How kaoutharasma/nestjs-kafka-saga-pattern works
Project Type and Purpose
• This is a microservices architecture built with NestJS, implementing the Saga orchestration pattern via Apache Kafka.
• Three services (“order”, “inventory”, “payment”) each run in their own Docker container and communicate asynchronously through Kafka topics.
High-Level Components
a. Inventory Service
• Exposes a controller for “fetch-available-products” and “update-stock” use cases
• Uses an in-memory repository for products
• Subscribes/publishes to Kafka topics for stock checks and updates
b. Order Service (Saga Orchestrator)
• Exposes “create-order” controller and DTOs
• Implements a saga with ordered steps:
1. check-product-availability
2. authorize-payment
3. update-stock
4. confirm-order
• Coordinates the other two services via Kafka topics
c. Payment Service
• Exposes “authorize-payment” controller
• Uses in-memory payment repository
• Subscribes/publishes to payment-related Kafka topics
d. Apache Kafka Broker
• Central event bus for asynchronous messaging
• Topics might include:
– Order.Created
– Inventory.CheckStock / Inventory.StockConfirmed
– Payment.Authorize / Payment.Authorized
– Order.Confirmed / Order.Failed
e. Docker Compose
• Brings up all three NestJS services + Kafka + Zookeeper
Relationships and Data Flow
1. Client → Order Service (HTTP POST /orders)
2. Order Service publishes “Order.Created” to Kafka
3. Inventory Service consumes “Order.Created”, checks stock → publishes “Inventory.StockConfirmed” or “Inventory.OutOfStock”
4. Order Service saga consumes stock result; if confirmed → publishes “Payment.Authorize”
5. Payment Service consumes → processes payment → publishes “Payment.Authorized” or “Payment.Declined”
6. Saga continues: if authorized → publishes “Inventory.UpdateStock” → Inventory Service decrements stock → publishes “Inventory.StockUpdated”
7. Saga finalizes: publishes “Order.Confirmed” or handles compensation on failures
Architectural Patterns and Principles
• Microservices: each service is independently deployed in its own Docker container.
• Saga Orchestration: the Order Service coordinates a distributed transaction across services using events.
• Asynchronous Messaging: all inter-service calls use Kafka topics rather than direct RPC.
• Dependency Inversion: services depend on repository interfaces allowing in-memory (and later persistent) implementations.
• Single Responsibility: each service focuses on one business domain (orders, inventory, payments).