← Back to FastAPI, page 3

fastapi-0041 · Hard senior

How would you add rate limiting to a FastAPI API that runs on several servers?

Rate limits need a shared counter, so with several servers store state in Redis (or use the API gateway's limiter). Implement a fixed window, sliding window or token bucket keyed by user ID, API key or client IP, apply it as a dependency or middleware, and return 429 with Retry-After and rate-limit headers. Use stricter limits on sensitive endpoints such as login and OTP, and keep coarse limits at the edge (CDN, gateway) for floods.

Full answer

Why: protect the service and the database from abuse and accidents (a buggy client loop), share capacity fairly, and slow down brute-force attacks on login or OTP endpoints.

Where to enforce:

  • Edge (CDN, WAF, API gateway, Nginx limit_req): cheapest, stops floods before they reach Python.
  • Application: needed for limits by user, plan or endpoint, which the edge cannot see.

Algorithms:

  • Fixed window: count requests per key per minute (INCR key; EXPIRE key 60). Simple; allows bursts at window edges (up to twice the limit across a boundary).
  • Sliding window log or counter: smoother, more memory or math.
  • Token bucket: tokens refill at a steady rate up to a burst size; each request takes one. Allows short bursts but enforces the average. Popular for APIs.

Shared state: in-process dictionaries only work with one process. With several workers or servers, use Redis with atomic operations (INCR plus EXPIRE in a pipeline, or a Lua script for token buckets) so all instances see the same counts.

Keys: authenticated user ID or API key first; client IP for anonymous traffic (behind a proxy, take the IP from trusted forwarded headers only, or attackers rotate fake IPs). Consider limits per endpoint group: login 5 per minute per account and per IP, search 60 per minute per user.

Response: status 429, Retry-After seconds, and informational headers (RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset, standardised in the IETF RateLimit header drafts; older APIs use X-RateLimit-*).

In FastAPI, a dependency is the natural fit: it can read the current user and be attached per route or per router. Libraries such as slowapi or fastapi-limiter provide ready implementations.

Fail-open or fail-closed: if Redis is down, decide deliberately. Many APIs fail open for normal endpoints (availability) and fail closed for login (security).

python
import time
from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException, Response
from fastapi.testclient import TestClient


class FakeRedis:
    """Mimics the two Redis commands a fixed-window limiter needs (INCR and EXPIRE)."""

    def __init__(self):
        self.data, self.expiry = {}, {}

    def incr(self, key):
        if key in self.expiry and self.expiry[key] <= time.time():
            self.data.pop(key, None); self.expiry.pop(key, None)
        self.data[key] = self.data.get(key, 0) + 1
        return self.data[key]

    def expire(self, key, seconds, nx=True):
        if not (nx and key in self.expiry):
            self.expiry[key] = time.time() + seconds

    def ttl(self, key):
        return max(0, int(self.expiry.get(key, time.time()) - time.time()))


redis = FakeRedis()        # use redis.asyncio.Redis in production


class RateLimit:
    def __init__(self, limit: int, window: int, scope: str):
        self.limit, self.window, self.scope = limit, window, scope

    def __call__(self, response: Response, x_api_key: Annotated[str, Header()]):
        window_id = int(time.time() // self.window)
        key = f"rl:{self.scope}:{x_api_key}:{window_id}"
        count = redis.incr(key)
        redis.expire(key, self.window)
        remaining = max(0, self.limit - count)
        response.headers["RateLimit-Limit"] = str(self.limit)
        response.headers["RateLimit-Remaining"] = str(remaining)
        if count > self.limit:
            # headers set on `response` are dropped when an exception is raised, so repeat them here
            raise HTTPException(status_code=429, detail="Too many requests",
                                headers={"Retry-After": str(max(1, redis.ttl(key))),
                                         "RateLimit-Limit": str(self.limit), "RateLimit-Remaining": "0"})


app = FastAPI()


@app.post("/login", dependencies=[Depends(RateLimit(limit=3, window=60, scope="login"))])
def login():
    return {"ok": True}


@app.get("/timetable", dependencies=[Depends(RateLimit(limit=100, window=60, scope="read"))])
def timetable():
    return {"monday": ["Maths", "DBMS"]}


c = TestClient(app)
key = {"X-API-Key": "app-123"}
for _ in range(4):
    r = c.post("/login", headers=key)
    print(r.status_code, r.headers.get("ratelimit-remaining"), r.headers.get("retry-after") is not None)
print(c.get("/timetable", headers=key).status_code, "(separate limit)")
print(c.post("/login", headers={"X-API-Key": "other-app"}).status_code, "(separate key)")

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. FakeRedis mirrors INCR and EXPIRE so the example runs without a Redis server; swap in redis.asyncio for real use. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 200 2 False 200 1 False 200 0 False 429 0 True 200 (separate limit) 200 (separate key)

Key points

  • Use shared state (Redis) when running several processes
  • Fixed window, sliding window, token bucket trade-offs
  • Key by user or API key; IP only from trusted proxies
  • 429 with Retry-After and RateLimit headers
  • Edge limits for floods; app limits for per-user rules

Common mistakes

  • Keeping counters in process memory with several workers or servers
  • Keying anonymous limits on X-Forwarded-For from untrusted clients
  • Returning 429 without Retry-After
  • Setting headers on the injected Response and expecting them on an HTTPException response
  • Using one global limit for login and for cheap read endpoints
  • Not deciding what happens when Redis is unavailable

Follow-ups

  • How would you implement a token bucket atomically in Redis?
  • How would you rate limit by subscription plan?
  • Should the limiter fail open or closed if Redis is down?

Tips

  • Mention shared state first, it is the core of the multi-server question
  • Compare at least two algorithms
  • Cover headers, keys and failure mode