Meters, failure counting, and WebSockets¶
Standard limits charge 1 unit before the endpoint runs. Three APIs handle cases where that model doesn't fit: post-execution meters, failure-only limits, and WebSocket message limits.
Post-execution meters¶
limiter.meter(...) accepts the same rates, key, and scope arguments as limit(), and injects a Meter. On entry it performs a zero-cost check (returning 429 if the caller is already exhausted), and your handler charges the actual cost once known:
# `scope=` makes both routes draw on one budget per customer; without it, each
# route keeps its own bucket.
budget = limiter.meter("1000/day", key=customer_key, scope="tokens")
@app.post("/chat")
async def chat(prompt: Prompt, meter: Annotated[Meter, Depends(budget)]) -> Reply:
# A caller with anything left of the day's budget gets this far.
reply = await ask_the_model(prompt.prompt)
# What the reply cost is known only now, and is counted whatever is left.
await meter.charge(reply.tokens)
return reply
await meter.charge(n)recordsnunits unconditionally (forced charge), allowing callers to go slightly into debt on their final or concurrent requests.await meter.hit(n)recordsnunits only if they fit, returning aDecision.- Response headers reflect the balance checked on entry.
- Requests that fail before calling
charge()consume nothing.
Use TokenBucket for post-execution budgets so debt is repaid at the refill rate rather than reset at the next window boundary:
Key budgets on verified identities—never on unvalidated headers:
async def customer_key(x_api_key: Annotated[str | None, Header()] = None) -> str:
# The budget belongs to a customer you have checked, not to whatever a header says.
customer = CUSTOMERS.get(x_api_key or "")
if customer is None:
raise HTTPException(401, "Unknown API key")
return f"customer:{customer}"
With on_missing_key="skip", a caller whose key returns None gets a meter that counts nothing:
async def metered(customer: Annotated[Customer, Depends(current_customer)]) -> str | None:
# Customers on the unlimited plan have no budget: returning None exempts them.
return None if customer.plan == "unlimited" else f"customer:{customer.name}"
budget = limiter.meter("1000/day", key=metered, scope="tokens", on_missing_key="skip")
@app.post("/chat")
async def chat(prompt: str, meter: Annotated[Meter, Depends(budget)]) -> Reply:
reply = await ask_the_model(prompt)
await meter.charge(reply.tokens) # counts nothing where the key returned None
return reply
Outside HTTP handlers, instantiate a meter directly: Meter(limiter, "user:42", "100000/day", scope="batch").
For example, in a nightly job:
async def summarize_overnight(user_id: int, documents: list[str]) -> list[str]:
# A job has no request to resolve a meter from, so it makes one. The scope
# keeps this budget apart from what the same user spends anywhere else.
meter = Meter(limiter, f"user:{user_id}", "1000/day", scope="batch")
summaries: list[str] = []
for document in documents:
if not (await meter.hit(0)).allowed:
break # nothing is left of today's budget
reply = await ask_the_model(document)
await meter.charge(reply.tokens)
summaries.append(reply.text)
return summaries
For streaming responses and client-disconnect handling, see the LLM token budget recipe.
Counting only failures¶
Pass count="failures" to check the limit on entry (cost 0) and charge only when the request fails:
# Every attempt from an address counts against this one, whatever comes of it.
attempts = limiter.limit("20/minute")
# Five wrong passwords for one account from one address in fifteen
# minutes, and that address has to wait before it tries that account
# again. A login that works counts for nothing.
wrong_for_an_account = limiter.limit(
"5/15 minutes", count="failures", failures={401}, key=combine(account, client_ip)
)
# Thirty wrong passwords from one address in an hour, whichever accounts
# they were for, and that address has to wait.
wrong_from_an_address = limiter.limit("30/hour", count="failures", failures={401})
@app.post(
"/login",
dependencies=[
Depends(attempts),
Depends(wrong_for_an_account),
Depends(wrong_from_an_address),
],
)
async def login(credentials: Credentials) -> dict[str, str]:
name = folded(credentials.username)
if PASSWORDS.get(name) != credentials.password:
raise HTTPException(status_code=401, detail="Wrong username or password.")
return {"signed in as": name}
Because failures are only charged after execution, concurrent requests are all admitted before any failure is recorded. Pair a failure limit with a normal request-rate limit (with a distinct rate or scope) to cap concurrency bursts.
Failure classification:
- Default: HTTP status ≥ 400 except
429. failures={401, 403}: restricts counting to specific status codes (recommended for app-wide limits so404s aren't counted). App-wide failure limits also needscope=; otherwise each route keeps its own failure count.- Unhandled exceptions count as
500. - Cancelled requests and client disconnects are not counted.
FastAPI dependency visibility¶
FastAPI dependencies only observe exceptions propagating through them, not returned response objects:
- Raise
HTTPException(401)rather than returningJSONResponse(status_code=401). - Place the failure limit before any dependencies whose exceptions it should count.
- Non-HTTP exceptions count as
500even if a custom exception handler converts them to another status. If your app raises its own exception types, charge a meter in the endpoint instead (see Login throttling). - On FastAPI 0.118+, validation errors (
422) and post-response errors (streaming/background task exceptions as500) also propagate through dependencies—specify explicitfailures={...}to exclude them. - On WebSockets, unhandled exceptions count as
500; normal disconnects count as nothing.
Starlette's RateLimitMiddleware and @limited inspect the actual HTTP response status directly and count both raised and returned error responses.
For full trade-offs on key selection and credential-stuffing protection, see the Login throttle recipe.
WebSockets¶
Attach limiter.limit(...) to a WebSocket route to limit connections at handshake time, and inject limiter.meter(...) to limit messages with await meter.hit() inside the receive loop:
connections = limiter.limit("10/minute")
messages = limiter.meter("3/minute", scope="chat messages")
@app.websocket("/chat", dependencies=[Depends(connections)])
async def chat(websocket: WebSocket, meter: Annotated[Meter, Depends(messages)]) -> None:
await websocket.accept()
async for text in websocket.iter_text():
decision = await meter.hit()
if decision.allowed:
await websocket.send_text(text.upper())
else:
wait = math.ceil(decision.retry_after)
await websocket.send_text(f"Slow down: try again in {wait} seconds.")
When decision.allowed is False, send a warning, drop the message, or close the socket (e.g., code 1008). Give the meter a distinct scope if it uses the same rate as the connection limit so they do not share a bucket.
See the WebSocket limits recipe for connection/key caveats.