Performance: Rate limiting
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 |
What is the main purpose of rate limiting in a FastAPI application?
Which of the following is the correct way to import a rate limiter middleware in FastAPI?
from fastapi import FastAPI
from _____ import RateLimiterMiddleware
app = FastAPI()
app.add_middleware(RateLimiterMiddleware, max_requests=5, window_seconds=60)
Given this FastAPI code snippet using fastapi_limiter:
from fastapi import FastAPI
from fastapi_limiter import FastAPILimiter
from fastapi_limiter.depends import RateLimiter
import aioredis
app = FastAPI()
@app.on_event("startup")
async def startup():
redis = await aioredis.from_url("redis://localhost")
await FastAPILimiter.init(redis)
@app.get("/items", dependencies=[Depends(RateLimiter(times=3, seconds=10))])
async def read_items():
return {"message": "Success"}
What happens if a user calls /items 4 times within 10 seconds?
Identify the error in this FastAPI rate limiting setup:
from fastapi import FastAPI
from fastapi_limiter import FastAPILimiter
import aioredis
app = FastAPI()
@app.on_event("startup")
async def startup():
redis = aioredis.from_url("redis://localhost")
await FastAPILimiter.init(redis)
@app.get("/data", dependencies=[Depends(RateLimiter(times=2, seconds=5))])
async def get_data():
return {"data": "info"}
You want to limit users to 10 requests per minute globally across multiple FastAPI instances behind a load balancer. Which setup is best?
1. Use in-memory counters in each instance
2. Use Redis with fastapi_limiter shared by all instances
3. Use local file storage for counts
4. Disable rate limitingPass the test and this pattern moves unknown