alata.
Digging Deeper

Rate Limiting

Throttle HTTP routes and domain actions with a cache-backed rate limiter.

Alata includes a rate limiter for throttling HTTP routes and for limiting any other action — OTP sends, login attempts, report generation. Counters live on your cache store, so there is no separate backend to run.

routes/api.py
from alata.http import APIRouter, Depends, throttle

router = APIRouter()

@router.get("/search", dependencies=[Depends(throttle("60/minute"))])
async def search():
    ...

Each caller gets 60 requests per minute on /search. The 61st receives a 429 with a Retry-After header.

Throttling routes

Rate strings

A rate string is <attempts>/<unit>, where the unit is second, minute, hour, or day:

throttle("10/second")
throttle("60/minute")
throttle("1000/hour")
throttle("10000/day")

Rate strings are parsed while the route is being declared, so a typo fails at startup rather than on the first request. The attempt count must be positive — to exempt a route pass Limit.none(), and to close one entirely pass Limit(0, 60).

Applying to a router

throttle() is a regular dependency, so it can guard a single route or every route on a router:

routes/api.py
router = APIRouter(prefix="/api", dependencies=[Depends(throttle("1000/hour"))])

Buckets are always per route: /api/search and /api/orders each get their own 1000/hour. Sub-apps mounted at different prefixes are counted separately too, even when they declare the same path.

Response headers

Successful responses report the state of the bucket, and rejected ones say when to come back:

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Retry-After: 48
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 48

A rejection raises ThrottledError, which the exception handler renders as a 429 — handle it there to customize the response body. Retry-After and X-RateLimit-Reset always agree, and are never zero.

Endpoints that build and return their own Response objects get the success headers through RateLimitHeadersMiddleware, which the scaffold registers by default. Without it, headers appear only on responses the framework assembles for you.

Customizing the key

"60 per minute" means 60 per minute per caller. By default the caller is the user id from the request context when one is set, and the client IP otherwise. The scaffold's IdentityMiddleware reads caller-supplied identity headers. Replace it with verified authentication before using identity-based limits; otherwise callers can change the header to obtain a new bucket.

Publish real identities only (a per-session guest id counts as real). A middleware that sets user_id_context to a fallback constant like "anonymous" puts every unauthenticated caller in one shared bucket, letting a single client exhaust the limit for everyone. Leave the context unset for unknown callers — they fall back to per-IP buckets.

Pass key= to take over how callers are identified — a callable receiving the request and returning a string:

app/http/throttling.py
from alata.http import Request


def client_ip(request: Request) -> str:
    return f"ip:{request.client.host}" if request.client else "ip:unknown"
@router.post("/login", dependencies=[Depends(throttle("5/minute", key=client_ip))])
async def login():
    ...

Login, registration, and password-reset routes can use the client address. Behind a proxy, configure the ASGI server to accept forwarded addresses only from trusted proxies. For an API key, derive the bucket from the credential your authentication dependency has already verified:

def api_key(request: Request) -> str:
    return f"key:{request.state.api_key_id}"


@router.get("/v1/events", dependencies=[Depends(throttle("1000/hour", key=api_key))])
async def events():
    ...

A server on a unix socket behind a reverse proxy reports no client address, so IP-keyed buckets collapse into one shared bucket (the limiter logs a warning once). Use a verified identity key or configure trusted proxy address handling.

Limit objects

Rate strings cover the common cases; Limit objects express the rest:

from alata.rate_limiting import Limit

Limit.per_second(10)
Limit.per_minute(60)
Limit.per_minutes(5, 10)            # 10 attempts per 5 minutes
Limit.per_hour(1000)
Limit.per_day(10000)
Limit.per_minute(60).by(tenant_id)  # scope the bucket to a discriminator
Limit.none()                        # exempt — never counted, no headers set
Limit(0, 60)                        # closed — every request rejected, Retry-After: 60

Limits are frozen values — build them once and share them. A closed limit never touches the store and reports its own window length as Retry-After.

.by() replaces the caller key for that limit — the key= callable and the default keying are not consulted. Use key= to change identification for every limit on the route, and .by() when one limit needs a different scope.

Named limiters

A named limiter maps a name to a resolver that runs on every request, so the rule can depend on who is asking — plan tiers, internal exemptions, per-tenant quotas. Register them in a provider's boot():

app/providers/app_provider.py
from alata.rate_limiting import Limit
from alata.support.service_provider import ServiceProvider


class AppProvider(ServiceProvider):
    def boot(self):
        limiter = self.app.make("limiter")
        limiter.register("api", api_quota)


def api_quota(request):
    plan = plan_for(request)          # your lookup
    if plan == "enterprise":
        return Limit.none()
    if plan == "pro":
        return Limit.per_minute(600)
    return Limit.per_minute(60)

