Migrating from limits¶
Guide for migrating Starlette/FastAPI rate limits from direct limits (v5.x, sync limits or async limits.aio) usage to paceapi.
If you used limits through slowapi, start with From slowapi. If you use limits outside Starlette/FastAPI (sync code, Flask/Django) or with a backend paceapi has no store for, such as Etcd, stay on limits.
See Migrating to paceapi for shared defaults (no globals, Redis cutover, fail-open behavior).
API mapping¶
limits |
paceapi |
|---|---|
MemoryStorage() / limits.aio.storage.MemoryStorage() |
Limiter() (default MemoryStore) |
storage_from_string("async+redis://...") / RedisStorage(...) |
Limiter(RedisStore(client)) with your own redis.asyncio client (Stores) |
FixedWindowRateLimiter(storage) |
Limiter(algorithm=FixedWindow()) (clock-aligned; see below) |
SlidingWindowCounterRateLimiter(storage) |
Limiter() (SlidingWindow is the default) |
MovingWindowRateLimiter(storage) |
Not built in (see Not supported); use SlidingWindow or implement Algorithm |
parse("5/minute") / RateLimitItemPerMinute(5) |
"5/minute" or Rate(5, MINUTE) |
parse_many("2/second;4/minute") + loop |
Pass multiple rates to one call: limiter.hit(key, "2/second", "4/minute") or limiter.limit("2/second", "4/minute") (atomic all-or-nothing) |
await strategy.hit(limit, *identifiers, cost=n) |
decision = await limiter.hit(key, rate, cost=n, scope=...) (decision.allowed is the boolean) |
await strategy.get_window_stats(limit, *identifiers) |
Returned on the same Decision (remaining, reset_after, retry_after); no second round trip |
await strategy.test(limit, *identifiers, cost=n) |
decision = await limiter.hit(key, rate, cost=0, scope=...) and check decision.remaining >= n |
Custom FastAPI Depends calling hit() + get_window_stats() + raising HTTPException(429) |
Depends(limiter.limit(...)) (route scoping, headers, and 429 built in) |
| Custom Starlette/ASGI middleware | RateLimitMiddleware |
key_prefix= on storage |
Limiter(..., prefix=...) |
await strategy.clear(limit, *identifiers) |
Not supported (buckets expire by TTL; in tests, create a fresh Limiter() or advance FrozenClock) |
Migrated app example¶
Limiter setup (replacing storage URIs and strategy classes):
# Default is MemoryStore + SlidingWindow. Pass `RedisStore(client)` with your own
# `redis.asyncio` client in production, or `algorithm=FixedWindow()` for fixed windows.
limiter = Limiter()
Atomic multi-rate FastAPI route limit (replacing a custom dependency built on parse_many, hit, and get_window_stats):
# Replaces a hand-rolled dependency looping over `parse_many("2/second;4/minute")`,
# calling `hit()` + `get_window_stats()`, and raising 429 with manual headers.
@app.get("/search", dependencies=[Depends(limiter.limit("2/second", "4/minute"))])
async def search(q: str = "") -> dict[str, str]:
return {"q": q}
Direct limiter.hit() with variable cost (returning allowed and remaining in one round trip):
# Replaces `await strategy.hit(limit, "export", user, cost=items)` followed by
# `await strategy.get_window_stats(...)`: one call returns the full Decision.
@app.post("/exports/{user}")
async def export_data(user: str, items: Annotated[int, Query(ge=0)] = 1) -> dict[str, int]:
decision = await limiter.hit(f"user:{user}", "10/minute", cost=items, scope="export")
if not decision.allowed:
raise RateLimitExceeded(decision)
return {"exported": items, "remaining": decision.remaining}
Peeking remaining quota without consuming it (replacing test() + get_window_stats()):
# Replaces `test()` + `get_window_stats()`: `cost=0` inspects quota without consuming it.
@app.get("/exports/{user}/quota")
async def export_quota(user: str) -> dict[str, int]:
decision = await limiter.hit(f"user:{user}", "10/minute", cost=0, scope="export")
return {"remaining": decision.remaining, "reset_after": math.ceil(decision.reset_after)}
Full example: examples/from_limits.py.
Behavioral differences¶
- Single round trip for check and headers:
limits'shit()returns a barebool, so populating headers or reporting remaining quota requires a secondget_window_stats()call.paceapireturns the fullDecision(allowed,remaining,reset_after,retry_after) from the same atomic step. - Atomic all-or-nothing multi-rate checks: Passing several rates to one
limiter.hit()orlimiter.limit()evaluates and updates every bucket in a single Redis Lua script (co-located in one Redis Cluster slot via hash tags). If any rate rejects the request, none of the buckets are incremented. Looping overparse_many(...)inlimitsevaluates each rule separately. - Clock-aligned fixed windows, not first-request:
limits'sFixedWindowRateLimiterstarts a window when a key's first request arrives.paceapi'sFixedWindowis clock-aligned to multiples of the period (Algorithms). If you need windows that start on each caller's first request, see the per-caller window custom algorithm example. - Peeking with
cost=0vs.test():limiter.hit(..., cost=0)inspects remaining quota without consuming it, anddecision.allowedisTruewhenever the bucket is not in debt (even whendecision.remaining == 0). Checkdecision.remaining >= costrather thandecision.allowedwhen portingtest(..., cost=cost). - Relative durations instead of Unix timestamps:
Decision.reset_afterandDecision.retry_afterare relative seconds (float), not Unix epoch timestamps likeWindowStats.reset_time. - Caller-owned
redis.asyncioclient and server clock:RedisStorewraps your ownredis.asyncioclient (redis>=8.0.0) rather than creating clients from URIs or defaulting tocoredis, and uses RedisTIMErather than client wall-clock time. - Fail-open default with circuit breaker: Store errors default to
on_store_error="allow"withstore_timeoutandstore_cooldown(Failure modes) instead of raising storage errors directly. Passon_store_error="raise"to matchlimits's default. - Rate units: Supported units are seconds, minutes, hours, and days (express months and years in days).
Not supported¶
MovingWindowRateLimiter(exact per-request timestamp log;paceapi's built-in algorithms are all O(1) memory per key).- Synchronous API (
paceapiisasyncio-only). clear()for resetting individual buckets mid-window, andstorage.check()health pings.- Etcd backend (built-in stores are memory, Redis/Valkey, MongoDB, and Memcached; implement
LimiterStorefor custom backends).