We are going to design a saga orchestrator that supports:
Compensation: when a step fails, we can trigger compensation actions for previously completed steps.
Retries: automatic retries with configurable backoff and max retries.
Dead Letter Queue (DLQ): after max retries, the saga is moved to a DLQ for manual intervention.
Observability: logs, metrics, and possibly tracing.
We'll design a simple but extensible orchestrator.
Steps:
Define the saga as a sequence of steps (each step has an action and a compensation).
The orchestrator will run the steps in order.
If a step fails, we will retry (with backoff) up to a configured max.
If a step fails after max retries, we will trigger compensation for all completed steps (in reverse order) and then move the saga to a DLQ.
We'll use a state machine to track the current step and the state of the saga.
We'll design the following classes:
Saga: the entire saga instance, with a unique ID, current step index, state (RUNNING, COMPLETED, FAILED, COMPENSATED, etc.), and data.
Step: a step in the saga, with an action (function) and a compensation (function). Also, retry configuration for the step.
Orchestrator: manages the execution of the saga. It will:
Start the saga.
Execute the current step (with retries).
On success, move to next step.
On failure (after retries), trigger compensation for all completed steps (in reverse order) and then mark saga as failed and move to DLQ.
We'll also consider:
Observability: we'll log at each step and emit metrics (success, failure, retry, compensation). We can use a callback for metrics.
Let's design the Step:
class Step:
def init(self, action, compensation, max_retries=3, backoff_ms=1000):
self.action = action # function that takes saga data and returns (success, result) or raises exception
self.compensation = compensation # function that takes saga data and returns (success, result) or raises exception
self.max_retries = max_retries
self.backoff_ms = backoff_ms
def execute(self, saga_data):
# We'll try up to max_retries, with backoff.
for attempt in range(self.max_retries):
try:
result = self.action(saga_data)
return result
except Exception as e:
if attempt == self.max_retries - 1:
raise # if last retry, re-raise
time.sleep(self.backoff_ms / 1000.0)
# Should not get here because if we fail the last retry we raise, but for safety:
raise Exception(f"Step failed after {self.max_retries} retries")
def compensate(self, saga_data):
try:
return self.compensation(saga_data)
except Exception as e:
# Log and maybe re-raise? We want to continue with other compensations even if one fails?
# But note: if compensation fails, we might have an inconsistent state. We'll log and continue? Or mark the saga as compensation failed?
# For simplicity, we'll log and continue, but we might want to have a way to record which compensations failed.
# We'll return the exception and let the orchestrator decide.
return e
data: dict (passed between steps, can be updated by steps)
error: optional error message or exception from the last failure
Orchestrator:
def init(self, saga, dlq_handler=None, metrics_callback=None, logger=None):
self.saga = saga
self.dlq_handler = dlq_handler # function that takes a saga and does something (e.g., store in DB, send to queue)
self.metrics_callback = metrics_callback # function(saga, event) to record metrics
self.logger = logger or logging.getLogger(name)
def run(self):
try:
self._run_saga()
except Exception as e:
self.logger.error(f"Saga {self.saga.id} failed with error: {e}")
# We don't need to do anything else because _run_saga will handle compensation and DLQ.
def _run_saga(self):
# If the saga is already in a terminal state? We might want to check.
while self.saga.current_step_index < len(self.saga.steps):
step = self.saga.steps[self.saga.current_step_index]
try:
self.saga.state = "RUNNING"
self.logger.info(f"Saga {self.saga.id}: executing step {self.saga.current_step_index}")
result = step.execute(self.saga.data)
# Update saga data with result? The step might modify the saga data.
# We assume the step modifies the saga.data in place, or we can design that the step returns a new data?
# For simplicity, let's assume the step modifies the saga.data and returns a result that we ignore for now.
# But we might want to store the result of each step? We can store in saga.data with a key for the step.
# Alternatively, we can have a list of step results in the saga.
# Let's change: we'll store the result of each step in saga.results (a list) and also update saga.data if needed?
# We'll leave it to the step to update saga.data. So we don't store the result separately.
code
self.saga.current_step_index += 1
self.record_metric("step_success")
except Exception as e:
self.logger.error(f"Saga {self.saga.id}: step {self.saga.current_step_index} failed: {e}")
self.record_metric("step_failure")
# Step failed after retries, so we need to compensate.
self._compensate()
# Then move to DLQ
self._to_dlq()
return
# If we get here, all steps completed successfully.
self.saga.state = "COMPLETED"
self.logger.info(f"Saga {self.saga.id} completed successfully.")
self.record_metric("saga_completed")
def _compensate(self):
self.saga.state = "COMPENSATING"
self.logger.info(f"Saga {self.saga.id}: starting compensation for {self.saga.current_step_index} completed steps.")
# We have completed steps from 0 to current_step_index-1 (if current_step_index is the one that failed, we haven't completed it).
# So we compensate in reverse order from current_step_index-1 down to 0.
for i in range(self.saga.current_step_index - 1, -1, -1):
step = self.saga.steps[i]
try:
step.compensate(self.saga.data)
self.record_metric("compensation_success")
except Exception as e:
self.logger.error(f"Saga {self.saga.id}: compensation for step {i} failed: {e}")
self.record_metric("compensation_failure")
# We continue with other compensations.
self.saga.state = "COMPENSATED"
self.logger.info(f"Saga {self.saga.id}: compensation completed.")
def _to_dlq(self):
self.saga.state = "IN_DLQ"
if self.dlq_handler:
self.dlq_handler(self.saga)
self.record_metric("saga_to_dlq")
self.logger.info(f"Saga {self.saga.id} moved to DLQ.")
def record_metric(self, event):
if self.metrics_callback:
self.metrics_callback(self.saga.id, event, self.saga.current_step_index, self.saga.state)
However, note: the above design does not allow for dynamic saga definitions (like branching). We assume a linear saga.
But what if we want to have conditional steps? We can extend the Step to have a condition that returns a boolean and then skip steps?
Alternatively, we can design the saga as a directed acyclic graph (DAG). But the requirement is for a saga orchestrator, which is typically linear.
However, the pattern above is for a linear saga. For more complex sagas (with parallel steps, or conditional branching) we would need a more complex state machine.
Since the requirement says "saga orchestrator", and the typical orchestrator pattern is linear (orchestration vs choreography), we'll stick to linear.
But note: the compensation in a linear saga is straightforward: reverse order.
For a more complex saga (with parallel steps) we would need to define a compensation order that respects the dependencies.
Since the problem does not specify, we'll do linear.
However, let's make the Step execution and compensation more robust:
We might want to have a timeout for each step? Not in the basic requirement.
We might want to have a way to pass data from one step to the next? We are using saga.data which is a mutable dictionary.
We might want to have a way to skip a step? We can add a condition function to the step that returns True to run, False to skip.
Let's extend Step:
condition: a function that takes saga.data and returns boolean. If condition returns False, the step is skipped (and we don't run compensation for it?).
But note: if we skip a step, then in compensation we should not compensate it? And if a later step fails, we only compensate the steps that were executed.
So we need to track which steps were executed. We can have a list of executed step indices.
Alternatively, we can change the orchestrator to:
code
for each step index in the saga:
if step.condition and not step.condition(saga.data):
skip and move to next.
else:
try to execute step (with retries). If fails, compensate the executed steps (so far) and break.
So we need to track the executed steps (by index). We can store in saga.executed_steps (list of indices) or we can just use current_step_index when we fail?
But note: if we skip a step, we don't want to compensate it because it wasn't executed.
So let's change:
code
Let's update the Step class to have condition:
code
class Step:
def __init__(self, action, compensation, condition=None, max_retries=3, backoff_ms=1000):
self.action = action
self.compensation = compensation
self.condition = condition # function(saga_data) -> bool, or None for always run
...
def should_run(self, saga_data):
if self.condition is None:
return True
return self.condition(saga_data)
And in the orchestrator loop:
code
if not step.should_run(self.saga.data):
... skip ...
But note: the condition might be expensive? We run it every time we consider the step.
Alternatively, we can precompute the steps to run? But the condition might depend on the outcome of previous steps.
So we run the condition at the time we are about to run the step.
This design is for linear saga with conditional steps.
Now, what about parallel steps? That would require a more complex state machine and compensation order. We'll leave that for future extension.
Let's code accordingly.
We'll also add:
code
- A way to pass data from step to step: we are using saga.data which is a mutable dict. Steps can read and write to it.
- We might want to store the result of each step? We can have saga.data['step_results'] as a dict mapping step index to result. But let's not, unless required.
Observability:
code
We are logging and recording metrics. The metrics_callback will be called with:
saga_id, event, step_index, state
Events: "step_success", "step_failure", "compensation_success", "compensation_failure", "saga_completed", "saga_to_dlq"
DLQ:
code
The dlq_handler is a function that takes the saga object and does something (e.g., store in a database, send to a message queue).
Let's write the code accordingly.
We'll also add:
code
- A way to start a saga: the orchestrator will be given a saga (with steps and initial data).
Note: We are using a while loop and incrementing the current_step_index. We must be cautious about thread safety if we run multiple sagas in parallel? The orchestrator is for one saga.
We'll design the orchestrator to run one saga at a time. If we want to run multiple, we create multiple orchestrators.
Alternatively, we can have a saga manager that manages multiple sagas. But that's beyond the scope.
Let's code:
We'll use Python's logging and time.
We'll define:
code
class Saga:
def __init__(self, id, steps, data=None):
self.id = id
self.steps = steps
self.data = data or {}
self.current_step_index = 0
self.completed_steps = [] # list of indices of completed steps
self.state = "STARTED"
self.error = None
class Step:
... as above ...
class Orchestrator:
... as above ...
Let's adjust the Orchestrator to use the completed_steps and condition.
def _compensate(self):
self.saga.state = "COMPENSATING"
self.logger.info(f"Saga {self.saga.id}: starting compensation for {len(self.saga.completed_steps)} completed steps.")
# Compensate in reverse order of completed_steps.
for i in reversed(self.saga.completed_steps):
step = self.saga.steps[i]
try:
step.compensate(self.saga.data)
self.record_metric("compensation_success")
except Exception as e:
self.logger.error(f"Saga {self.saga.id}: compensation for step {i} failed: {e}")
self.record_metric("compensation_failure")
self.saga.state = "COMPENSATED"
self.logger.info(f"Saga {self.saga.id}: compensation completed.")
But note: what if the compensation of a step modifies the saga.data? That's expected.
Also, note: the compensation might fail, but we continue with the next compensation.
We are done.
However, we might want to have a way to mark the saga as failed even if compensation fails? We are already marking as COMPENSATED, but if some compensations failed, we might want to mark as COMPENSATION_FAILED?
Let's adjust:
code
We'll track if any compensation failed.
In _compensate:
compensation_failed = False
for ...:
try:
...
except:
compensation_failed = True
if compensation_failed:
self.saga.state = "COMPENSATION_FAILED"
else:
self.saga.state = "COMPENSATED"
And then in _to_dlq, we move to DLQ regardless? The requirement says after max retries, we compensate and then move to DLQ.
But if compensation fails, we still move to DLQ? Yes, because we want manual intervention.
So we can mark the saga as COMPENSATION_FAILED and then to DLQ? Or we mark as FAILED and then to DLQ?
Let's have:
After compensation, we set state to COMPENSATED (even if some compensations failed) and then we move to DLQ.
But then we lose the information that compensation failed? We have the error in the logs and metrics.
Alternatively, we can set:
self.saga.state = "COMPENSATED" if no compensation failed, else "COMPENSATION_FAILED"
And then in _to_dlq, we set to "IN_DLQ".
But the DLQ handler might want to know the state? We are passing the saga, so it can see the state.
Let's do:
in _compensate, we set:
self.saga.state = "COMPENSATED" if all compensations succeeded, else "COMPENSATION_FAILED"
Then in _to_dlq, we set to "IN_DLQ", but we don't override the previous state? We can set:
self.saga.state = "IN_DLQ"
But then we lose the information that it was COMPENSATION_FAILED? We can store the previous state in saga.original_state?
Alternatively, we can have:
saga.state = "FAILED" after compensation? But then we have two types of failures: step failure and compensation failure.
Let's keep it simple:
After compensation, we set state to "COMPENSATED" if all succeeded, else "COMPENSATION_FAILED".
Then we call _to_dlq, which sets state to "IN_DLQ", but we can also store the reason? We have the error.
Actually, the saga object already has an error field. We set the error in the step failure. But what about compensation failure? We might want to record that too.
We can set saga.error to the last compensation error? Or we can have a list of compensation errors? Let's not complicate.
We'll just log the compensation errors. The DLQ handler can inspect the saga.completed_steps and the saga.state to know what happened.
Alternatively, we can have:
self.saga.compensation_errors = [] # list of (step_index, error)
Then in _compensate, we append errors to that list.
But the requirement doesn't specify, so let's keep it simple and just log.
We'll stick to the current design.
Let's code accordingly.
One more thing: what if the saga has no steps? Then we should mark as completed immediately.
We'll adjust:
code
In _run_saga:
if not self.saga.steps:
self.saga.state = "COMPLETED"
return
But note: the while loop condition will fail immediately, so we set state to COMPLETED at the end.
So it's okay.
Let's code the classes.
We'll also make the Step.execute and Step.compensate use the same retry logic? Only the action has retries? The compensation might not need retries? Or we might want to retry compensation too?
The requirement says: compensation, retries, DLQs. It doesn't specify if compensation should be retried.
Typically, compensation is a cleanup action and might be idempotent, but if it fails, we might want to retry? Or we might want to give up and mark as compensation failed.
We can add retry configuration for compensation? But the Step class already has max_retries and backoff. We can use the same for both? Or separate?
Let's change the Step to have:
code
action_retry_config and compensation_retry_config? Or just use the same?
Since the requirement says "retries" (for steps) and then compensation, it doesn't specify retries for compensation.
We'll assume that compensation is also subject to the same retry policy? Or we can have:
code
In Step:
action_max_retries, action_backoff_ms
compensation_max_retries, compensation_backoff_ms
But to keep it simple, we'll use the same retry config for both.
Alternatively, we can have:
code
class Step:
def __init__(self, action, compensation, condition=None, max_retries=3, backoff_ms=1000, compensation_retries=None, compensation_backoff_ms=None):
self.action = action
self.compensation = compensation
self.condition = condition
self.max_retries = max_retries
self.backoff_ms = backoff_ms
self.compensation_max_retries = compensation_retries if compensation_retries is not None else max_retries
self.compensation_backoff_ms = compensation_backoff_ms if compensation_backoff_ms is not None else backoff_ms
Then in Step.compensate, we use compensation_max_retries and compensation_backoff_ms.
But note: the compensation might be called multiple times? No, we call each step's compensation once, but with retries.
We'll adjust the Step.compensate to use its own retry config.
However, the requirement doesn't specify, so we'll keep it simple and use the same for both.
We'll change the Step to have:
code
retry_policy: dict with 'max_retries' and 'backoff_ms' for action, and maybe separate for compensation?
But let's not overcomplicate. We'll use the same for both.
If needed, we can extend later.
We'll code accordingly.
Let's code.
Note: We are using time.sleep for backoff. In a real system, we might want to use async or a scheduler. But for simplicity, we'll do sync.
We'll assume the actions and compensations are synchronous.
If we want async, we would need to change the design.
We'll stick to sync.
Code:
We'll write the classes and then an example.
Let's do it.
I'll design a comprehensive saga orchestrator with compensation, retries, DLQ support, and observability. This will be a production-ready pattern in Python.
Core Architecture
python
Production Enhancements
python
Key Features Implemented
Saga Pattern with Compensation
Reversible operations with compensation functions
Reverse-order compensation on failure
Partial compensation continues even if one compensation fails
# Get saga status
status = orchestrator.get_saga_status(saga_id)
# Get DLQ contents
failed_sagas = orchestrator.dlq.get_failed_sagas(limit=50)
# Metrics exposed at /metrics for Prometheus
3. DLQ Processing
python
# Reprocess failed saga from DLQ
for failed_saga in dlq.get_failed_sagas():
if should_retry(failed_saga):
# Fix the underlying issue
fixed_saga = fix_saga_context(failed_saga)
# Re-execute
await orchestrator.execute_saga(fixed_saga)
Deployment Considerations
Scalability: Use message queues (RabbitMQ/Kafka) for distributed execution
Persistence: Store saga state in database with proper indexing
Idempotency: All actions/compensations must be idempotent
This orchestrator provides a solid foundation for distributed transaction management with enterprise-grade features. The design is extensible - you can add:
Parallel step execution
Saga choreography pattern
saga timeouts and TTL
Human-in-the-loop approval steps
Audit logging
Notification integrations (Slack/Email on failures)
In the main loop, we are using a while loop and current_step_index. We are incrementing after success.
But if we skip, we increment without executing.
We can have:
while self.saga.current_step_index < len(self.saga.steps):
step = self.saga.steps[self.saga.current_step_index]
if step.condition and not step.condition(self.saga.data):
self.logger.info(f"Saga {self.saga.id}: step {self.saga.current_step_index} skipped by condition.")
self.saga.current_step_index += 1
continue
... rest of the try/except for execution.
Then in compensation, we compensate from 0 to current_step_index-1? But note: if we skipped some steps, then the executed steps are not necessarily contiguous from 0?
Actually, we are only incrementing the index when we skip or succeed. So if we skip step 1, then we have executed step 0 and then skip 1, then we are at index 2 (pointing to step 2) and we have only executed step 0.
But when we fail at step 2, we want to compensate only step 0? Yes.
So the executed steps are from 0 to (current_step_index-1) but only those that were executed (not skipped). However, note that we are not skipping in the middle of a sequence? We are skipping one step at a time.
But what if we have steps 0,1,2 and we skip step1? Then when we fail at step2, we have executed step0 and step2? Wait, no: we only executed step0 and then skipped step1, then we are about to execute step2. But step2 fails, so we have only executed step0? Because step2 failed, we didn't complete it.
So we want to compensate step0 only.
How do we know which steps were completed? We can record the completed step indices in a list in the saga.
Let's change:
In the saga, we have:
completed_steps: list of indices that were completed (i.e., step executed and succeeded).
Then in the loop:
if step.condition and not step.condition(...):
... skip, do not add to completed_steps.
else:
try:
step.execute(...)
self.saga.completed_steps.append(self.saga.current_step_index)
self.saga.current_step_index += 1
except:
... compensate using self.saga.completed_steps in reverse.
But note: we are using current_step_index to track the next step to run. When we skip, we increment current_step_index but don't add to completed_steps.
Then when we fail, we have a list of completed_steps (which are the ones that succeeded). We compensate in reverse order of completed_steps.
And then we set the saga state to failed and to DLQ.
However, note that if a step fails, we don't add it to completed_steps, so we don't compensate it.
But what about the step that failed? We don't compensate it because it didn't complete.
So compensation order: reverse of completed_steps.
We'll adjust the orchestrator:
Saga class:
completed_steps: list of int
In _run_saga:
while self.saga.current_step_index < len(self.saga.steps):
step = self.saga.steps[self.saga.current_step_index]
if step.condition and not step.condition(self.saga.data):
self.logger.info(f"Saga {self.saga.id}: step {self.saga.current_step_index} skipped by condition.")
self.saga.current_step_index += 1
continue
try:
... execute step ...
self.saga.completed_steps.append(self.saga.current_step_index)
self.saga.current_step_index += 1
except Exception as e:
self._compensate()
self._to_dlq()
return
In _compensate:
for i in reversed(self.saga.completed_steps):
step = self.saga.steps[i]
... compensate step ...
But note: what if the compensation of a step fails? We continue with the next? We already did that.
However, note: the condition might be dynamic and based on the state after previous steps. So we are okay.
"""
Saga Orchestrator with Compensation, Retries, DLQ, and Observability
"""
import asyncio
import logging
import time
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Tuple
from uuid import uuid4
# Observability imports (optional, can be replaced with your observability stack)
# from prometheus_client import Counter, Histogram, Gauge
# import opentelemetry.trace as trace
logger = logging.getLogger(__name__)
class SagaState(Enum):
STARTED = "STARTED"
RUNNING = "RUNNING"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
COMPENSATING = "COMPENSATING"
COMPENSATED = "COMPENSATED"
IN_DLQ = "IN_DLQ"
class StepStatus(Enum):
PENDING = "PENDING"
SUCCEEDED = "SUCCEEDED"
FAILED = "FAILED"
COMPENSATED = "COMPENSATED"
SKIPPED = "SKIPPED"
@dataclass
class StepResult:
step_id: str
status: StepStatus
output: Optional[Any] = None
error: Optional[Exception] = None
attempts: int = 0
started_at: Optional[datetime] = None
completed_at: Optional[datetime] = None
compensation_attempts: int = 0
@dataclass
class Saga:
"""Saga instance with state tracking"""
saga_id: str = field(default_factory=lambda: str(uuid4()))
name: str = "unnamed_saga"
state: SagaState = SagaState.STARTED
steps: List[Dict[str, Any]] = field(default_factory=list)
step_results: Dict[str, StepResult] = field(default_factory=dict)
context: Dict[str, Any] = field(default_factory=dict)
created_at: datetime = field(default_factory=datetime.utcnow)
updated_at: datetime = field(default_factory=datetime.utcnow)
compensation_triggered_at: Optional[datetime] = None
failure_reason: Optional[str] = None
def add_step(
self,
step_id: str,
action: Callable,
compensation: Callable,
retry_policy: Optional[Dict] = None,
condition: Optional[Callable] = None,
timeout_seconds: float = 300.0
):
"""Add a step to the saga"""
self.steps.append({
"step_id": step_id,
"action": action,
"compensation": compensation,
"retry_policy": retry_policy or {
"max_attempts": 3,
"initial_backoff_ms": 1000,
"max_backoff_ms": 30000,
"backoff_multiplier": 2.0
},
"condition": condition,
"timeout_seconds": timeout_seconds
})
class MetricsCollector:
"""Collects metrics for observability"""
def __init__(self):
# In production, integrate with Prometheus/StatsD
self.counters = {
"sagas_started": 0,
"sagas_completed": 0,
"sagas_failed": 0,
"sagas_compensated": 0,
"sagas_moved_to_dlq": 0,
"steps_executed": 0,
"retries": 0,
"compensations": 0
}
def increment(self, metric: str, value: int = 1, labels: Optional[Dict] = None):
self.counters[metric] = self.counters.get(metric, 0) + value
# In production: PROMETHEUS_COUNTER.labels(**labels).inc(value)
def record_duration(self, metric: str, duration_seconds: float, labels: Optional[Dict] = None):
# In production: PROMETHEUS_HISTOGRAM.labels(**labels).observe(duration_seconds)
pass
def set_gauge(self, metric: str, value: float, labels: Optional[Dict] = None):
# In production: PROMETHEUS_GAUGE.labels(**labels).set(value)
pass
class TracingDecorator:
"""Decorator for distributed tracing"""
def __init__(self, tracer=None):
self.tracer = tracer # OpenTelemetry tracer
def trace_step(self, step_id: str, saga_id: str):
"""Create tracing context for step execution"""
if self.tracer:
# return self.tracer.start_as_current_span(f"saga.step.{step_id}")
pass
return None
def trace_compensation(self, step_id: str, saga_id: str):
"""Create tracing context for compensation"""
if self.tracer:
# return self.tracer.start_as_current_span(f"saga.compensation.{step_id}")
pass
return None
class DeadLetterQueue:
"""Dead Letter Queue handler for failed sagas"""
def __init__(self, storage_backend: Optional[Callable] = None):
self.storage = storage_backend or self._default_storage
self.failed_sagas: List[Saga] = []
def _default_storage(self, saga: Saga):
"""Default in-memory storage (replace with DB/queue in production)"""
self.failed_sagas.append(saga)
logger.warning(f"Saga {saga.saga_id} moved to DLQ. Reason: {saga.failure_reason}")
async def store(self, saga: Saga):
"""Store failed saga in DLQ"""
try:
if asyncio.iscoroutinefunction(self.storage):
await self.storage(saga)
else:
self.storage(saga)
except Exception as e:
logger.error(f"Failed to store saga {saga.saga_id} in DLQ: {e}")
# Could implement retry logic for DLQ storage itself
def get_failed_sagas(self, limit: int = 100) -> List[Saga]:
"""Retrieve failed sagas from DLQ"""
return self.failed_sagas[-limit:]
class SagaOrchestrator:
"""Main saga orchestrator with compensation, retries, and observability"""
def __init__(
self,
metrics_collector: Optional[MetricsCollector] = None,
dlq: Optional[DeadLetterQueue] = None,
tracer: Optional[TracingDecorator] = None,
logger: Optional[logging.Logger] = None
):
self.metrics = metrics_collector or MetricsCollector()
self.dlq = dlq or DeadLetterQueue()
self.tracer = tracer or TracingDecorator()
self.logger = logger or logging.getLogger(__name__)
self.running_sagas: Dict[str, Saga] = {}
async def execute_saga(self, saga: Saga) -> Saga:
"""Execute a saga with full lifecycle management"""
try:
self.running_sagas[saga.saga_id] = saga
saga.state = SagaState.RUNNING
saga.updated_at = datetime.utcnow()
self.logger.info(f"Starting saga {saga.saga_id}: {saga.name}")
self.metrics.increment("sagas_started")
# Execute all steps sequentially
for step_config in saga.steps:
step_id = step_config["step_id"]
# Check condition if exists
if step_config.get("condition"):
if not step_config["condition"](saga.context):
saga.step_results[step_id] = StepResult(
step_id=step_id,
status=StepStatus.SKIPPED,
started_at=datetime.utcnow(),
completed_at=datetime.utcnow()
)
self.logger.info(f"Step {step_id} skipped (condition false)")
continue
# Execute step with retry logic
result = await self._execute_step_with_retry(saga, step_config)
saga.step_results[step_id] = result
if result.status == StepStatus.FAILED:
saga.state = SagaState.FAILED
saga.failure_reason = f"Step {step_id} failed: {str(result.error)}"
await self._trigger_compensation(saga)
await self._handle_failure(saga)
return saga
# Update context with step output
if result.output is not None:
saga.context[f"step_{step_id}_output"] = result.output
# All steps succeeded
saga.state = SagaState.COMPLETED
self.metrics.increment("sagas_completed")
self.logger.info(f"Saga {saga.saga_id} completed successfully")
except Exception as e:
saga.state = SagaState.FAILED
saga.failure_reason = f"Orchestrator error: {str(e)}"
await self._trigger_compensation(saga)
await self._handle_failure(saga)
self.logger.error(f"Saga {saga.saga_id} failed with orchestrator error: {e}")
finally:
saga.updated_at = datetime.utcnow()
if saga.saga_id in self.running_sagas:
del self.running_sagas[saga.saga_id]
return saga
async def _execute_step_with_retry(
self,
saga: Saga,
step_config: Dict[str, Any]
) -> StepResult:
"""Execute a step with exponential backoff retry"""
step_id = step_config["step_id"]
retry_policy = step_config["retry_policy"]
action = step_config["action"]
timeout = step_config.get("timeout_seconds", 300.0)
result = StepResult(step_id=step_id, status=StepStatus.PENDING)
attempt = 0
while attempt < retry_policy["max_attempts"]:
attempt += 1
result.attempts = attempt
result.started_at = datetime.utcnow()
try:
self.logger.debug(f"Executing step {step_id}, attempt {attempt}/{retry_policy['max_attempts']}")
# Execute with timeout
async with asyncio.timeout(timeout):
output = await self._execute_action(action, saga.context)
result.status = StepStatus.SUCCEEDED
result.output = output
result.completed_at = datetime.utcnow()
duration = (result.completed_at - result.started_at).total_seconds()
self.metrics.record_duration(
"step_duration_seconds",
duration,
{"step": step_id, "saga": saga.name}
)
self.metrics.increment("steps_executed", labels={"step": step_id})
self.logger.info(f"Step {step_id} succeeded on attempt {attempt}")
return result
except asyncio.TimeoutError:
error = TimeoutError(f"Step {step_id} timed out after {timeout}s")
result.error = error
self.logger.warning(f"Step {step_id} timeout on attempt {attempt}: {error}")
except Exception as e:
result.error = e
self.logger.warning(f"Step {step_id} failed on attempt {attempt}: {e}")
# Check if we should retry
if attempt < retry_policy["max_attempts"]:
backoff_ms = min(
retry_policy["initial_backoff_ms"] *
(retry_policy["backoff_multiplier"] ** (attempt - 1)),
retry_policy["max_backoff_ms"]
)
self.metrics.increment("retries")
self.logger.info(f"Retrying step {step_id} in {backoff_ms}ms")
await asyncio.sleep(backoff_ms / 1000.0)
else:
result.completed_at = datetime.utcnow()
self.logger.error(f"Step {step_id} failed after {attempt} attempts")
return result
return result
async def _execute_action(self, action: Callable, context: Dict[str, Any]) -> Any:
"""Execute step action with tracing"""
span = self.tracer.trace_step("action", context.get("saga_id", "unknown"))
try:
if asyncio.iscoroutinefunction(action):
return await action(context)
else:
return action(context)
finally:
if span:
span.end()
async def _trigger_compensation(self, saga: Saga):
"""Trigger compensation for all completed steps in reverse order"""
saga.state = SagaState.COMPENSATING
saga.compensation_triggered_at = datetime.utcnow()
self.logger.info(f"Starting compensation for saga {saga.saga_id}")
self.metrics.increment("sagas_compensated")
# Get successful steps in reverse order
successful_steps = [
(step_id, result)
for step_id, result in saga.step_results.items()
if result.status == StepStatus.SUCCEEDED
]
successful_steps.sort(key=lambda x: saga.steps.index(
next(s for s in saga.steps if s["step_id"] == x[0])
), reverse=True)
for step_id, result in successful_steps:
step_config = next(s for s in saga.steps if s["step_id"] == step_id)
try:
self.logger.info(f"Compensating step {step_id} for saga {saga.saga_id}")
span = self.tracer.trace_compensation(step_id, saga.saga_id)
try:
compensation = step_config["compensation"]
if asyncio.iscoroutinefunction(compensation):
await compensation(saga.context, result.output)
else:
compensation(saga.context, result.output)
result.status = StepStatus.COMPENSATED
result.compensation_attempts += 1
self.metrics.increment("compensations", labels={"step": step_id})
self.logger.info(f"Step {step_id} compensated successfully")
finally:
if span:
span.end()
except Exception as e:
self.logger.error(f"Compensation failed for step {step_id}: {e}")
# Continue compensating other steps even if one fails
saga.state = SagaState.COMPENSATED
self.logger.info(f"Compensation completed for saga {saga.saga_id}")
async def _handle_failure(self, saga: Saga):
"""Handle saga failure (move to DLQ after compensation)"""
saga.state = SagaState.IN_DLQ
self.metrics.increment("sagas_moved_to_dlq")
try:
await self.dlq.store(saga)
self.logger.error(f"Saga {saga.saga_id} moved to DLQ. Reason: {saga.failure_reason}")
except Exception as e:
self.logger.error(f"Failed to move saga {saga.saga_id} to DLQ: {e}")
def get_saga_status(self, saga_id: str) -> Optional[Dict[str, Any]]:
"""Get current status of a saga"""
saga = self.running_sagas.get(saga_id)
if not saga:
# Check DLQ
for failed_saga in self.dlq.failed_sagas:
if failed_saga.saga_id == saga_id:
return self._serialize_saga(failed_saga)
return None
return self._serialize_saga(saga)
def _serialize_saga(self, saga: Saga) -> Dict[str, Any]:
"""Serialize saga for reporting"""
return {
"saga_id": saga.saga_id,
"name": saga.name,
"state": saga.state.value,
"created_at": saga.created_at.isoformat(),
"updated_at": saga.updated_at.isoformat(),
"compensation_triggered_at": (
saga.compensation_triggered_at.isoformat()
if saga.compensation_triggered_at else None
),
"failure_reason": saga.failure_reason,
"steps": [
{
"step_id": step["step_id"],
"status": saga.step_results.get(step["step_id"], StepResult(step_id=step["step_id"], status=StepStatus.PENDING)).status.value,
"attempts": saga.step_results.get(step["step_id"], StepResult(step_id=step["step_id"], status=StepStatus.PENDING)).attempts,
"compensation_attempts": saga.step_results.get(step["step_id"], StepResult(step_id=step["step_id"], status=StepStatus.PENDING)).compensation_attempts
}
for step in saga.steps
]
}
# Example usage and test
async def example_saga():
"""Example saga implementation"""
# Define step actions and compensations
async def create_order(context: Dict[str, Any]) -> Dict[str, Any]:
order_id = f"ORDER-{uuid4().hex[:8]}"
context["order_id"] = order_id
# Simulate API call
await asyncio.sleep(0.1)
return {"order_id": order_id, "status": "created"}
def create_order_compensation(context: Dict[str, Any], output: Dict[str, Any]):
# Compensation: cancel order
order_id = context.get("order_id")
if order_id:
logger.info(f"Cancelling order {order_id}")
# Simulate cancellation API call
# await cancel_order_api(order_id)
async def process_payment(context: Dict[str, Any]) -> Dict[str, Any]:
if "order_id" not in context:
raise ValueError("No order_id in context")
payment_id = f"PAY-{uuid4().hex[:8]}"
context["payment_id"] = payment_id
await asyncio.sleep(0.2)
# Simulate payment processing that sometimes fails
if context.get("force_payment_failure"):
raise ValueError("Payment processing failed")
return {"payment_id": payment_id, "status": "paid"}
def process_payment_compensation(context: Dict[str, Any], output: Dict[str, Any]):
payment_id = context.get("payment_id")
if payment_id:
logger.info(f"Refunding payment {payment_id}")
# Simulate refund
# await refund_payment_api(payment_id)
async def send_notification(context: Dict[str, Any]) -> Dict[str, Any]:
await asyncio.sleep(0.05)
return {"notification_id": f"NOTIF-{uuid4().hex[:8]}", "status": "sent"}
def send_notification_compensation(context: Dict[str, Any], output: Dict[str, Any]):
# No compensation needed for notifications (fire-and-forget)
pass
# Create saga
saga = Saga(name="order_fulfillment")
saga.add_step(
step_id="create_order",
action=create_order,
compensation=create_order_compensation,
retry_policy={
"max_attempts": 2,
"initial_backoff_ms": 500,
"max_backoff_ms": 5000
}
)
saga.add_step(
step_id="process_payment",
action=process_payment,
compensation=process_payment_compensation,
condition=lambda ctx: ctx.get("order_id") is not None
)
saga.add_step(
step_id="send_notification",
action=send_notification,
compensation=send_notification_compensation
)
# Execute saga
orchestrator = SagaOrchestrator()
# Test success case
print("=== Running successful saga ===")
result = await orchestrator.execute_saga(saga)
print(f"Saga result: {result.state.value}")
# Test failure case
print("\n=== Running failing saga ===")
saga2 = Saga(name="order_fulfillment_failing")
saga2.context["force_payment_failure"] = True
saga2.add_step("create_order", create_order, create_order_compensation)
saga2.add_step("process_payment", process_payment, process_payment_compensation)
saga2.add_step("send_notification", send_notification, send_notification_compensation)
result2 = await orchestrator.execute_saga(saga2)
print(f"Saga result: {result2.state.value}")
print(f"Compensation triggered: {result2.compensation_triggered_at is not None}")
# Check DLQ
print(f"\nDLQ size: {len(orchestrator.dlq.failed_sagas)}")
# Get saga status
status = orchestrator.get_saga_status(saga2.saga_id)
print(f"Saga status: {status}")
if __name__ == "__main__":
# Configure logging
logging.basicConfig(level=logging.INFO)
# Run example
asyncio.run(example_saga())
# production_config.py
class ProductionSagaOrchestrator(SagaOrchestrator):
"""Production-ready saga orchestrator with additional features"""
def __init__(self, config: Dict[str, Any]):
super().__init__()
self.config = config
# Initialize real storage backends
self._init_storage()
self._init_observability()
self._init_retry_scheduler()
def _init_storage(self):
"""Initialize database/queue storage"""
# Example with PostgreSQL
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
self.db_engine = create_engine(self.config["database_url"])
self.Session = sessionmaker(bind=self.db_engine)
# Initialize DLQ with database storage
self.dlq = DatabaseDeadLetterQueue(self.db_engine)
"""
pass
def _init_observability(self):
"""Initialize metrics and tracing"""
# Prometheus metrics
"""
from prometheus_client import Counter, Histogram, Gauge, start_http_server
self.SAGA_COUNTER = Counter(
'saga_executions_total',
'Total saga executions',
['saga_name', 'status']
)
self.STEP_DURATION = Histogram(
'step_duration_seconds',
'Step execution duration',
['step_id', 'saga_name']
)
start_http_server(8000) # Prometheus metrics endpoint
"""
pass
def _init_retry_scheduler(self):
"""Initialize background retry scheduler"""
# Use Celery or similar for async retry scheduling
"""
from celery import Celery
self.celery = Celery('saga_retries')
self.celery.conf.broker_url = self.config["redis_url"]
"""
pass
async def schedule_retry(self, saga: Saga, step_id: str, attempt: int):
"""Schedule retry with exponential backoff"""
step_config = next(s for s in saga.steps if s["step_id"] == step_id)
backoff_ms = min(
step_config["retry_policy"]["initial_backoff_ms"] *
(step_config["retry_policy"]["backoff_multiplier"] ** (attempt - 1)),
step_config["retry_policy"]["max_backoff_ms"]
)
# In production, use message queue
"""
self.celery.send_task(
'retry_saga_step',
args=[saga.saga_id, step_id],
countdown=backoff_ms / 1000.0
)
"""
await asyncio.sleep(backoff_ms / 1000.0)
class DatabaseDeadLetterQueue(DeadLetterQueue):
"""Database-backed DLQ"""
def __init__(self, db_engine):
self.db_engine = db_engine
# Create table if not exists
async def store(self, saga: Saga):
"""Store saga in database"""
with self.db_engine.connect() as conn:
conn.execute(
"""
INSERT INTO saga_dlq
(saga_id, saga_name, state, failure_reason, context, steps, created_at)
VALUES (%s, %s, %s, %s, %s, %s, %s)
""",
saga.saga_id, saga.name, saga.state.value,
saga.failure_reason,
json.dumps(saga.context),
json.dumps([
{
"step_id": s["step_id"],
"retry_policy": s["retry_policy"]
}
for s in saga.steps
]),
saga.created_at
)