Performance: Request timing middleware
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 |
import time
from fastapi import FastAPI
app = FastAPI()
@app.middleware('http')
async def add_process_time_header(request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers['X-Process-Time'] = str(process_time)
return responseimport time
from fastapi import FastAPI
app = FastAPI()
@app.middleware('http')
def timing_middleware(request, call_next):
start = time.time()
response = call_next(request)
duration = time.time() - start
response.headers['X-Time'] = str(duration)
return responsePass the test and this pattern moves unknown