We are going to design an event-driven order management service using Domain-Driven Design (DDD) aggregates, Saga orchestration, and retry compensations.
Key components:
- Aggregates: We'll have at least two aggregates: Order and Inventory (or Product). The Order aggregate will handle order creation, modification, and cancellation. The Inventory aggregate will handle stock updates.
- Events: We'll define events for each state change. For example: OrderCreated, OrderConfirmed, OrderCancelled, InventoryReserved, InventoryReservationFailed, etc.
- Saga: We'll have a saga (or process manager) to coordinate the order confirmation process. This involves reserving inventory, processing payment, and then confirming the order. If any step fails, we need to compensate (e.g., release inventory if payment fails).
- Retry and Compensation: We'll use a retry mechanism for transient failures and compensation for business-level failures (like payment failure).
Let's break down:
Aggregates
Order Aggregate
- Root: Order
- Entities: OrderLine (if needed, but often OrderLine is a value object in the Order aggregate)
- Value Objects: OrderId, CustomerId, Money (for total), Address, etc.
- States: Created, Confirmed, Cancelled
- Commands: CreateOrder, ConfirmOrder, CancelOrder
- Events: OrderCreated, OrderConfirmed, OrderCancelled
Inventory Aggregate (or Product Aggregate)
- Root: Inventory (or Product)
- Value Objects: ProductId, Quantity, etc.
- Commands: ReserveInventory, ReleaseInventory
- Events: InventoryReserved, InventoryReservationFailed, InventoryReleased
Saga: OrderConfirmationSaga
This saga will listen for OrderCreated events and then start the confirmation process:
- When OrderCreated is published, the saga starts and sends ReserveInventory command to the Inventory aggregate.
- If InventoryReserved event is received, then we proceed to process payment (which might be an external service, so we might have a Payment process manager or just a command to a payment service). Alternatively, we can have a separate saga for payment, but for simplicity, let's assume we have a Payment service that we call via command and then wait for PaymentCompleted or PaymentFailed.
- If PaymentCompleted, then we send ConfirmOrder command to the Order aggregate.
- If at any step we get a failure (InventoryReservationFailed or PaymentFailed), we need to cancel the order (or at least release any reserved inventory and then cancel the order).
But note: if we fail after reserving inventory (e.g., payment fails), we must release the inventory. Also, we might need to handle timeouts for the payment.
We'll design the saga to be stateful, keeping track of the orderId and the current step.
Retry and Compensation
- For transient failures (like network issues when calling the inventory service), we can use a retry mechanism at the command level (with exponential backoff, etc.).
- For business failures (like insufficient stock), we get a InventoryReservationFailed event and then we compensate by cancelling the order and maybe notifying the user.
- Also, if the saga is in the middle and the service restarts, we need to be able to recover the saga state. We can use event sourcing for the saga or persist the state in a database.
Implementation Considerations
We'll use an event bus (or message broker) for communication between aggregates and the saga.
Let's define the events and commands:
Events:
- OrderCreated
- OrderConfirmed
- OrderCancelled
- InventoryReserved
- InventoryReservationFailed (with reason)
- InventoryReleased
- PaymentCompleted
- PaymentFailed
Commands:
- CreateOrder
- ConfirmOrder
- CancelOrder
- ReserveInventory
- ReleaseInventory
- ProcessPayment (if we have a separate payment service, else we might handle payment within the saga)
But note: the saga should not call commands directly? Actually, in a typical saga, the saga sends commands to the aggregates (or other services) and then reacts to events.
Alternatively, we can have the saga publish an event that the payment service listens to, but then the payment service would publish PaymentCompleted/Failed. However, for simplicity, let's assume we have a Payment service that we call by sending a command and then it emits events.
Saga Steps:
- OrderCreated -> Saga starts, sends ReserveInventory (with product IDs and quantities) to Inventory aggregate.
- If InventoryReserved, then send ProcessPayment command to Payment service.
- If PaymentCompleted, then send ConfirmOrder to Order aggregate.
- If InventoryReservationFailed, then send CancelOrder to Order aggregate (and maybe also ReleaseInventory? But if reservation failed, we didn't reserve, so no release needed).
- If PaymentFailed, then we need to release the inventory (because we reserved it) and then cancel the order.
But note: the saga must know that we have reserved inventory when payment fails. So the saga should keep state about the reservation.
Alternatively, we can design the compensation in a way that when PaymentFailed, we send ReleaseInventory and then CancelOrder.
But what if ReleaseInventory fails? Then we might need to retry the release. So we might have a compensation saga for that? Or we can have the same saga handle the compensation with retries.
We can model the saga as a state machine:
State: Started
Event: OrderCreated -> Action: ReserveInventory -> Next State: WaitingForInventoryReservation
State: WaitingForInventoryReservation
Event: InventoryReserved -> Action: ProcessPayment -> Next State: WaitingForPayment
Event: InventoryReservationFailed -> Action: CancelOrder -> Next State: Completed (failed)
State: WaitingForPayment
Event: PaymentCompleted -> Action: ConfirmOrder -> Next State: Completed (success)
Event: PaymentFailed -> Action: ReleaseInventory -> Next State: ReleasingInventory
State: ReleasingInventory
Event: InventoryReleased -> Action: CancelOrder -> Next State: Completed (failed)
Event: InventoryReleaseFailed -> Action: RetryReleaseInventory (with retry logic) -> Stay in ReleasingInventory? Or have a sub-saga for release?
But note: the ReleaseInventory command might also fail due to transient issues, so we need retries. We can handle retries in the saga by having a retry count and a delay, or we can have a separate retry mechanism (like a dead letter queue and a retry service).
Alternatively, we can use a compensating transaction that is idempotent and then use a retry policy.
Idempotency
All commands and events should be idempotent. For example, if we send ReleaseInventory multiple times, it should be safe (if already released, then it's a no-op).
Data Flow
- Client sends CreateOrder command to Order aggregate (via command bus).
- Order aggregate validates and emits OrderCreated event.
- Saga listens to OrderCreated and sends ReserveInventory command to Inventory aggregate.
- Inventory aggregate reserves stock and emits InventoryReserved (or fails with InventoryReservationFailed).
- Saga listens to InventoryReserved and sends ProcessPayment command to Payment service.
- Payment service processes and emits PaymentCompleted or PaymentFailed.
- Saga listens to PaymentCompleted and sends ConfirmOrder to Order aggregate -> Order emits OrderConfirmed.
- If PaymentFailed, saga sends ReleaseInventory and then after release, sends CancelOrder.
But note: what if the saga fails after PaymentCompleted and before ConfirmOrder? Then the order is not confirmed but payment is taken. We need to handle that. We might have a timeout for the saga and then compensate? That's a complex scenario.
Alternatively, we can change the order: after payment, we confirm the order, but if confirmation fails, we might need to refund the payment? That's a more complex business rule.
For simplicity, let's assume that ConfirmOrder is a simple state change and should always succeed if we get to that point. But if it fails due to technical issues, we might retry the command.
Technical Failures and Retries
We can have a retry mechanism at the command bus level or in the saga. For example, when sending a command, if we don't get an event in a certain time, we retry. But that might be complex.
Alternatively, we can use a timeout in the saga for each step and then retry the command if it times out? But note: the command might have been processed but the event was lost. We need idempotent commands and events to handle duplicates.
A common pattern is to use a message broker with at-least-once delivery and make the handlers idempotent.
Implementation Sketch
We'll have:
- Command Bus: For sending commands to aggregates.
- Event Bus: For publishing events and subscribing to them.
- Aggregates: Each aggregate listens to commands and emits events.
- Saga: Listens to events and sends commands.
We'll use a database to persist the saga state (or event store for the saga if we use event sourcing for the saga).
Let's sketch the saga in pseudo-code:
class OrderConfirmationSaga:
def __init__(self):
self.state = None
self.order_id = None
self.retry_count = 0
self.max_retries = 3
def on_order_created(self, event):
self.order_id = event.order_id
self.state = "WAITING_FOR_INVENTORY"
send_command(ReserveInventoryCommand(order_id=event.order_id, items=event.items))
def on_inventory_reserved(self, event):
if self.state != "WAITING_FOR_INVENTORY":
return # ignore if out of order
self.state = "WAITING_FOR_PAYMENT"
send_command(ProcessPaymentCommand(order_id=self.order_id, amount=event.total_amount))
def on_inventory_reservation_failed(self, event):
if self.state != "WAITING_FOR_INVENTORY":
return
self.state = "CANCELLING"
send_command(CancelOrderCommand(order_id=self.order_id, reason=event.reason))
def on_payment_completed(self, event):
if self.state != "WAITING_FOR_PAYMENT":
return
self.state = "CONFIRMING"
send_command(ConfirmOrderCommand(order_id=self.order_id))
def on_payment_failed(self, event):
if self.state != "WAITING_FOR_PAYMENT":
return
self.state = "RELEASING_INVENTORY"
send_command(ReleaseInventoryCommand(order_id=self.order_id, items=event.items)) # we need to know the items? Maybe from the inventory reserved event? Or we can store the items in the saga.
def on_inventory_released(self, event):
if self.state != "RELEASING_INVENTORY":
return
self.state = "CANCELLING"
send_command(CancelOrderCommand(order_id=self.order_id, reason="Payment failed"))
def on_inventory_release_failed(self, event):
if self.state != "RELEASING_INVENTORY":
return
self.retry_count += 1
if self.retry_count < self.max_retries:
# retry after delay
schedule_retry(ReleaseInventoryCommand(order_id=self.order_id, items=...), delay=exponential_backoff(self.retry_count))
else:
# give up? Maybe we need to alert and manually intervene.
# But we still want to cancel the order? Or we leave the inventory reserved?
# This is a tricky situation: we couldn't release the inventory and payment failed, so we are in an inconsistent state.
# We might need to mark the order as "payment_failed_but_inventory_not_released" and alert.
self.state = "FAILED"
# ... maybe send an alert
Note: The saga must store its state (order_id, state, retry_count, and maybe the items for release) in a persistent store so that if the saga service restarts, it can recover.
Handling Duplicate Events
Because of at-least-once delivery, we might receive the same event multiple times. We need to make the saga idempotent. We can do that by:
- Storing the last processed event for each order and ignoring duplicates (using event id or sequence).
- Or making the state transitions idempotent: if we are in state WAITING_FOR_PAYMENT and we get another InventoryReserved, we ignore.
But note: what if we get InventoryReserved and then another InventoryReserved? We should ignore the second because we already processed the first.
We can store the event id that we last processed for each order and skip if we see the same event id again.
Alternatively, we can use the event's unique ID and have a table of processed event IDs.
Timeouts
We also need to handle timeouts. For example, if we don't get an event within a certain time, we might consider it failed and compensate.
We can have a timer for each step. For example, when we send ReserveInventory, we set a timer for 30 seconds. If we don't get InventoryReserved or InventoryReservationFailed, then we time out and consider it a failure and cancel the order.
But note: the command might be delayed, so we need to be cautious.
We can have a separate timeout process that checks for sagas that are stuck and then triggers a compensation.
Conclusion
This is a high-level design. The actual implementation will depend on the technology stack (languages, frameworks, message broker, database).
We have:
- Two aggregates: Order and Inventory.
- A saga (OrderConfirmationSaga) that coordinates the order confirmation.
- Events and commands with idempotency.
- Retry for transient failures (in the saga for sending commands, and also in the aggregates for their own operations?).
- Compensation for business failures (payment failure -> release inventory -> cancel order).
We also need to consider:
- How to store the saga state? We can use a relational database table with columns: saga_id, order_id, state, retry_count, last_event_id, etc.
- How to ensure exactly-once processing? We can't, so we design for at-least-once and idempotency.
This design is a starting point and would need to be adjusted based on specific business requirements and technical constraints.
I'll architect an event-driven order management service using Domain-Driven Design (DDD) with Saga orchestration, compensations, and retry patterns. Here's a comprehensive design:
1. Domain Model & Aggregates
Aggregate 1: Order Aggregate
// Root Entity
class Order {
orderId: OrderId;
customerId: CustomerId;
status: OrderStatus; // PENDING, CONFIRMED, FULFILLED, CANCELLED
orderLines: OrderLine[];
totalAmount: Money;
version: number; // For optimistic concurrency
// Business Methods
confirm(): void {
if (this.status !== OrderStatus.PENDING)
throw new DomainError("Can only confirm pending orders");
this.status = OrderStatus.CONFIRMED;
this.registerEvent(new OrderConfirmed(this.orderId, this.customerId));
}
cancel(reason: string): void {
if (this.status === OrderStatus.FULFILLED)
throw new DomainError("Cannot cancel fulfilled order");
this.status = OrderStatus.CANCELLED;
this.registerEvent(new OrderCancelled(this.orderId, reason));
}
addItem(productId: ProductId, quantity: number, price: Money): void {
// Validation logic
this.orderLines.push(new OrderLine(productId, quantity, price));
this.recalculateTotal();
}
}
// Value Objects
class OrderId extends ValueObject<string> {}
class Money extends ValueObject<number> {}
class OrderLine {
productId: ProductId;
quantity: number;
unitPrice: Money;
lineTotal: Money;
}
Aggregate 2: Inventory Aggregate
class Inventory {
productId: ProductId;
availableQuantity: number;
reservedQuantity: number;
reserve(quantity: number): void {
if (this.availableQuantity < quantity)
throw new InsufficientStockError(productId);
this.availableQuantity -= quantity;
this.reservedQuantity += quantity;
this.registerEvent(new StockReserved(this.productId, quantity));
}
release(quantity: number): void {
this.availableQuantity += quantity;
this.reservedQuantity -= quantity;
this.registerEvent(new StockReleased(this.productId, quantity));
}
deduct(quantity: number): void {
this.reservedQuantity -= quantity;
this.registerEvent(new StockDeducted(this.productId, quantity));
}
}
Aggregate 3: Payment Aggregate
class Payment {
paymentId: PaymentId;
orderId: OrderId;
amount: Money;
status: PaymentStatus; // PENDING, COMPLETED, FAILED, REFUNDED
retryCount: number = 0;
process(amount: Money): void {
// Payment gateway integration
if (this.attemptPayment(amount)) {
this.status = PaymentStatus.COMPLETED;
this.registerEvent(new PaymentCompleted(this.paymentId, this.orderId));
} else {
this.retryCount++;
this.registerEvent(new PaymentFailed(this.paymentId, this.orderId, this.retryCount));
}
}
refund(): void {
this.status = PaymentStatus.REFUNDED;
this.registerEvent(new PaymentRefunded(this.paymentId, this.orderId));
}
}
2. Domain Events
// Order Events
interface OrderCreated {
orderId: string;
customerId: string;
items: OrderItemDto[];
total: number;
occurredOn: Date;
}
interface OrderConfirmed {
orderId: string;
customerId: string;
occurredOn: Date;
}
interface OrderCancelled {
orderId: string;
reason: string;
occurredOn: Date;
}
// Inventory Events
interface StockReserved {
productId: string;
orderId: string;
quantity: number;
occurredOn: Date;
}
interface StockReservationFailed {
productId: string;
orderId: string;
reason: string;
occurredOn: Date;
}
interface StockReleased {
productId: string;
orderId: string;
quantity: number;
occurredOn: Date;
}
// Payment Events
interface PaymentCompleted {
paymentId: string;
orderId: string;
amount: number;
occurredOn: Date;
}
interface PaymentFailed {
paymentId: string;
orderId: string;
retryCount: number;
occurredOn: Date;
}
3. Saga Orchestration (Process Manager)
class OrderProcessingSaga {
private readonly sagaId: string;
private orderId: string;
private currentState: SagaState;
private compensationStack: CompensationAction[] = [];
private retryPolicy: RetryPolicy;
constructor(private eventBus: EventBus,
private commandBus: CommandBus,
private sagaRepository: SagaRepository) {
this.retryPolicy = new ExponentialBackoffRetry(
maxRetries: 3,
baseDelay: 1000,
maxDelay: 30000
);
}
// Event Handlers (started by OrderCreated)
async onOrderCreated(event: OrderCreated): Promise<void> {
this.sagaId = generateSagaId();
this.orderId = event.orderId;
this.currentState = SagaState.RESERVING_STOCK;
// Store saga state
await this.sagaRepository.save(this.snapshot());
try {
// Step 1: Reserve inventory
await this.reserveInventory(event.items);
} catch (error) {
await this.handleFailure(error);
}
}
async onStockReserved(event: StockReserved): Promise<void> {
if (this.currentState !== SagaState.RESERVING_STOCK) return;
this.currentState = SagaState.PROCESSING_PAYMENT;
await this.sagaRepository.save(this.snapshot());
try {
// Step 2: Process payment
await this.processPayment(event.orderId, event.quantity);
} catch (error) {
await this.handleFailure(error);
}
}
async onPaymentCompleted(event: PaymentCompleted): Promise<void> {
if (this.currentState !== SagaState.PROCESSING_PAYMENT) return;
this.currentState = SagaState.CONFIRMING_ORDER;
await this.sagaRepository.save(this.snapshot());
try {
// Step 3: Confirm order
await this.confirmOrder(event.orderId);
this.currentState = SagaState.COMPLETED;
await this.sagaRepository.save(this.snapshot());
} catch (error) {
await this.handleFailure(error);
}
}
// Compensation Handlers
async onStockReservationFailed(event: StockReservationFailed): Promise<void> {
await this.compensate("Stock reservation failed: " + event.reason);
}
async onPaymentFailed(event: PaymentFailed): Promise<void> {
if (event.retryCount >= this.retryPolicy.maxRetries) {
await this.compensate("Payment failed after retries");
} else {
// Retry payment with backoff
await this.retryPayment(event.orderId, event.retryCount);
}
}
private async reserveInventory(items: OrderItemDto[]): Promise<void> {
const commands = items.map(item =>
new ReserveStockCommand(this.orderId, item.productId, item.quantity)
);
// Push compensation action
this.compensationStack.push({
type: CompensationType.RELEASE_STOCK,
orderId: this.orderId,
items: items
});
await this.commandBus.sendAll(commands);
}
private async processPayment(orderId: string, quantity: number): Promise<void> {
const total = this.calculateTotal(quantity);
const command = new ProcessPaymentCommand(
orderId,
total,
this.retryPolicy.currentRetry
);
this.compensationStack.push({
type: CompensationType.REFUND_PAYMENT,
orderId: this.orderId,
amount: total
});
await this.commandBus.send(command);
}
private async confirmOrder(orderId: string): Promise<void> {
await this.commandBus.send(new ConfirmOrderCommand(orderId));
}
private async compensate(reason: string): Promise<void> {
this.currentState = SagaState.COMPENSATING;
// Execute compensations in reverse order
while (this.compensationStack.length > 0) {
const action = this.compensationStack.pop()!;
try {
await this.executeCompensation(action);
} catch (error) {
// Log compensation failure but continue with other compensations
console.error(`Compensation failed for ${action.type}:`, error);
}
}
// Final: Cancel the order
await this.commandBus.send(
new CancelOrderCommand(this.orderId, `Saga failed: ${reason}`)
);
this.currentState = SagaState.COMPENSATED;
await this.sagaRepository.save(this.snapshot());
}
private async executeCompensation(action: CompensationAction): Promise<void> {
switch (action.type) {
case CompensationType.RELEASE_STOCK:
await this.commandBus.send(
new ReleaseStockCommand(action.orderId, action.items)
);
break;
case CompensationType.REFUND_PAYMENT:
await this.commandBus.send(
new RefundPaymentCommand(action.orderId, action.amount)
);
break;
}
}
private snapshot(): SagaSnapshot {
return {
sagaId: this.sagaId,
orderId: this.orderId,
state: this.currentState,
compensationStack: this.compensationStack,
retryCount: this.retryPolicy.currentRetry,
lastUpdated: new Date()
};
}
}
enum SagaState {
RESERVING_STOCK,
PROCESSING_PAYMENT,
CONFIRMING_ORDER,
COMPLETED,
COMPENSATING,
COMPENSATED,
FAILED
}
interface CompensationAction {
type: CompensationType;
orderId: string;
items?: OrderItemDto[];
amount?: Money;
}
enum CompensationType {
RELEASE_STOCK,
REFUND_PAYMENT
}
4. Retry Mechanisms
Retry Policy Interface
interface RetryPolicy {
shouldRetry(attempt: number, error: Error): boolean;
getDelay(attempt: number): number;
maxRetries: number;
}
class ExponentialBackoffRetry implements RetryPolicy {
constructor(
public maxRetries: number = 3,
public baseDelay: number = 1000,
public maxDelay: number = 30000,
public multiplier: number = 2
) {}
shouldRetry(attempt: number, error: Error): boolean {
return attempt < this.maxRetries &&
this.isRetryableError(error);
}
getDelay(attempt: number): number {
const delay = this.baseDelay * Math.pow(this.multiplier, attempt);
return Math.min(delay, this.maxDelay);
}
private isRetryableError(error: Error): boolean {
// Network errors, timeouts, etc.
return error instanceof NetworkError ||
error instanceof TimeoutError;
}
}
Command Retry Decorator
class RetryableCommandHandler {
constructor(
private commandHandler: CommandHandler,
private retryPolicy: RetryPolicy
) {}
async execute(command: Command): Promise<void> {
let attempt = 0;
let lastError: Error | null = null;
while (attempt <= this.retryPolicy.maxRetries) {
try {
await this.commandHandler.handle(command);
return;
} catch (error) {
lastError = error;
if (!this.retryPolicy.shouldRetry(attempt, error)) {
throw error;
}
const delay = this.retryPolicy.getDelay(attempt);
await this.delay(delay);
attempt++;
}
}
throw lastError;
}
private delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
5. Infrastructure Components
Event Bus (Kafka-based)
class KafkaEventBus implements EventBus {
private producer: KafkaProducer;
private consumerGroups: Map<string, ConsumerGroup> = new Map();
async publish(event: DomainEvent): Promise<void> {
const topic = this.getTopicForEvent(event);
const message = {
eventId: event.eventId,
aggregateId: event.aggregateId,
type: event.type,
payload: event.payload,
metadata: {
occurredOn: event.occurredOn,
version: event.version
}
};
await this.producer.send({
topic,
messages: [{ value: JSON.stringify(message) }]
});
}
subscribe<T extends DomainEvent>(
eventType: string,
handler: (event: T) => Promise<void>,
consumerGroup: string
): void {
// Ensure idempotent processing with exactly-once semantics where possible
// Use event ID for deduplication
}
}
Command Bus
class CommandBus {
private handlers: Map<string, CommandHandler> = new Map();
private middleware: Middleware[] = [];
async send<T extends Command>(command: T): Promise<void> {
const handler = this.handlers.get(command.constructor.name);
if (!handler) throw new HandlerNotFoundException(command);
// Apply middleware (logging, metrics, retry, etc.)
const pipeline = this.middleware.reduceRight(
(next, mw) => () => mw.execute(command, next),
() => handler.handle(command)
);
await pipeline();
}
registerMiddleware(middleware: Middleware): void {
this.middleware.push(middleware);
}
}
Saga Repository
class SqlSagaRepository implements SagaRepository {
constructor(private db: Database) {}
async save(saga: SagaSnapshot): Promise<void> {
await this.db.sagas.upsert({
sagaId: saga.sagaId,
orderId: saga.orderId,
state: saga.state,
compensationStack: JSON.stringify(saga.compensationStack),
retryCount: saga.retryCount,
lastUpdated: saga.lastUpdated
});
}
async findById(sagaId: string): Promise<SagaSnapshot | null> {
const result = await this.db.sagas.find({ sagaId });
if (!result) return null;
return {
...result,
compensationStack: JSON.parse(result.compensationStack)
};
}
async findByOrderId(orderId: string): Promise<SagaSnapshot | null> {
const results = await this.db.sagas.find({ orderId });
return results[0] || null;
}
}
6. Resilience Patterns
Circuit Breaker
class CircuitBreaker {
private failures = 0;
private state: CircuitState = CircuitState.CLOSED;
private lastFailureTime: number = 0;
async execute<T>(operation: () => Promise<T>): Promise<T> {
if (this.state === CircuitState.OPEN) {
if (Date.now() - this.lastFailureTime > this.resetTimeout) {
this.state = CircuitState.HALF_OPEN;
} else {
throw new CircuitBreakerOpenError();
}
}
try {
const result = await operation();
this.onSuccess();
return result;
} catch (error) {
this.onFailure();
throw error;
}
}
private onSuccess(): void {
this.failures = 0;
this.state = CircuitState.CLOSED;
}
private onFailure(): void {
this.failures++;
this.lastFailureTime = Date.now();
if (this.failures >= this.failureThreshold) {
this.state = CircuitState.OPEN;
}
}
}
Bulkhead Pattern
class Bulkhead {
private semaphore: Semaphore;
constructor(private maxConcurrent: number) {
this.semaphore = new Semaphore(maxConcurrent);
}
async execute<T>(operation: () => Promise<T>): Promise<T> {
await this.semaphore.acquire();
try {
return await operation();
} finally {
this.semaphore.release();
}
}
}
7. Monitoring & Observability
class SagaMetrics {
private counter: Counter;
private gauge: Gauge;
private histogram: Histogram;
constructor(private registry: MetricRegistry) {
this.counter = registry.createCounter('saga_executions_total');
this.gauge = registry.createGauge('active_sagas', () => this.getActiveSagaCount());
this.histogram = registry.createHistogram('saga_duration_ms');
}
recordSagaStart(sagaId: string, sagaType: string): void {
this.counter.increment({ sagaType, outcome: 'started' });
this.gauge.set(this.getActiveSagaCount());
}
recordSagaComplete(sagaId: string, sagaType: string, duration: number, outcome: string): void {
this.histogram.record(duration, { sagaType, outcome });
this.counter.increment({ sagaType, outcome });
}
recordCompensation(sagaId: string, compensationType: string): void {
this.counter.increment({ compensationType, outcome: 'executed' });
}
}
8. Deployment & Configuration
# docker-compose.yml services
services:
order-service:
image: order-management:latest
environment:
- KAFKA_BROKERS=kafka:9092
- SAGA_STORAGE=postgresql
- RETRY_MAX_ATTEMPTS=3
- CIRCUIT_BREAKER_FAILURE_THRESHOLD=5
- BULKHEAD_MAX_CONCURRENT=10
depends_on:
- kafka
- postgres
volumes:
- ./config:/app/config
inventory-service:
# Similar configuration
payment-service:
# Similar configuration
saga-coordinator:
image: saga-coordinator:latest
environment:
- SAGA_REPLAY_WINDOW_HOURS=24
- DEAD_LETTER_QUEUE_ENABLED=true
depends_on:
- kafka
- postgres
kafka:
image: confluentinc/cp-kafka:latest
environment:
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
postgres:
image: postgres:15
environment:
POSTGRES_DB: order_management
POSTGRES_PASSWORD: password
9. Example Flow: Order Creation Saga
1. Client → CreateOrderCommand → Order Aggregate
2. Order → OrderCreated Event → Kafka
3. Saga → StockReservationCommand → Inventory Aggregate
4. Inventory → StockReserved Event → Kafka
5. Saga → ProcessPaymentCommand → Payment Aggregate
6. Payment → PaymentCompleted Event → Kafka
7. Saga → ConfirmOrderCommand → Order Aggregate
8. Order → OrderConfirmed Event → Kafka → Notify User
10. Failure Scenarios & Compensation
Scenario 1: Payment Fails
1. PaymentFailed Event (retry count: 3) → Saga
2. Saga → RefundPaymentCommand (if already charged) → Payment
3. Saga → ReleaseStockCommand → Inventory
4. Saga → CancelOrderCommand → Order
5. Order → OrderCancelled Event → Notify User
Scenario 2: Inventory Reservation Fails
1. StockReservationFailed Event → Saga
2. Saga → CancelOrderCommand → Order
3. Order → OrderCancelled Event → Notify User
Scenario 3: Partial Failure (Payment succeeds, Order confirmation fails)
1. PaymentCompleted → Saga
2. Saga → ConfirmOrder → Order (fails)
3. Saga retries ConfirmOrderCommand (with retry policy)
4. If all retries fail → RefundPayment + CancelOrder
Key Design Principles Applied:
- DDD Aggregates: Each aggregate maintains its own invariants and emits events
- Event-Driven: Loose coupling via asynchronous events
- Saga Orchestration: Centralized process manager with explicit state
- Compensating Transactions: Each step has explicit compensation
- Idempotency: All commands/events designed for safe retries
- Resilience: Circuit breakers, bulkheads, retries, timeouts
- Observability: Metrics, logging, distributed tracing (OpenTelemetry)
- Event Sourcing Ready: Saga state stored as events/snapshots
Technology Stack Recommendations:
- Languages: TypeScript/Node.js or Java/Kotlin
- Message Broker: Apache Kafka (with exactly-once semantics)
- Database: PostgreSQL for saga state, separate DB per aggregate
- Monitoring: Prometheus + Grafana + Jaeger
- Containerization: Docker + Kubernetes
- APIs: REST for commands, GraphQL/WebSocket for queries
- Event Store: (Optional) Use Kafka as event store or dedicated EventStoreDB
This architecture provides a robust, scalable, and maintainable order management system that handles distributed transactions through sagas, ensures data consistency through compensations, and provides resilience through various fault-tolerance patterns.