Skip to content

Migrating from slowapi

Guide for migrating FastAPI/Starlette rate limits from slowapi (v0.1.10) to paceapi.

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

API mapping

slowapi paceapi
Limiter(key_func=get_remote_address) Limiter() (client_ip is the default key)
app.state.limiter = limiter + add_exception_handler(RateLimitExceeded, ...) Not needed—RateLimitExceeded is a Starlette HTTPException handled automatically
@limiter.limit("5/minute") + request: Request parameter dependencies=[Depends(limiter.limit("5/minute"))] (no endpoint signature changes). Left as a decorator, it fails at import with TypeError: RateLimit.__call__() takes 1 positional argument but 2 were given
key_func= key= (must use typed parameters; untyped functions and lambdas are rejected at setup time; see Keys)
default_limits=[...] + SlowAPIMiddleware Router or app-level dependencies=[Depends(...)]
SlowAPIMiddleware, SlowAPIASGIMiddleware Not needed for route dependencies
application_limits=[...] RateLimitMiddleware with rates=
@limiter.shared_limit("10/minute", scope="reports") limiter.limit("10/minute", scope="reports")
@limiter.exempt Exclude the route from the limited router
exempt_when= Key returning None with on_missing_key="skip"
cost= cost= (fixed int or FastAPI dependency; see Multiple limits, scopes, and costs)
Callable limit string Rate dependency (can depend on authenticated user)
per_method=True Default behavior (scopes include HTTP method)
headers_enabled=True + response: Response Enabled by default; disable with Limiter(header_style=None)
storage_uri="redis://..." / mongodb:// / memcached:// Limiter(RedisStore(client)), MongoStore(db), or MemcachedStore(client) with your own async client (Stores)
strategy= algorithm= (Algorithms)
swallow_errors=True on_store_error="allow" (default; see Failure modes)
in_memory_fallback_enabled=True fallback=MemoryStore()
key_prefix= prefix=
enabled=False Limiter(enabled=False) and limiter.disabled() in tests
error_message= Exception handler on RateLimitExceeded (Headers and errors)

Migrated app example

Router-level default limit:

# A limit on a router is every route's default. Each route counts by itself.
api = APIRouter(dependencies=[Depends(limiter.limit("100/minute"))])

@api.get("/items")
async def items() -> list[str]:
    return ["tea", "coffee"]

Route-specific tighter limit:

# A route's own limit applies as well as the router's. The endpoint takes
# what it needs, and no `request` unless it wants one.
@api.get("/search", dependencies=[Depends(limiter.limit("5/minute"))])
async def search(q: str = "") -> dict[str, str]:
    return {"q": q}

Shared scope across multiple routes:

# One allowance for both routes: the scope is what they share.
reports = Depends(limiter.limit("10/minute", scope="reports"))

@api.get("/reports/daily", dependencies=[reports])
async def daily() -> dict[str, str]:
    return {"report": "daily"}

@api.get("/reports/weekly", dependencies=[reports])
async def weekly() -> dict[str, str]:
    return {"report": "weekly"}

Exempt route (mounted outside the limited router):

# A route with no limit is one that is not on the router that has one.
@app.get("/health")
async def health() -> dict[str, str]:
    return {"status": "ok"}

app.include_router(api)

Full example: examples/from_slowapi.py.

Behavioral differences

Before you switch, compare the 429 body, Retry-After, and what happens when the store is down (Failure modes) with what your clients and alerts rely on today.

  • Route limits stack with router/app limits: Unlike slowapi (where route limits override defaults unless override_defaults=False), all applicable limits are enforced.
  • Default algorithm is SlidingWindow: slowapi defaults to fixed window. Pass Limiter(algorithm=FixedWindow()) for fixed-window behavior. Note that paceapi's sliding window is a constant-memory counter approximation, not a per-request timestamp log.
  • A fixed window starts on the clock, not at the first request: slowapi leaves the counting to limits, which documents its fixed window as starting when a key's first request arrives. paceapi's FixedWindow is clock-aligned: windows begin at multiples of the period, at the same moment for every key (Algorithms). A daily quota whose first request arrives at 15:00 resets at 15:00 the next day under limits; under FixedWindow it resets at 00:00 UTC, whenever the first request arrived. No built-in algorithm starts a window at a key's first request.
  • Route templates, not concrete paths: /items/1 and /items/2 share one route bucket by default.
  • Multiple rates are separate args: "5/minute;100/hour" becomes limiter.limit("5/minute", "100/hour"). Supported units are seconds, minutes, hours, and days (express months/years in days).
  • Runs before body validation: As a FastAPI dependency, a limit runs before the body is validated against the endpoint's model, so a request whose body fails validation is still counted. A body that is not parseable JSON is rejected before any dependency runs and is not counted.
  • 429 payload format: paceapi returns {"detail": "Rate limit exceeded. Try again in N seconds."} instead of {"error": ...}. Register a custom RateLimitExceeded handler if clients expect the old format.
  • Header semantics: X-RateLimit-Reset is relative seconds (not a Unix timestamp). Retry-After is only sent on 429 responses and is always integer seconds (no HTTP-date format).
  • Fail-open default: Store errors fail open (on_store_error="allow") instead of raising. Pass on_store_error="raise" to match slowapi's default.
  • IPv6 & proxy handling: IPv6 addresses are grouped by /64; X-Forwarded-For is ignored unless trusted_proxies is configured (Keys).
  • Missing keys raise MissingKeyError: Unless on_missing_key="skip" is set.
  • Fresh counters on cutover: Redis key formats differ, so counters start fresh on migration.

Not supported

  • @limiter.exempt and methods=[...] (attach limits directly to matching routes/routers).
  • .env / environment-variable auto-configuration (configure Limiter in Python).
  • retry_after="http-date".

New capabilities unlocked