Saga Pattern & Distributed Transactions
π New Features
Saga Pattern & Distributed Transactions
- Saga Orchestrator: Introduced Saga and SagaTransaction to manage long-running distributed transactions across multiple services 2. or internal operations.
- Step-Based Execution: Added SagaStepHandler interface. Each step defines an act (forward action) and compensate (rollback action) method.
- Automatic Compensation: If any step fails, the Saga automatically triggers compensation for all previously completed steps in reverse order (LIFO).
- State Persistence: Introduced ISagaStorage protocol with MemorySagaStorage implementation. Sagas now persist their state (RUNNING, COMPENSATING, FAILED, COMPLETED) and execution history, enabling crash recovery.
- Recovery Tooling: Added recover_saga() utility to resume interrupted sagas from their last known consistent state.
π‘ Reliability & Recovery Strategy
This release implements a Strict Backward Recovery strategy to guarantee data consistency:
- Point of No Return: Once a Saga enters COMPENSATING or FAILED status, forward execution is permanently disabled. Recovery will only complete pending compensations.
- Zombie State Prevention: Prevents scenarios where a partial rollback conflicts with a retried forward execution.
- Idempotency: The recovery mechanism automatically skips steps that were already successfully completed (or compensated) to prevent double-execution.
- Resilient Compensation: Added configurable exponential backoff and retry mechanisms specifically for compensation steps (compensation_retry_count, compensation_retry_delay).
β‘οΈ Implementation Details
- Type Safety: Full generic type support for SagaContext. The context is strictly typed throughout the transaction.
- DI Integration: Step handlers are resolved dynamically via the Dependency Injection container, allowing seamless injection of repositories and API clients.
- Middleware Support: Saga execution supports the existing middleware chain for logging, context propagation, etc.
- Flexible Context Serialization: Support for Pydantic models, DataClasses, and standard dictionaries for state persistence.
π Documentation & Examples
- Core Examples: Added examples/saga.py demonstrating success and failure scenarios.
- FastAPI Integration: Added examples/fastapi_saga_sse.py showing how to stream Saga progress to clients via Server-Sent Events (SSE).
- Recovery Guide: Added comprehensive documentation on how the recovery strategy works and how to implement storage backends.
π§ͺ Testing
- Extensive test suite added covering complex edge cases:
- Recovery from crashes during forward execution.
- Recovery from crashes during compensation (ensuring the rollback completes).
- Verification of the "Point of No Return" logic.
- Idempotency checks for step re-execution.