Performance: Rate limiting
MEDIUM IMPACT
Rate limiting affects server response time and user interaction speed by controlling request frequency to avoid overload.
from fastapi import FastAPI, Request from starlette.responses import JSONResponse import time app = FastAPI() rate_limits = {} @app.middleware("http") async def fixed_window_rate_limit(request: Request, call_next): client_ip = request.client.host current_time = int(time.time()) window = current_time // 60 # 1-minute window key = f"{client_ip}:{window}" count = rate_limits.get(key, 0) if count >= 100: return JSONResponse(status_code=429, content={"detail": "Too many requests"}) rate_limits[key] = count + 1 response = await call_next(request) return response
from fastapi import FastAPI, Request from starlette.responses import JSONResponse app = FastAPI() @app.middleware("http") async def naive_rate_limit(request: Request, call_next): # Simple in-memory counter without expiration if not hasattr(app.state, 'counter'): app.state.counter = 0 app.state.counter += 1 if app.state.counter > 100: return JSONResponse(status_code=429, content={"detail": "Too many requests"}) response = await call_next(request) return response
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Naive global counter | 0 (server-side only) | 0 | 0 | [X] Bad |
| Per-client fixed window | 0 (server-side only) | 0 | 0 | [OK] Good |