Reference the name anywhere a rate string would go:

@router.get("/v1/search", dependencies=[Depends(throttle("api"))])
async def search():
    ...

A resolver may return a Limit, a list of them, or a rate string. The resolver picks the rule; the caller key still comes from the default (or key=), so each caller counts against their own bucket at their own ceiling.

Names are validated at startup: a throttle() referencing a name no provider registered fails boot with every unknown name listed.

Multiple limits

Pass a list to enforce several shapes at once. Each limit gets its own bucket; they are checked in order and the first rejection wins:

throttle([Limit.per_second(5), Limit.per_minute(100)])

Combine a per-caller limit with a shared global cap by pinning the global one with .by():

throttle([
    Limit.per_minute(10),                # per caller
    Limit.per_minute(500).by("global"),  # everyone shares one bucket
])

List the per-caller limit first, so a caller already over their own quota never spends the shared budget. On success the headers describe the last limit in the list.

Manual rate limiting

The limiter is a container singleton with nothing HTTP about it. Every method has a sync form and an a-prefixed async twin — Async and Sync covers which one belongs where:

app/services/otp.py
from alata.container import container
from alata.exceptions import UnprocessableError


async def send_otp(user_id: int) -> None:
    limiter = container.make("limiter")
    key = f"otp:{user_id}"
    if not await limiter.aattempt(key, max_attempts=3, decay_seconds=300):
        wait = await limiter.aavailable_in(key)
        raise UnprocessableError(f"Too many codes requested. Try again in {wait} seconds.")

    await deliver_otp(user_id)

Clear the bucket on success so a caller who gets it right is not left locked out:

app/services/auth.py
from alata.container import container
from alata.exceptions import AuthenticationError, UnprocessableError


async def authenticate(email: str, password: str):
    limiter = container.make("limiter")
    key = f"login:{email}"
    if await limiter.atoo_many_attempts(key, max_attempts=5):
        raise UnprocessableError("Too many failed attempts.")

    user = await attempt_login(email, password)
    if user is None:
        await limiter.ahit(key, decay_seconds=900)
        raise AuthenticationError("Invalid credentials.")

    await limiter.aclear(key)
    return user
MethodPurpose
attempt(key, max_attempts, decay_seconds)Consume one attempt if available; True when allowed
hit(key, decay_seconds)Increment unconditionally; returns the new count
too_many_attempts(key, max_attempts)Has the key exhausted its attempts?
attempts(key)Current count in the window
remaining(key, max_attempts)Attempts left
available_in(key)Seconds until the window resets
clear(key)Drop the bucket

Configuration

The limiter rides the cache: counters live on the cache's default store unless an optional config/rate_limit.py points them elsewhere:

config/rate_limit.py
RATE_LIMIT_CONFIG = {
    "store": "redis",          # a store from CACHE_CONFIG["stores"]; None = the cache default
    "prefix": "rate_limit:",   # key namespace
}

The store decides what a limit actually bounds:

StoreCounter scope
redisShared across all workers and servers
databaseShared across all workers and servers
filePer server
memoryPer worker process
nullNo counters — limiting is a no-op (logged)

On memory, "60/minute" means 60 per minute per worker — four workers admit 240. Use redis or database whenever more than one worker serves traffic.

Testing

RateLimiter.fake() is an in-memory limiter that needs no backend. Bind it and your routes are throttled by a store you control:

from alata.container import container
from alata.rate_limiting import RateLimiter


def test_search_is_throttled(fresh_container):
    container.instance("limiter", RateLimiter.fake())

    assert client.get("/search").status_code == 200

The fake store's clock is a plain attribute — step it forward instead of sleeping through a window:

def test_window_reopens(fresh_container):
    limiter = RateLimiter.fake()
    now = {"t": 1000.0}
    limiter.store.now = lambda: now["t"]
    container.instance("limiter", limiter)

    assert client.get("/limited").status_code == 200
    assert client.get("/limited").status_code == 200
    assert client.get("/limited").status_code == 429

    now["t"] += 61                      # the window has expired
    assert client.get("/limited").status_code == 200

Good to know

  • Windows are fixed, not sliding. A window opens on a key's first attempt and resets all at once, so traffic hugging a boundary can briefly reach about twice the nominal rate. If a 2× burst would hurt, halve the limit or shorten the window.
  • The limiter fails open. When the cache backend cannot count (an outage, or the null store), requests are admitted and a WARNING is logged once per process. Alert on it — while it fires, limits are not enforced.
  • A rejected attempt still counts. Admission is one atomic increment, so hammering a blocked bucket pushes the count past the limit; X-RateLimit-Remaining clamps at 0 and the window still expires on its original schedule.

On this page