Event-Driven Order Management Architecture
This architecture designs an Order Management Service using Domain-Driven Design (DDD) principles, event-driven architecture (EDA) with CQRS/Event Sourcing (ES), Saga Orchestration for distributed transactions, and retry/compensation patterns for resilience. It models a typical e-commerce flow: Create Order → Authorize Payment → Reserve Inventory → Create Shipment.
Key Assumptions & Tech Stack
- Microservices: Order, Payment, Inventory, Shipping (each owns a Bounded Context).
- Messaging: Apache Kafka (topics partitioned by aggregate ID for ordering).
- Framework: Axon Framework (Java/Spring Boot) for DDD aggregates, ES, CQRS, and Sagas.
- Persistence: Event Store (Axon Server/EventStoreDB) + Read Models (PostgreSQL/MongoDB via Projections).
- Saga Storage: Relational DB (e.g., PostgreSQL) for orchestrator state (idempotent, transactional).
- Resilience: Circuit breakers (Resilience4j), retries (exponential backoff), dead-letter queues (DLQ).
- Deployment: Kubernetes with Kafka Streams for projections.
1. Bounded Contexts & DDD Aggregates
Each service enforces invariants within its aggregate root. Aggregates are loaded/updated via commands, emit domain events on state changes.
| Bounded Context | Aggregate Root | Key State/Invariants | Commands | Emitted Events |
|---|
| Order | Order (ID: orderId) | Status (PENDING→PAID→RESERVED→SHIPPED→DELIVERED/CANCELLED), lines, total | CreateOrder, CancelOrder, ConfirmPayment, ConfirmReservation, ConfirmShipment | OrderCreated, OrderCancelled, PaymentConfirmed, ReservationConfirmed, ShipmentConfirmed |
| Payment | Payment (ID: paymentId) | Status (AUTHORIZED→CAPTURED/FAILED), amount | AuthorizePayment, CapturePayment, RefundPayment | PaymentAuthorized, PaymentFailed, PaymentCaptured, PaymentRefunded |
| Inventory | ProductInventory (ID: productId) | Quantity available/reserved | ReserveInventory, CommitReservation, ReleaseReservation | InventoryReserved, InventoryReservationFailed, ReservationCommitted, ReservationReleased |
| Shipping | Shipment (ID: shipmentId) | Status (CREATED→IN_TRANSIT→DELIVERED) | CreateShipment, CancelShipment | ShipmentCreated, ShipmentCancelled |
Invariants:
- Order: Cannot ship without payment & inventory.
- Payment: Atomic auth (idempotent via paymentId).
- Inventory: Reservations expire after 30min (via saga timeout).
2. Domain Events
Events are immutable, versioned, and schema-evolved (Avro/Protobuf). Published to Kafka topics (e.g., order-events, payment-events).
Core Events:
OrderCreated {orderId, customerId, lines[], total}
PaymentAuthorized {paymentId, orderId, amount}
PaymentFailed {paymentId, orderId, reason}
InventoryReserved {reservationId, productId, quantity, expiry}
InventoryReservationFailed {orderId, productId, reason}
ShipmentCreated {shipmentId, orderId, tracking}
- Compensating:
PaymentRefunded, ReservationReleased, OrderCancelled
Projections: Event handlers update read models (e.g., Order Query Service via Kafka Streams).
3. Saga Orchestration Pattern
A dedicated OrderFulfillmentSaga Orchestrator service coordinates the saga per orderId (stateful, persisted).
Saga Lifecycle (FSM)
Initial: OrderCreated
├── Step 1: Send AuthorizePayment → Wait(PaymentAuthorized | PaymentFailed | Timeout)
│ ├── Success: PaymentAuthorized → Send ReserveInventory → Wait(InventoryReserved | Failed | Timeout)
│ │ ├── Success: InventoryReserved → Send CreateShipment → Wait(ShipmentCreated | Failed | Timeout)
│ │ │ ├── Success: Mark COMPLETE (emit OrderFulfilled)
│ │ │ └── Fail: Compensate (CancelShipment → ReleaseReservation → RefundPayment → CancelOrder)
│ └── Fail: Compensate (CancelOrder)
└── Timeout/Fail: Compensate accordingly
Orchestrator Implementation (Axon Saga)
// Pseudo-code (Axon Framework)
@Saga
public class OrderFulfillmentSaga {
@StartSaga
@SagaEventHandler(associationProperty = "orderId")
public void on(OrderCreated event) {
// Persist saga state: {orderId, status=AUTHORIZING, retries=0}
commandGateway.send(new AuthorizePayment(event.getOrderId(), event.getTotal()));
}
@SagaEventHandler(associationProperty = "orderId")
public void on(PaymentAuthorized event) {
updateState(status=RESERVING);
commandGateway.send(new ReserveInventory(event.getOrderId(), /*lines*/));
}
// Similar for other events...
@SagaEventHandler(associationProperty = "orderId")
public void on(PaymentFailed event) {
compensate(event.getOrderId(), CompensationStep.CANCEL_ORDER);
}
// TimeoutHandler (via Axon Scheduler)
public void handleTimeout(SagaState state) {
if (retries < MAX_RETRIES) {
retryCommand(state.lastCommand); // Exponential backoff
} else {
compensate(state.orderId, CompensationStep.FULL_ROLLBACK);
}
}
}
- Association: Events routed to saga instance via
orderId (Kafka headers).
- State Persistence: JSON in DB; reloaded on restart.
- Idempotency: Events/commands include
SagaInstanceId + version checks.
4. Retry & Compensation Mechanisms
Retries
- Command Retries: Axon Command Gateway with Resilience4j (3 retries, 1s→2s→4s backoff).
- Event Handling: Consumer retries (Kafka
enable.auto.commit=false + manual offsets) → DLQ after 5 fails.
- Saga Timeouts: Scheduler (Axon) triggers retry/compensate (e.g., 10min per step).
Compensations (Saga-Driven)
- Reversible Steps: Each forward command has a compensating command (e.g.,
ReserveInventory ↔ ReleaseReservation).
- Partial Rollback: Saga tracks completed steps, skips reverses (e.g., if shipment fails after inventory, release inventory only).
- Final States: Saga ends in COMPLETE/FAILED; queries aggregate events for audit.
- Outbox Pattern: Services use transactional outbox (JPA + Debezium/Kafka Connect) for exactly-once delivery.
Compensation Flow Example (Payment Fails):
Payment Service ─→ PaymentFailed ─→ Saga ─→ CancelOrder ─→ Order Service ─→ OrderCancelled
5. Message Flow Diagram (Text-Based)
Client ─→ POST /orders ─→ Order Service
│
↓ Command: CreateOrder
├─→ Event Store ─→ OrderCreated (Kafka: order-events)
│
↓ Saga Orchestrator (listens all topics)
│
├──→ Command: AuthorizePayment ─→ Payment Service ─→ PaymentAuthorized (payment-events)
│ │
│ └──→ Fail? PaymentFailed ─→ Saga compensate: CancelOrder
│
├──→ Command: ReserveInventory ─→ Inventory ─→ InventoryReserved (inventory-events)
│
└──→ Command: CreateShipment ─→ Shipping ─→ ShipmentCreated (shipping-events)
│
└─→ Saga COMPLETE: OrderFulfilled (query projection updates)
6. Deployment & Observability
- Scaling: Saga per partition (Kafka consumer groups).
- Monitoring: Micrometer + Prometheus (saga states, retry counts, DLQ size).
- Testing: Axon Test fixtures (in-memory event bus), Testcontainers (Kafka/Postgres).
- Edge Cases:
- Duplicates: Aggregate version checks.
- Network Partitions: Saga replays from events.
- Long-Running: Saga expiry (24h → manual intervention).
This design ensures ACID-like consistency in a distributed system, with high availability via retries and auditability via events. For code repos, see Axon examples (e.g., axon-order-management). Extend for billing/tax as needed.