Skip to content

Migrating from fastapi-limiter

Guide for migrating FastAPI rate limits from fastapi-limiter (both v0.1.x Redis Lua and v0.2.x pyrate_limiter releases) to paceapi.

See Migrating to paceapi for shared defaults (no globals, Redis cutover, fail-open behavior).

API mapping

fastapi-limiter paceapi
await FastAPILimiter.init(redis) (v0.1.x) limiter = Limiter(RedisStore(client)) (no startup hook)
Limiter(Rate(2, Duration.SECOND * 5)) (v0.2.x pyrate_limiter) Limiter() + Rate(2, 5 * SECOND) or "2/5 seconds"
Depends(RateLimiter(times=2, seconds=5)) (v0.1.x) Depends(limiter.limit(Rate(2, 5 * SECOND)))
Depends(RateLimiter(limiter=limiter)) (v0.2.x) Depends(limiter.limit("2/5 seconds"))
identifier= callable key= (supports full FastAPI dependency injection; see Limiting by user)
callback= on exceed Exception handler on RateLimitExceeded (Headers and errors)
WebSocketRateLimiter Depends(limiter.limit(...)) for handshakes + Depends(limiter.meter(...)) for per-message limits (WebSockets)

Migrated app example

Limiter setup:

# No global `FastAPILimiter.init(redis)` needed; pass `RedisStore(client)` in production.
limiter = Limiter()

Dependency-based caller key (replacing identifier=):

async def current_user(authorization: Annotated[str | None, Header()] = None) -> str:
    if not authorization or not authorization.startswith("Bearer "):
        raise HTTPException(401, "Missing bearer token")
    return authorization.removeprefix("Bearer ")


async def user_key(user: Annotated[str, Depends(current_user)]) -> str:
    return f"user:{user}"

Custom 429 response (replacing callback=):

# Replaces fastapi-limiter's `callback=` with a standard FastAPI exception handler.
@app.exception_handler(RateLimitExceeded)
async def rate_limited(_: Request, exc: RateLimitExceeded) -> JSONResponse:
    headers = dict(exc.headers or {})
    return JSONResponse(
        {"detail": "Too many requests", "retry_after": int(headers["Retry-After"])},
        status_code=exc.status_code,
        headers=headers,
    )

Limited routes:

# Replaces `Depends(RateLimiter(times=2, seconds=5))` or `pyrate_limiter` `Rate(2, 5s)`.
@app.get("/ping", dependencies=[Depends(limiter.limit(Rate(2, 5 * SECOND)))])
async def ping() -> dict[str, str]:
    return {"msg": "pong"}

# Replaces `identifier=` with a FastAPI dependency key; 401s are never counted.
@app.get("/me", dependencies=[Depends(limiter.limit("3/minute", key=user_key))])
async def me(user: Annotated[str, Depends(current_user)]) -> dict[str, str]:
    return {"user": user}

Full example: examples/from_fastapi_limiter.py.

Behavioral differences

  • Auth runs before counting: Because key= is resolved as a FastAPI dependency, unauthenticated requests fail with 401 before consuming quota or touching Redis.
  • Standard headers enabled by default: Allowed responses include X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset (429 includes Retry-After). A request let through by a failed store carries none. An endpoint that returns a Response directly needs RateLimitMiddleware for them (details).
  • Trusted proxy & IPv6 safety: Unlike naive X-Forwarded-For header reads, ClientIP only trusts X-Forwarded-For from explicitly listed trusted_proxies and groups IPv6 clients by /64 (Keys).
  • Built-in resilience: store_timeout, circuit-breaker store_cooldown, and fallback=MemoryStore() protect your API during Redis outages (Failure modes).
  • WebSocket support without manual bucket wiring: Connection handshakes and message loops use the same Limiter and Meter APIs.