9. Middleware & Request Flow

What Middleware Really Intercepts

Middleware in FastAPI intercepts requests before they reach route handlers and responses before they are returned to clients. It operates at the framework boundary, allowing cross-cutting concerns to be applied uniformly. Middleware is ideal for behavior that must affect all or most requests consistently.


Request → Response Lifecycle

A FastAPI request passes through middleware layers, routing, dependency resolution, and endpoint execution before returning a response. Each stage has a clearly defined responsibility in the lifecycle. Understanding this flow is essential for debugging, performance tuning, and correct placement of logic.


Logging, Timing, and Headers

Middleware is commonly used to implement request logging, execution timing, and custom header injection. These concerns are orthogonal to business logic and benefit from centralized handling. Proper middleware design improves observability without cluttering endpoint code.

import time
from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_process_time(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    response.headers["X-Process-Time"] = str(time.time() - start_time)
    return response

When Not to Use Middleware

Middleware should not be used for request-specific business logic or operations that depend on route-level context. Overusing middleware can obscure control flow and make behavior harder to reason about. Route handlers and dependencies are often more appropriate for localized concerns.

Last updated