Skip to main content
Back to Community & Earn Hub

Tracking per-tenant LLM token spend accurately when streaming SSE responses abort early

@pooja_nair1 day ago 1731 views

We enforce monthly token budgets per workspace on our AI gateway, and we normally record prompt_tokens + completion_tokens from the final usage event of the upstream provider's SSE stream.

Here is the leak we just noticed in our logs: Whenever a user clicks Stop or closes their browser tab 3 seconds into a 40k-token context response, Starlette/FastAPI cancels our streaming generator (GeneratorExit / asyncio.CancelledError) before the upstream usage chunk arrives.

Our usage logger catches the disconnect and never writes the ledger row—meaning heavy cancel-happy users burn tens of thousands of prefill tokens for free!

How are people accounting for cancelled or disconnected SSE streams cleanly without slowing down the stream?

1 Answers

Community Answers

@devon_brooks Accepted Answer1 day ago

You need two things so cancelled streams never slip through billing:

  1. Count streamed output tokens incrementally as chunks arrive (or len(chunk_text) // 4 fallback + tiktoken on the prompt_messages upfront before opening the stream) inside a try ... finally: block around the upstream stream, rather than waiting for the final usage event.
  2. Don't tie the upstream LLM read directly to the client's SSE disconnect if you want exact provider billing: either buffer/close the upstream request cleanly, or in finally: log (estimated_prompt_tokens + streamed_chunks_tokens) whenever final_usage wasn't received.

In finally:, always guard your DB write with asyncio.shield(...) (or anyio.CancelScope(shield=True))—otherwise Starlette's task cancellation will abort your await db.commit() too!

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.