DEV Community

Aman Kumar
Aman Kumar

Posted on Originally published at dev.to

Designing Fault-Tolerant Async Microservices with FastAPI, Redis, and Circuit Breakers

Designing Fault-Tolerant Async Microservices with FastAPI, Redis, and Circuit Breakers

In modern distributed systems, network partitions, cascading failures, and downstream latency spikes are not edge cases—they are guaranteed states of operation. When building high-throughput asynchronous services using Python and FastAPI, relying solely on standard try/except blocks or basic HTTP timeouts is a recipe for systemic collapse.

To achieve high availability, we need a defense-in-depth architecture combining non-blocking I/O, distributed rate-limiting via Redis token buckets, and client-side circuit breaking.

This article explores how to architect a production-grade, fault-tolerant FastAPI microservice that gracefully handles downstream degradation.


Architectural Data Flow

The following sequence details how an incoming request traverses our resilient middleware stack, bypassing failing downstream dependencies via a circuit breaker and protecting resource exhaustion via Redis rate-limiting.

 [ Client ]
     │
     ▼
 [ FastAPI App ] ──( 1. Check Rate Limit )──> [ Redis Cluster ]
     │                                              │
     ├─( 2. State OK )──────────────────────────────┘
     ▼
 [ Circuit Breaker ] ──( 3. State: CLOSED / HALF-OPEN )
     │
     ├─( If OPEN ) ──> [ Return Fallback Response ]
     │
     └─( If CLOSED )
           │
           ▼
     [ Downstream HTTP Service ] (Timeout / Retry Logic)
Enter fullscreen mode Exit fullscreen mode

Production-Ready Implementation

Below is a complete, syntax-valid, production-ready FastAPI service implementing a distributed Redis rate limiter, a custom async circuit breaker, and robust error handling.

Ensure you have the required dependencies installed:

pip install fastapi uvicorn redis httpx pydantic
Enter fullscreen mode Exit fullscreen mode
import time
import logging
from typing import Callable, Any
from fastapi import FastAPI, HTTPException, status, Request
from fastapi.responses import JSONResponse
import redis.asyncio as aioredis
import httpx
from pydantic_settings import BaseSettings

# --- Configuration & Logging ---
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("ResilientService")

class Settings(BaseSettings):
    REDIS_URL: str = "redis://localhost:6379/0"
    DOWNSTREAM_SERVICE_URL: str = "https://httpbin.org/delay/1"
    RATE_LIMIT_MAX_REQUESTS: int = 5
    RATE_LIMIT_WINDOW: int = 60  # seconds

    class Config:
        env_file = ".env"

settings = Settings()
app = FastAPI(title="Resilient Microservice", version="1.0.0")

# --- Global State / Connections ---
redis_client: aioredis.Redis | None = None

@app.on_event("startup")
async def startup_event():
    global redis_client
    redis_client = aioredis.from_url(settings.REDIS_URL, decode_responses=True)
    logger.info("Connected to Redis instance.")

@app.on_event("shutdown")
async def shutdown_event():
    if redis_client:
        await redis_client.close()
        logger.info("Redis connection closed.")


# --- Circuit Breaker Pattern Implementation ---
class CircuitBreakerOpenException(Exception):
    pass

class AsyncCircuitBreaker:
    def __init__(self, failure_threshold: int = 3, recovery_time: float = 10.0):
        self.failure_threshold = failure_threshold
        self.recovery_time = recovery_time
        self.failure_count = 0
        self.state = "CLOSED"  # CLOSED, OPEN, HALF-OPEN
        self.last_failure_time = 0.0

    async def __call__(self, func: Callable[..., Any], *args, **kwargs) -> Any:
        current_time = time.time()

        # Check if circuit should transition from OPEN to HALF-OPEN
        if self.state == "OPEN":
            if current_time - self.last_failure_time > self.recovery_time:
                logger.warning("Circuit breaker entering HALF-OPEN state.")
                self.state = "HALF-OPEN"
            else:
                logger.error("Circuit breaker is OPEN. Rejecting request.")
                raise CircuitBreakerOpenException("Downstream service unavailable.")

        try:
            result = await func(*args, **kwargs)

            # If successful in HALF-OPEN or CLOSED, reset state
            if self.state in ["HALF-OPEN", "OPEN"]:
                logger.info("Circuit breaker recovered. Resetting to CLOSED.")
                self.state = "CLOSED"
                self.failure_count = 0
            return result

        except Exception as e:
            self.failure_count += 1
            self.last_failure_time = time.time()
            logger.error(f"Execution failed (Attempt {self.failure_count}): {str(e)}")

            if self.failure_count >= self.failure_threshold or self.state == "HALF-OPEN":
                self.state = "OPEN"
                logger.critical(f"Circuit breaker tripped to OPEN state for {self.recovery_time}s.")
            raise e

