DEV Community

Aman Kumar
Aman Kumar

Posted on Originally published at dev.to

Distributed Sagas & Idempotency Keys: Building Resilient Microservices in Python

The Problem: Distributed Partial Failures

In microservices architectures, business workflows (such as payment processing, order placement, and inventory reserving) span multiple independent databases. Distributed 2PC (Two-Phase Commit) protocols introduce severe latency and single-point-of-failure bottlenecks.

To achieve ACID semantics across autonomous services without distributed locks, production architectures combine:

  1. Idempotency Keys: Guaranteeing duplicate HTTP requests (e.g. from network retries) execute exactly once.
  2. The Saga Pattern: Executing sequential local transactions coupled with compensating transactions on failure.

System Workflow

Client Request (ID: uuid)
      |
      v
+---------------------+      Acquire Lock & Check Cache       +--------------------+
| Idempotency Filter  | ------------------------------------> | Redis Key Store    |
| (FastAPI Middleware)| <------------------------------------ | (TTL, State: PEND) |
+---------------------+      Cache HIT -> Return Replay       +--------------------+
      | Cache MISS
      v
+---------------------+        Forward Actions (Order, Payment) +--------------------+
| Saga Orchestrator   | -------------------------------------> | Microservice Step  |
| (State Machine)     | <------------------------------------- | Result / Error     |
+---------------------+         On Failure: Compensate         +--------------------+
Enter fullscreen mode Exit fullscreen mode

Production Implementation: FastAPI Idempotency Middleware & Saga Step

from __future__ import annotations

import asyncio
import json
import uuid
from dataclasses import dataclass, field
from typing import Any, Callable, Coroutine

from fastapi import FastAPI, Header, HTTPException, Request, Response, status
import redis.asyncio as aioredis

app = FastAPI(title="Resilient Order Service")
redis_client = aioredis.from_url("redis://localhost:6379/0", decode_responses=True)


@dataclass
class SagaStep:
    name: str
    action: Callable[[], Coroutine[Any, Any, Any]]
    compensate: Callable[[], Coroutine[Any, Any, Any]]


class SagaOrchestrator:
    """Executes distributed transaction steps with automatic reverse compensation."""
    def __init__(self, saga_id: str):
        self.saga_id = saga_id
        self.steps: list[SagaStep] = []
        self.executed_steps: list[SagaStep] = []

    def add_step(self, step: SagaStep) -> None:
        self.steps.append(step)

    async def execute(self) -> dict[str, Any]:
        results: dict[str, Any] = {}
        for step in self.steps:
            try:
                res = await step.action()
                results[step.name] = res
                self.executed_steps.append(step)
            except Exception as exc:
                # Trigger backward rollback
                await self._rollback()
                raise HTTPException(
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                    detail=f"Saga {self.saga_id} failed at step '{step.name}': {exc}",
                )
        return results

    async def _rollback(self) -> None:
        for step in reversed(self.executed_steps):
            try:
                await step.compensate()
            except Exception as comp_err:
                # Log critical alert for manual operator intervention
                pass


@app.middleware("http")
async def idempotency_middleware(request: Request, call_next: Callable[[Request], Coroutine[Any, Any, Response]]) -> Response:
    idempotency_key = request.headers.get("X-Idempotency-Key")
    if not idempotency_key or request.method not in ("POST", "PUT", "PATCH"):
        return await call_next(request)

    redis_key = f"idempotency:{idempotency_key}"
    # Atomic setnx with 120-second lease
    acquired = await redis_client.set(redis_key, "IN_PROGRESS", nx=True, ex=120)

    if not acquired:
        cached_val = await redis_client.get(redis_key)
        if cached_val == "IN_PROGRESS":
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail="Concurrent request with identical idempotency key is executing.",
            )
        # Return cached serialized response
        cached_data = json.loads(cached_val)
        return Response(
            content=cached_data["content"],
            status_code=cached_data["status_code"],
            media_type="application/json",
            headers={"X-Cache-Lookup": "HIT"},
        )

    response = await call_next(request)

    if response.status_code < 400:
        resp_body = [section async for section in response.body_iterator]
        full_content = b"".join(resp_body).decode("utf-8")
        payload = json.dumps({"status_code": response.status_code, "content": full_content})
        await redis_client.set(redis_key, payload, ex=86400)
        return Response(content=full_content, status_code=response.status_code, media_type="application/json")
    else:
        await redis_client.delete(redis_key)
        return response
Enter fullscreen mode Exit fullscreen mode

Key Architectural Principles

  1. Short Lease Times on Mutexes: Never lock an idempotency key indefinitely without a TTL.
  2. Deterministic Step Ordering: Ensure forward dependencies are verified before side effects are executed.
  3. Idempotent Compensations: Compensating actions must themselves be safe to retry multiple times without accumulating drift.

GitHub Repository: github.com/aman179102

Top comments (0)