Tracking per-tenant LLM token spend accurately when streaming SSE responses abort early
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?