Performance: Custom middleware creation
MEDIUM IMPACT
This affects the request-response cycle speed and server throughput by adding processing steps before and after handling requests.
from fastapi import FastAPI from starlette.middleware.base import BaseHTTPMiddleware import asyncio app = FastAPI() class EfficientMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): # Non-blocking async processing await asyncio.sleep(0.1) # does not block event loop response = await call_next(request) return response app.add_middleware(EfficientMiddleware)
from fastapi import FastAPI from starlette.middleware.base import BaseHTTPMiddleware app = FastAPI() class SlowMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): # Heavy synchronous processing import time time.sleep(0.1) # blocks event loop response = await call_next(request) return response app.add_middleware(SlowMiddleware)
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking synchronous middleware | N/A | N/A | N/A | [X] Bad |
| Async non-blocking middleware | N/A | N/A | N/A | [OK] Good |
| CPU-heavy synchronous middleware | N/A | N/A | N/A | [X] Bad |
| CPU work offloaded to thread pool | N/A | N/A | N/A | [OK] Good |