Software Architecture
Saga Pattern in Distributed Systems: Orchestration vs Choreography for Multi-Service Transactions
When transitioning from monolithic architectures to microservices, traditional ACID two-phase commit (2PC) database transactions across distributed network boundaries become an anti-pattern. Network latency, locking deadlocks, and coordinating node failures degrade availability according to the CAP theorem. The Saga Pattern provides eventual consistency across multiple autonomous database boundaries through an ordered sequence of local transactions, paired with explicit compensating actions in the event of failures.
Architectural Comparison: Choreography vs Orchestration
Selecting between event-driven choreography and centralized workflow orchestration fundamentally dictates system maintainability and failure observability:
| Evaluation Dimension | Choreographed Saga (Event-Driven) | Orchestrated Saga (Coordinator-Driven) |
|---|---|---|
| Communication | Asynchronous message brokers (Kafka, RabbitMQ) | Synchronous or async calls directed by orchestrator |
| Coupling | Loose; services listen to domain events | Tighter coupling to centralized coordinator |
| Visibility & Debugging | Difficult; requires distributed tracing (OpenTelemetry) | Centralized state machine visibility (Temporal, Camunda) |
| Compensating Complexity | High risk of cyclic dependencies as services scale | Explicit, structured compensation flow modeling |
| Ideal Use Case | Simple workflows with 2 to 4 microservice hops | Complex enterprise business flows with 5+ services |
Orchestrated Saga Implementation with Temporal Workflow
Workflow orchestration engines like Temporal provide durable execution, automatic state persistence, and native compensating action rollbacks during failure conditions:
# order_saga_workflow.py
from datetime import timedelta
from temporalio import workflow
from temporalio.exceptions import ActivityError
with workflow.unsafe.imports_passed_through():
from activities import reserve_inventory, charge_credit_card, cancel_inventory_reservation
@workflow.defn
class OrderFulfillmentSaga:
@workflow.run
async def run(self, order_id: str, customer_id: str, amount: float):
compensations = []
try:
# Step 1: Reserve Inventory
await workflow.execute_activity(
reserve_inventory,
order_id,
start_to_close_timeout=timedelta(seconds=10)
)
# Register compensating rollback action
compensations.append(lambda: workflow.execute_activity(
cancel_inventory_reservation,
order_id,
start_to_close_timeout=timedelta(seconds=10)
))
# Step 2: Charge Payment Gateway
await workflow.execute_activity(
charge_credit_card,
args=[customer_id, amount],
start_to_close_timeout=timedelta(seconds=15)
)
return {"status": "ORDER_COMPLETED", "order_id": order_id}
except ActivityError as e:
workflow.logger.error(f"Saga step failed. Executing compensating transactions: {e}")
# Execute rollbacks in reverse order (LIFO)
for compensate in reversed(compensations):
try:
await compensate()
except Exception as rollback_err:
workflow.logger.critical(f"Compensating transaction failed: {rollback_err}")
return {"status": "ORDER_ROLLED_BACK", "reason": str(e)}
- Idempotent Compensations: Compensating transactions (e.g., refunding payments or un-reserving inventory) must be strictly idempotent to handle retry loops safely.
- Pivot Transactions: Identify the point of no return in your business workflow; transactions executed after the pivot transaction cannot be compensated and must run to completion.
- Semantic Failure vs System Failure: Differentiate between business logic rejections (insufficient funds: trigger compensation) and transient network drops (retry with exponential backoff).
