Performance: Request timing middleware
MEDIUM IMPACT
This affects the server response time and perceived page load speed by measuring how long each request takes to process.
from fastapi import FastAPI, Request import time import asyncio app = FastAPI() @app.middleware("http") async def timing_middleware(request: Request, call_next): start = time.time() response = await call_next(request) end = time.time() duration = end - start # Schedule logging asynchronously without blocking asyncio.create_task(async_log(duration)) return response async def async_log(duration: float): print(f"Request took {duration:.4f} seconds")
from fastapi import FastAPI, Request import time app = FastAPI() @app.middleware("http") async def timing_middleware(request: Request, call_next): start = time.time() response = await call_next(request) end = time.time() duration = end - start # Blocking logging inside middleware print(f"Request took {duration:.4f} seconds") return response
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking synchronous logging in middleware | 0 | 0 | 0 | [X] Bad |
| Asynchronous logging after response | 0 | 0 | 0 | [OK] Good |