Skip to content

LLM token budget

LLM completions consume a variable number of tokens known only after generation. Use limiter.meter() with a TokenBucket to check remaining budget on entry and charge actual token usage afterwards.

Keying and setup

Authenticate callers before metering so unauthenticated headers cannot mint fresh budgets:

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}"

Use TokenBucket so overages create debt repaid at the refill rate (window algorithms discard debt at window boundaries):

limiter = Limiter(algorithm=TokenBucket())

Standard endpoint

# `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

Streaming responses

Charge tokens in a finally: block so clients who disconnect mid-stream are still billed for tokens already generated:

@app.post("/chat/stream")
async def chat_stream(
    prompt: Prompt, meter: Annotated[Meter, Depends(budget)]
) -> StreamingResponse:
    async def reply() -> AsyncIterator[str]:
        used = 0
        try:
            async for piece, tokens in stream_from_the_model(prompt.prompt):
                used += tokens
                yield piece
        finally:
            # Whether the reply ended or the caller hung up, what was sent
            # is charged. A caller who hangs up cancels this task, and a
            # charge is counted all the same.
            await meter.charge(used)

    return StreamingResponse(reply(), media_type="text/plain")

meter.charge() is shielded from task cancellation, so a client disconnect that cancels the streaming generator does not stop the charge. It is still one store call: if the store fails or exceeds store_timeout, the charge may or may not have been counted (a call that timed out can still reach the store), and on_store_error decides the request's outcome.

Production considerations

  • One budget across routes: scope="tokens" makes /chat and /chat/stream draw on the same bucket. Without scope=, a meter keeps a separate budget per route.
  • Soft ceiling under concurrency: Because actual cost is charged post-execution, the final request (or concurrent in-flight requests) can push a caller temporarily negative. Pair the token meter with a standard request-rate limit or concurrency limit to bound simultaneous overages.
  • Response headers reflect entry balance: X-RateLimit-Remaining reports tokens available before the current request's charge().
  • Charge on partial work: Requests that error before calling meter.charge() consume nothing—charge in finally: whenever upstream compute was already spent.

Full source: examples/token_budget.py.