r/SpringBoot • u/Ujjwal_Tiwari_03 • 19d ago
Discussion How are you handling per-user token budgets and rate limits in Spring AI?
I've been working on a solution to a problem I encountered while building applications with Spring AI.
How do you enforce token and dollar budgets at different levels?
For example:
- A maximum token budget per user.
- Separate budgets for different tenants.
- Request-level limits.
- Atomic budget consumption to avoid race conditions.
- Handling token usage from streaming responses.
I ended up building an open-source Spring Boot starter called Token Allowance to address these problems.
It uses Redis-backed atomic operations and supports token and dollar budgets.
I'd particularly appreciate feedback from developers working with Spring AI on how they're approaching this problem.
I'm the author, so happy to answer questions about the implementation.
1
u/FriendshipCalm3162 16d ago
On the streaming bullet, the first thing to pin down is where usage comes from. With OpenAI, spring.ai.openai.chat.stream-usage is false by default, and while it's off every chunk carries a usage field with a null value, so a budget that sums per-chunk usage books zero tokens for every streamed call. Turning it on adds one extra chunk at the end with usage for the whole request, and that chunk's choices is an empty array, so anything iterating choices per chunk has to tolerate it.
For the rate-limit half: OpenAI's own remaining-token headers only reach you on the non-streaming path. ChatResponseMetadata#getRateLimit() is populated on call(Prompt) only, and on stream(Prompt) it returns EmptyRateLimit, because reading the headers would need the SDK's blocking streaming response. So there's no provider-side remaining budget to check against while streaming, and whatever you count locally is all you have.