Proposing orchestrated saga microservice architecture
Outlined a global e-commerce microservice setup with Order, Inventory, and Payment services coordinated via a saga orchestrator managing distributed transactions. The orchestrator handles state transitions and compensating rollbacks (like releasing inventory on payment failure), using events over Kafka and incorporating idempotency keys, timeouts, and outbox pattern for consistency. Included ephemeral inventory holds with TTL, atomic reservation handling, domain event streaming, and multi-region considerations with saga logs. Provided pseudocode sketches for orchestrator flow, service endpoints, DB schemas, and message formats to illustrate implementation.
Below is a practical design for using the Saga pattern to coordinate distributed transactions across Order, Inventory, and Payment services in a global e-commerce setup. The focus is on how to handle the happy path and the compensations/rollbacks when Payment fails after Inventory has already been reserved.
1. High-Level Microservice Architecture
Each service owns its database. Use Outbox Pattern per service to publish events atomically with local DB writes.
2. Saga Flow (Orchestrated Variant)
Happy Path:
Order Service receives CreateOrder request → persist order with status PENDING, publish OrderCreated.
Saga Orchestrator sees OrderCreated → issues ReserveInventory command to Inventory.
Inventory Service reserves items (try phase); on success publish InventoryReserved (or on failure InventoryReservationFailed).
Saga Orchestrator upon InventoryReserved → issues AuthorizePayment to Payment.
Payment Service authorizes/charges; on success publish PaymentAuthorized (or on failure PaymentFailed).
Saga Orchestrator upon PaymentAuthorized → updates Order status to COMPLETED (or CONFIRMED). Optionally, triggers capture/fulfillment.
Failure/Compensation (Payment fails after Inventory reserved):
On PaymentFailed:
Saga triggers ReleaseInventory command.
Inventory releases hold and publishes InventoryReleased.
Saga updates Order status to CANCELED (with reason PAYMENT_FAILED).
If Payment was partially captured, issue RefundPayment/Void as needed (depends on Payment semantics).
Other failure variants:
If InventoryReservationFailed, update Order to CANCELED with reason OUT_OF_STOCK.
If Payment times out → treat as failure → release inventory → cancel order.
3. Command/Event Contracts (Example)
Topics/Queues (Commands):
order-service.commands (from orchestrator to Order if needed)
inventory.commands (ReserveInventory, ReleaseInventory)
payment.commands (AuthorizePayment, CapturePayment, RefundPayment/VoidPayment)
Topics (Events):
order.events: OrderCreated, OrderCompleted, OrderCanceled
inventory.events: InventoryReserved, InventoryReservationFailed, InventoryReleased
payment.events: PaymentAuthorized, PaymentFailed, PaymentRefunded (optional)
Message schema (simplified JSON):
json Copy code
// ReserveInventory Command
{
"type": "ReserveInventory",
"orderId": "123",
"items": [
{"sku": "ABC", "qty": 2},
{"sku": "XYZ", "qty": 1}
],
"correlationId": "order-123",
"idempotencyKey": "inv-123"
}
// InventoryReserved Event
{
"type": "InventoryReserved",
"orderId": "123",
"reservedAt": "2024-01-01T00:00:00Z",
"correlationId": "order-123"
}
// AuthorizePayment Command
{
"type": "AuthorizePayment",
"orderId": "123",
"amount": 120.50,
"currency": "USD",
"paymentMethodId": "pm_456",
"correlationId": "order-123",
"idempotencyKey": "pay-123"
}
// PaymentFailed Event
{
"type": "PaymentFailed",
"orderId": "123",
"reason": "card_declined",
"correlationId": "order-123"
}
4. Data Model & Statuses
Order Statuses (example):
PENDING (created, no inventory reserved)
INVENTORY_RESERVED
PAYMENT_AUTHORIZED
COMPLETED
CANCELED (with reason: OUT_OF_STOCK, PAYMENT_FAILED, TIMEOUT, etc.)
Inventory Reservation Model:
reservationId, orderId, items, ttl, status: RESERVED, RELEASED, EXPIRED.
Keep a TTL on reservations to auto-release if saga hangs.
Payment Transaction Model:
paymentId, orderId, status: PENDING, AUTHORIZED, FAILED, CAPTURED, REFUNDED.
Support idempotency keys.
5. Orchestrator Logic (Pseudocode)
python Copy code
def handle_event(event):
if event.type == "OrderCreated":
send_command("ReserveInventory", orderId=event.orderId, items=event.items)
elif event.type == "InventoryReserved":
send_command("AuthorizePayment", orderId=event.orderId, amount=event.amount, currency=event.currency)
elif event.type == "InventoryReservationFailed":
update_order_status(event.orderId, "CANCELED", reason="OUT_OF_STOCK")
# Done.
elif event.type == "PaymentAuthorized":
update_order_status(event.orderId, "COMPLETED")
# Optionally send "CapturePayment" if using two-step flow.
elif event.type == "PaymentFailed":
# Compensation: release inventory
send_command("ReleaseInventory", orderId=event.orderId)
update_order_status(event.orderId, "CANCELED", reason="PAYMENT_FAILED")
elif event.type == "InventoryReleased":
# Confirmation of compensation, might log/emit metrics
pass
Timeout Handling:
If no InventoryReserved within X seconds after OrderCreated → cancel order.
If no PaymentAuthorized/Failed within Y seconds after InventoryReserved → treat as failure; issue ReleaseInventory and cancel.
6. Compensation / Rollback Scenarios
Payment fails after inventory reserved : PaymentFailed triggers ReleaseInventory, then Order → CANCELED.
Payment succeeds, but later needs reversal (e.g., chargeback) :
If goods not shipped: issue RefundPayment, ReleaseInventory if not shipped; set Order to CANCELED.
If shipped: follow returns/refunds business rules, not part of initial saga.
Inventory partial reservation :
Decide business policy: all-or-nothing reservation; otherwise you need a more complex partial flow. For simplicity, reserve all items or fail.
7. Idempotency & Reliability Patterns
Idempotency Keys on commands to Payment and Inventory to prevent duplicate charges/reservations on retries.
Outbox Pattern : Ensure events are published atomically with DB writes.
Exactly-once vs. at-least-once : Assume at-least-once delivery; design handlers to be idempotent.
Ordering : Partition events by orderId/correlationId to preserve saga step order.
Retries with Backoff : For transient errors; do not retry on hard failures (e.g., card declined).
DLQ : For poison messages.
8. Global Concerns (Multi-Region)
Regionalization : Deploy Order, Inventory, Payment per region; keep user traffic regional to reduce latency.
Data Locality : Inventory per warehouse/region; Payment routed to nearest/acquirer region.
Sagas per Region : Run regional sagas; escalate cross-region only when needed (e.g., global inventory pools).
Clock/TTL : Use service timeouts, not wall-clock synchronization.
9. Example REST/Async Interfaces
Inventory Service:
POST /reservations with orderId, items, ttl (returns reservationId)
POST /reservations/{reservationId}/release
Emits events on inventory.events.
Payment Service:
POST /payments/authorize with orderId, amount, currency, paymentMethodId, idempotencyKey
Optionally POST /payments/{id}/capture, POST /payments/{id}/refund
Emits payment.events.
Order Service:
POST /orders → returns orderId (triggers OrderCreated event)
GET /orders/{orderId} to query status.
10. Testing the Saga
Unit : Simulate each service’s happy/failure paths with idempotency keys.
Integration : Run end-to-end with a real broker; assert final order states on both success/failure.
Chaos/Timeouts : Inject timeouts in Payment to ensure inventory is released.
Load/Scale : Verify partitions per orderId keep ordering; monitor lag.
11. Minimal Happy-Path + Failure Sequence
User creates order → OrderCreated.
Orchestrator → ReserveInventory.
Inventory → InventoryReserved.
Orchestrator → AuthorizePayment.
Payment → fails (PaymentFailed).
Orchestrator → ReleaseInventory, updates Order to CANCELED.
Inventory → InventoryReleased. Saga ends.
This implements the required rollback logic when Payment fails after inventory is reserved.