breaker = AsyncCircuitBreaker(failure_threshold=3, recovery_time=15.0)


# --- Redis Token Bucket Rate Limiter ---
async def check_rate_limit(client_ip: str) -> bool:
    if not redis_client:
        return True  # Fail-open design if cache goes down

    key = f"rate_limit:{client_ip}"
    current = await redis_client.get(key)

    if current is None:
        pipe = redis_client.pipeline()
        pipe.set(key, 1, ex=settings.RATE_LIMIT_WINDOW)
        await pipe.execute()
        return True

    if int(current) >= settings.RATE_LIMIT_MAX_REQUESTS:
        return False

    await redis_client.incr(key)
    return True


# --- Downstream Caller ---
async def call_downstream_service() -> dict:
    async with httpx.AsyncClient(timeout=3.0) as client:
        response = await client.get(settings.DOWNSTREAM_SERVICE_URL)
        response.raise_for_status()
        return response.json()


# --- API Endpoints ---
@app.get("/api/v1/resource")
async def get_resource(request: Request):
    client_ip = request.client.host if request.client else "unknown"

    # 1. Rate Limiting Check
    is_allowed = await check_rate_limit(client_ip)
    if not is_allowed:
        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail="Rate limit exceeded. Try again later."
        )

    # 2. Executing with Circuit Breaker Protection
    try:
        data = await breaker(call_downstream_service)
        return {"status": "success", "data": data}

    except CircuitBreakerOpenException:
        # Fallback response strategy
        return JSONResponse(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            content={
                "status": "degraded",
                "message": "Downstream service is temporarily unavailable. Serving cached or fallback state."
            }
        )
    except httpx.HTTPStatusError as exc:
        logger.error(f"Downstream HTTP error: {exc.response.status_code}")
        raise HTTPException(
            status_code=status.HTTP_502_BAD_GATEWAY,
            detail="Downstream service returned an invalid response."
        )
    except Exception as exc:
        logger.error(f"Unexpected error: {str(exc)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="An unexpected internal error occurred."
        )
Enter fullscreen mode Exit fullscreen mode

Engineering Deep-Dive & Best Practices

  1. Fail-Open vs. Fail-Closed Cache Strategy:
    Notice how check_rate_limit returns True if the Redis connection fails entirely. In high-availability architectures, caching layers should ideally fail-open. You want your API to accept traffic even if the Redis cluster drops momentarily, rather than taking down your entire compute tier because of a state-store outage.

  2. Stateful Circuit Breaking:
    The AsyncCircuitBreaker manages state transitions locally per process instance. In a horizontal auto-scaling environment (like Kubernetes), these counters are isolated per pod. For strict global thresholds, transition state checks should be pushed to Redis hashes or Lua scripts.

  3. Asynchronous Context and Timeouts:
    Using httpx.AsyncClient with an explicit timeout (timeout=3.0) prevents worker thread starvation. In blocking architectures (like older WSGI servers), slow third-party APIs quickly tie up execution threads, causing an entire cluster backlog. FastAPI's native async def routing ensures that while waiting on IO-bound network calls, the event loop can concurrently process incoming requests.


Conclusion

Building reliable microservices requires moving past the illusion of network reliability. By incorporating non-blocking patterns, distributed rate-limiting, and self-healing circuit breakers into your FastAPI services, you drastically reduce blast radii during component outages.

For reference implementations, configurations, and further systems engineering tooling, check out my GitHub profile at aman179102.

Top comments (0)