Skip to content

Production API stack

This recipe combines rate limiting, caching, and traffic management in a single FastAPI service:

  • Public endpoints (/catalog) are coalesced and cached at the middleware layer before reaching the application.
  • Authenticated endpoints (/me/projects) bypass the public cache, enforce per-user rate limits, cache typed Pydantic models per user, and automatically invalidate on writes.
  • Expensive endpoints (/me/export) add a per-user concurrency limit and a tighter route-level deadline.
  • Health checks (/healthz) are exempt from load shedding so orchestrators do not evict busy instances.

Primitives

Create the shared instances once (with RedisStore in multi-worker deployments):

limiter = Limiter()
cache = Cache(ttl=300)
shedder = LoadShedder({"anonymous": 0.5, "free": 0.8}, max_in_flight=200, max_lag=0.25)
app_deadline = Deadline(30)
app_concurrency = ConcurrencyLimit(100, wait=0.5)
export_concurrency = ConcurrencyLimit(2, retry_after=5)
export_deadline = Deadline(10)

Authentication and shedding priority

LoadSheddingMiddleware classifies requests before routing or FastAPI dependencies run, so priority reads only from the HTTPConnection:

def priority(conn: HTTPConnection) -> str | None:
    """Classify requests for load shedding before routing or auth dependencies run."""
    if conn.url.path == "/healthz":
        return None
    token = conn.headers.get("authorization", "").removeprefix("Bearer ")
    account = TOKENS.get(token)
    return account[1] if account is not None else "anonymous"


async def current_user(authorization: Annotated[str | None, Header()] = None) -> str:
    token = (authorization or "").removeprefix("Bearer ")
    account = TOKENS.get(token)
    if account is None:
        raise HTTPException(401, "Invalid or missing bearer token")
    return account[0]


async def user_key(user: Annotated[str, Depends(current_user)]) -> str:
    return f"user:{user}"

Middleware order

Starlette runs middleware added last on the outside. Requests flow top-to-bottom from LoadSheddingMiddleware down to ConcurrencyLimitMiddleware:

public = cache.namespace("public", ttl=60)
users = cache.namespace("user", ttl=300)

# Middleware runs bottom-to-top on inbound requests:
# LoadShedding -> Deadline -> RateLimit -> Coalescing -> ResponseCache -> Concurrency -> App
app.add_middleware(ConcurrencyLimitMiddleware, limit=app_concurrency)
app.add_middleware(
    ResponseCacheMiddleware,
    namespace=public,
    resource="catalog",
    client_ttl=15,
)
app.add_middleware(CoalescingMiddleware)
app.add_middleware(RateLimitMiddleware, limiter=limiter, rates=global_rate, scope="global")
app.add_middleware(DeadlineMiddleware, deadline=app_deadline)
app.add_middleware(LoadSheddingMiddleware, shedder=shedder, priority=priority)

See Middleware order for why each layer sits where it does.

Routes

@users.cached("projects", entity="user_id", key=("user_id",))
async def load_projects(user_id: str) -> list[Project]:
    return await db.list_projects(user_id)

@app.get("/healthz")
async def health() -> dict[str, str]:
    return {"status": "ok"}

@app.get("/catalog")
async def catalog() -> list[dict[str, object]]:
    return await db.list_catalog()

@app.get(
    "/me/projects",
    dependencies=[Depends(limiter.limit(user_rate, key=user_key))],
)
async def get_projects(user: Annotated[str, Depends(current_user)]) -> list[Project]:
    return await load_projects(user)

@app.post(
    "/me/projects",
    dependencies=[Depends(limiter.limit(user_rate, key=user_key))],
)
@users.invalidates("projects", entity="user")
async def create_project(
    project: Project,
    user: Annotated[str, Depends(current_user)],
) -> Project:
    return await db.add_project(user, project)

@app.post(
    "/me/export",
    dependencies=[Depends(limiter.limit(user_rate, key=user_key))],
)
@export_concurrency.held(key="user")
@export_deadline.enforced()
async def export_data(user: Annotated[str, Depends(current_user)]) -> dict[str, object]:
    return await db.run_export(user)

Key details

  • Shed requests never consume rate limits. Because LoadSheddingMiddleware runs outside RateLimitMiddleware, shedding anonymous callers under load does not burn their quota.
  • Coalescing wraps the response cache. Concurrent requests on a cold /catalog cache trigger one cache read, one app call, and one cache write.
  • Coalesced requests count once against route limits. Concurrent identical GET /me/projects requests from one token share one response, so the route's per-user limit counts the burst once. RateLimitMiddleware sits outside coalescing and counts every request.
  • Authenticated requests bypass the public cache. ResponseCacheMiddleware skips requests with Authorization or Cookie headers by default, leaving /me/projects to route-level auth and per-user @users.cached.
  • Route decorators stack inner-to-outer. @export_concurrency.held(key="user") sits outside @export_deadline.enforced(), so the slot is always released when the deadline cancels the endpoint.

Full source: examples/production_api.py.