Limiting by user¶
An address is a rough guide to who is calling. An office shares one, and a phone changes its own between two requests. When callers sign in, count them by account.
A key that uses your authentication¶
A key is resolved the way FastAPI resolves any dependency, so it can ask for the same things your endpoints ask for:
async def current_user(authorization: Annotated[str | None, Header()] = None) -> User:
# A stand-in for your real authentication: a token of the form "Bearer user-<id>".
token = (authorization or "").removeprefix("Bearer user-")
if not token.isdigit():
raise HTTPException(401, "Not signed in")
return User(int(token))
async def user_key(user: Annotated[User, Depends(current_user)]) -> str:
return f"user:{user.id}"
@app.get("/me/reports", dependencies=[Depends(limiter.limit("3/minute", key=user_key))])
async def reports(user: Annotated[User, Depends(current_user)]) -> dict[str, int]:
return {"user": user.id}
- Authentication runs once. The key and the endpoint both depend on
current_user, and FastAPI resolves a dependency once per request. There is no second database lookup. FastAPI treatsSecurity(current_user, scopes=...)as a different dependency fromDepends(current_user), so if your endpoints ask for the user that way, have the key ask the same way. - A request that is not signed in counts for nothing.
current_useranswers 401 before the limiter is asked, so a stranger cannot use up anyone's allowance or fill the store with keys. - Give keys a prefix, such as
user:. It keeps a user's key from ever matching a key of another kind.
The whole app is in examples/per_user.py.
Different rates for different plans¶
The rate can be a dependency too:
async def customer(x_api_key: Annotated[str | None, Header()] = None) -> Customer:
found = CUSTOMERS.get(x_api_key or "")
if found is None:
raise HTTPException(401, "Unknown API key")
return found
async def customer_key(who: Annotated[Customer, Depends(customer)]) -> str:
return f"customer:{who.id}"
async def plan_rate(who: Annotated[Customer, Depends(customer)]) -> Rate:
return Rate(20, MINUTE) if who.plan == "pro" else Rate(2, MINUTE)
@app.get("/v1/data", dependencies=[Depends(limiter.limit(plan_rate, key=customer_key))])
async def data(who: Annotated[Customer, Depends(customer)]) -> dict[str, str]:
return {"customer": who.id}
A rate dependency returns one rate, or a list of them when several apply. It is
passed to limit() on its own, in place of the rates.
A caller who moves to another plan starts a fresh count under the new rate.
The whole app is in examples/plan_tiers.py.
Signed-in callers and everyone else¶
Some routes serve both. first_of tries several keys
in order and uses the first that has an answer:
async def optional_user(
authorization: Annotated[str | None, Header()] = None,
) -> User | None:
# A stand-in for your real authentication. It returns None for a caller who is
# not signed in, where a route that requires sign-in would answer 401.
token = (authorization or "").removeprefix("Bearer user-")
return User(int(token)) if token.isdigit() else None
async def user_key(user: Annotated[User | None, Depends(optional_user)]) -> str | None:
return None if user is None else f"user:{user.id}"
# A signed-in caller is counted as that user; anyone else by their address.
caller = first_of(user_key, client_ip)
async def caller_rate(user: Annotated[User | None, Depends(optional_user)]) -> str:
return "2/minute" if user is None else "10/minute"
@app.get("/feed", dependencies=[Depends(limiter.limit(caller_rate, key=caller))])
async def feed() -> dict[str, list[str]]:
return {"items": []}
Every key in first_of is resolved on every request. Give it an authentication
dependency that returns None for a caller who is not signed in, as
optional_user does. One that answers 401 would turn anonymous callers away
before the fallback is tried.
The whole app is in
examples/anonymous_or_user.py.
Counting combinations¶
combine keeps a separate count for each combination
of several keys. combine(user_key, client_ip) allows each user so much from
each address.
A combined key is narrower than either of its parts, so it never replaces a limit on one of them. An address that tries a thousand accounts uses a thousand different combinations, and only a limit on the address alone would notice. Attach both.