Performance: Why middleware processes requests globally
Middleware affects the time it takes for every request to be processed before reaching route handlers, impacting overall request latency.
Jump into concepts and practice - no test required
from fastapi import FastAPI app = FastAPI() @app.middleware("http") async def fast_middleware(request, call_next): # Non-blocking async operation example response = await call_next(request) return response
from fastapi import FastAPI app = FastAPI() @app.middleware("http") async def slow_middleware(request, call_next): import time time.sleep(0.1) # blocking delay response = await call_next(request) return response
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking middleware with sleep | N/A | N/A | Delays response arrival | [X] Bad |
| Non-blocking async middleware | N/A | N/A | Minimal delay on response | [OK] Good |
add_middleware() on the app instance to add middleware globally.from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
class PrintMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
print("Before request")
response = await call_next(request)
print("After request")
return response
app = FastAPI()
app.add_middleware(PrintMiddleware)
@app.get("/hello")
async def hello():
return {"message": "Hello"}/hello?class MyMiddleware:
async def dispatch(self, request, call_next):
print("Middleware active")
response = await call_next(request)
return response
app = FastAPI()
app.add_middleware(MyMiddleware)BaseHTTPMiddleware or implement ASGI interface properly./api. Why does FastAPI middleware still run on all routes, and how can you limit it?