Enterprise Cloud Architecture, Zero Trust Cybersecurity, LLMOps & High-Scale Systems

Software Architecture

Designing Idempotent APIs: Handling Network Retries and Duplicate Requests at Scale

November 11, 2026 ยท By writer

In distributed microservice networks, network partitions and client timeouts are inevitable. When a client initiates a financial transfer and experiences a connection timeout, retrying the HTTP POST request without idempotency protections risks catastrophic double-billing. Architectural resilience mandates that mutating operations are strictly idempotent: processing a request once or twenty times must yield identical side effects and state transitions.

The Idempotency Key Lifecycle: IETF Standards

Modern enterprise APIs (e.g., Stripe, Shopify) follow the IETF Idempotency-Key specification, where clients generate a unique UUIDv4 sent via HTTP header: Idempotency-Key: <uuid>. The API gateway or service middleware enforces the following state machine:

Incoming Key StateCurrent Processing StatusAPI Gateway ActionHTTP Response
Key Absent in CacheNew requestAcquire distributed lock, execute business logic, cache response200 OK / 201 Created
Key Present (IN_PROGRESS)Concurrent inflight executionReject concurrent duplicate request to prevent race conditions409 Conflict
Key Present (COMPLETED)Prior execution completedShort-circuit downstream, return cached response payloadOriginal HTTP Status + Body

Production FastAPI & Redis Idempotency Middleware

Below is a production Python implementation leveraging Redis atomic operations and distributed locking to guarantee safe idempotency:

# idempotency_middleware.py
import json
import redis
from fastapi import Request, Response, HTTPException
from starlette.middleware.base import BaseHTTPMiddleware

class IdempotencyMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, redis_client: redis.Redis, ttl_seconds: int = 86400):
        super().__init__(app)
        self.r = redis_client
        self.ttl = ttl_seconds

    async def dispatch(self, request: Request, call_next):
        # Only enforce idempotency on mutating operations
        if request.method not in ("POST", "PATCH"):
            return await call_next(request)

        idempotency_key = request.headers.get("Idempotency-Key")
        if not idempotency_key:
            return await call_next(request)

        redis_key = f"idempotency:{idempotency_key}"

        # 1. Attempt atomic lock acquisition (SET NX EX)
        # Sets status to 'IN_PROGRESS' if key does not exist
        acquired = self.r.set(redis_key, json.dumps({"status": "IN_PROGRESS"}), nx=True, ex=60)
        
        if not acquired:
            # Key already exists: inspect cached state
            cached_data = json.loads(self.r.get(redis_key))
            if cached_data.get("status") == "IN_PROGRESS":
                raise HTTPException(status_code=409, detail="A request with this Idempotency-Key is currently processing.")
            
            # Request already succeeded previously: return original response
            return Response(
                content=cached_data["body"],
                status_code=cached_data["status_code"],
                headers=cached_data["headers"]
            )

        try:
            # 2. Execute actual downstream application logic
            response = await call_next(request)
            
            # Read response body
            body = [chunk async for chunk in response.body_iterator]
            full_body = b"".join(body).decode("utf-8")

            # 3. Store final response with 24-hour TTL
            cache_payload = {
                "status": "COMPLETED",
                "status_code": response.status_code,
                "headers": dict(response.headers),
                "body": full_body
            }
            self.r.set(redis_key, json.dumps(cache_payload), ex=self.ttl)
            return Response(content=full_body, status_code=response.status_code, headers=dict(response.headers))

        except Exception as e:
            # On unexpected failure, release lock to allow client retry
            self.r.delete(redis_key)
            raise e
  • Payload Checksum Validation: Hash the request payload with the idempotency key to prevent clients from reusing identical keys with different payload arguments.
  • Database Unique Constraints: For maximum reliability, back distributed caching with database unique constraints (e.g., UNIQUE (tenant_id, idempotency_key)).
  • Atomic Lock Expirations: Always set an expiration window (e.g., 60 seconds) on inflight locks to avoid deadlocks should a worker process crash abruptly.
๐Ÿท๏ธ Topics: