Rate limiting in FastAPI

Difficulty: Intermediate

Question

How do you implement rate limiting in a FastAPI application?

Answer

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

Code examples

Rate limiting with SlowAPI

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

Key points

  • SlowAPI requires the `Request` parameter in the route for IP extraction
  • Use Redis backend in production: `Limiter(key_func=..., storage_uri='redis://localhost')`
  • Rate limit headers (X-RateLimit-Limit, X-RateLimit-Remaining) are added automatically

Common follow-up questions

  • How do you apply different rate limits to free vs premium users?
  • What is the difference between rate limiting at the application level vs the gateway level?

Interview tips

  • Mention that in-memory rate limiting doesn't work in multi-process or multi-server setups - Redis is needed

Concepts covered

rate limiting, slowapi, throttling, Redis

More FastAPI Interview questions