Difficulty: Intermediate
How do you implement rate limiting in a FastAPI application?
FastAPI doesn't include built-in rate limiting, but the most popular solution is SlowAPI, a library built on top of `limits`. It integrates as middleware and supports multiple storage backends.
SlowAPI uses a decorator `@limiter.limit()` on individual routes. Limits are specified as strings like `'5/minute'` or `'100/hour'`. The client is identified by IP address by default, but you can customize the key function (e.g., by user ID or API key).
For production, use Redis as the backend so limits are shared across multiple server instances. In-memory storage works for single-instance development.
Alternative approaches: - Custom middleware with Redis INCR + EXPIRE - API gateway-level limiting (Nginx, Kong, AWS API Gateway) - Token bucket algorithm for burst-friendly limits
from fastapi import FastAPI, Request
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@app.get("/search")
@limiter.limit("10/minute")
async def search(request: Request, q: str = ""):
return {"results": [], "query": q}
@app.get("/health")
async def health():
return {"status": "ok"} # no rate limit on health checks
rate limiting, slowapi, throttling, Redis