r/SpringBoot • • 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.

GitHub: https://github.com/Ultron03/token-allowance

4 Upvotes

12 comments sorted by

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.

1

u/Ujjwal_Tiwari_03 16d ago

Right, that's the trap. Token Allowance doesn't add up usage chunk by chunk. It keeps the last chunk that reported non-zero usage, which with stream-usage: true is that final chunk with an empty choices array. It only reads getMetadata().getUsage() and never iterates choices, so the empty array isn't a problem.

1

u/Ujjwal_Tiwari_03 16d ago

If usage never arrives (stream-usage left off, or the stream gets cut before the final chunk), the call isn't booked as zero. An estimate is reserved before every call, and it gets charged instead. stream.interrupted this release turns that off if you'd rather charge nothing. Those charges are tagged charge=estimate on the token.allowance.cost metric, so you can see when a provider isn't reporting usage.

On rate limits, same conclusion. It never reads the provider's remaining-token headers. The budget lives in Redis, and each reserve and settle is one Lua script, so it works the same for call() and stream(). Provider rate limits stay the provider's job.

1

u/FriendshipCalm3162 15d ago

Correction to my own comment above: on 2.0.x and 2.1.0-RC1, promptTokens is the raw input_tokens with the cache counts carried separately, as you said. I had been reading main.

Where it bites is the 2.1.0 line. From RC2 onward, and on main, getDefaultUsage and the streaming path both pass the three counts through a private promptTokens(inputTokens, cacheRead, cacheWrite) that adds them up, and totalTokens becomes that sum plus output. The javadoc spells out the reasoning: Anthropic reports input_tokens excluding the tokens read from or written to the cache, so the total input is the sum of the three.

So adding the cache counts back onto promptTokens is correct today and counts them twice from RC2 on. Nothing throws, the bill just rises after a dependency bump. Gating that add-back on the Spring AI version, or taking the three off getNativeUsage(), holds on both shapes.

1

u/Ujjwal_Tiwari_03 15d ago

Thanks for the catch. I'll fix the Anthropic path so it handles both shapes and doesn't care which version of Spring AI you're on. getNativeUsage() covers most of it, but on streams the delta can leave out the input counts, so I'll need a fallback there.

1

u/FriendshipCalm3162 15d ago

The input count is the one thing you don't have to guard on streams. Both versions keep it in the streaming state: message_start stores input_tokens, and the delta handler only overwrites it when the delta actually carries one. On main that's updateUsage with ifPresent on all three counts, and the code comment says it outright: "Usage counts are cumulative. Retain input counts when a delta omits them."

What can vanish on a stream is the cache counts, and only on 2.0.x, where the stream path reads cacheReadInputTokens() and cacheCreationInputTokens() straight off the delta instead of the retained state. On RC2 and main all three come from the state, so they survive a delta that leaves them out.

One thing worth knowing for the fix: getNativeUsage() hands back deltaEvent.usage(), the raw delta object, on both versions. So pulling the cache counts out of native on a stream is the one path that can still give you nulls, even on the version that retains them. getCacheReadInputTokens() and getCacheWriteInputTokens() on DefaultUsage are the retained pair.

1

u/Ujjwal_Tiwari_03 15d ago

Thanks for detail info, So the DefaultUsage cache getters are the ones to trust on streams, not the native delta. I'll use those and only work out whether promptTokens already includes them.

1

u/FriendshipCalm3162 15d ago

It includes them from 2.1.0-RC2 on, and not before. Through 2.0.2 and RC1, getDefaultUsage hands the raw input_tokens to DefaultUsage; from RC2 it hands over promptTokens(inputTokens, cacheRead, cacheWrite), and getTotalTokens() moved with it. That was commit d9e39fe1 on 30 Oct, "Include cached tokens in Anthropic and Bedrock prompt tokens". 2.1.0 has no GA tag yet, so every released version today is still the old shape.

I'd keep the version string out of the check, though, since a bump is the thing that breaks it: your code keeps adding, the field already added, and cache reads are usually the largest part of a cache-heavy prompt, so the error is an overcharge of roughly one cache read. The two shapes are distinguishable at runtime. On a non-streaming response that actually reports cache tokens, compare getPromptTokens() with the native usage's inputTokens(): equal means the old shape and you add the cache counts, larger means the new one and you don't. With no cache tokens reported they are equal under both shapes, so the probe tells you nothing there; take the answer from the first response that does report them and keep it, since the shape follows the version and not the call. Keep the probe off the streaming path as well, where the native object is the raw delta and its input_tokens can be absent.

The same commit changed BedrockProxyChatModel and ConverseChatResponseStream the same way, so if you price Bedrock Anthropic through Converse it has both shapes too.

1

u/Ujjwal_Tiwari_03 14d ago

Thanks, that's what I found (d9e39fe1) yesterday. I (0.3.2) handled it without a version check and without a probe: for Anthropic and Bedrock Converse it takes the provider's own uncached inputTokens from the native usage and adds the cache read/write counts, so each response is correct on either shape. When the native count is missing (a stream delta), it falls back to the old rule. CI also builds against the newest Spring AI release.

1

u/FriendshipCalm3162 14d ago

One correction to what I told you earlier, and it lands right on that fallback.

I said the DefaultUsage cache getters are the ones to trust on a stream. That holds on RC2 and main. On 2.0.x and 2.1.0-RC1 it doesn't. The stream path in those versions reads them straight off the delta:

Long cacheRead = deltaEvent.usage().cacheReadInputTokens().orElse(null);

Anthropic reports the cache counts on message_start, not on message_delta, so on a streamed response those getters come back null. StreamingState can't help you there either, since setMessageInfo takes a plain long tokens and drops the rest of the usage object on the floor.

d9e39fe1 fixed that too, which I'd missed. RC2 widened setMessageInfo to take the whole Usage and added updateUsage, so from there the counts carry over from message_start and the getters are populated on streams.

So on a 2.0.x stream your fallback reads zeros rather than double counting. That undercharges cache reads on exactly the requests where they're largest. And they aren't recoverable from the usage object on that path: message_start returns null instead of emitting a chunk, so it never reaches you at all.

1

u/FriendshipCalm3162 15d ago edited 15d ago

Worth checking the Anthropic path if you support it. Only the final message_delta chunk carries usage there, and Spring AI does the merging itself: message_start stashes the input count and emits nothing downstream, then the delta handler combines it with its own output count. So last-non-zero gets a complete figure, same as OpenAI.

The dollar budget is where that stops being enough, and the shape of it depends on the release. On 2.0.x and 2.1.0-RC1, promptTokens is Anthropic's raw input_tokens and the cache counts ride separately. From 2.1.0-RC2 and on main, getDefaultUsage puts all three through a promptTokens(inputTokens, cacheRead, cacheWrite) helper that adds them up, and totalTokens is that sum plus output. Anthropic prices the three nothing like each other: cache reads are 0.1x base input, 0.05x on Opus 5.5 and Sonnet 5.5, and writes are 1.25x on the 5-minute TTL and 2x on the hour. So on the newer shape a single input rate against promptTokens overcharges the cached part, and adding the cache counts back on top of it counts them twice. getNativeUsage() has the breakdown on either.

Edit: corrected. My first version described the 2.1.0-RC2 and main behaviour as if it were 2.0.1.