One budget gateway for Spring AI 2.1 and LangChain4j 1.24: estimate, reserve atomically, reconcile from usage. The same 1,000 HTTP requests can cost $1.13 or $162.
I put a rate limit in front of an agent and felt done. One thousand user turns a day. The limiter graphs stayed calm. The invoice did not. A user turn is an HTTP request. The agent behind it is a loop. Spring AI's ToolCallingAdvisor calls the model, runs the tool, calls the model again, and the next prompt is longer because the history came along. The rate limit counted the turn. The provider counted every hop. So the gateway I want is not another counter of requests. It has three jobs, and they are not the same job. Estimate a hold before the call. Reserve that hold atomically. Reconcile it when the provider tells you what actually happened. Versions in this piece, checked against the source at those tags on November 30, 2026: Component Version Spring Boot 4.2.0 Spring AI 2.1.0 (GA November 19) LangChain4j 1.24.1 (November 26) Java 25 (for ScopedValue ) <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-bom</artifactId> <version>2.1.0</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-bom</artifactId> <version>1.24.1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> You only need one of the two. The gateway, the SQL, and the tests are the same; only the hook into the model call changes. Interactive cost simulation Controlling HTTP request volume is the wrong instrument for an agent. The calculator prices one day from the hop count, the growing prompt, and a price card. The cards are round numbers I budget with, not a vendor quote. Shape Model calls Input Output Day Chat, small, 1 hop 1,000 2.0M 0.5M $1.13 Agent, mid, 6 hops 6,000 39M 3.0M $162.00 Same agent, frontier 6,000 39M 3.0M $810.00 Input tokens for a turn with S hops: S * 2000 + 1800 * S * (S - 1) / 2 . At one hop the extra term is zero. At six hops it is 27,000, so the turn is 39,000 input tokens and 3,000 output tokens. The mid-price agent is twelve times the one-hop call on that same mid card ($13.50), and about 144 times the cheap chat. A $25 day budget fits all 1,000 cheap turns. It fits about 154 of the mid-price agent turns. It fits about 30 of the frontier ones. A request cap counts arrivals. The invoice counts tokens. Three moments Estimate is a guess you can make from the prompt in your hand. Reserve is the only moment that has to be correct under concurrency. Reconcile is where the guess gets replaced by Usage . The application hits a Spring AI ChatClient advisor. The advisor asks the gateway to estimate and reserve. If the hold fits, the model is called and the actual usage is settled into the ledger. If the hold does not fit, the model call is canceled and the ledger records the deny. OpenTelemetry sees both branches. If you collapse the three moments into "check the balance, then call the model," two turns will both see $0.50 left, both spend $0.40, and the account goes negative. I have done that. The database never got a vote. Inside the tool loop Spring AI 2.x runs the tool loop as an advisor. ToolCallingAdvisor calls chain.copy(this).nextCall(...) on every hop. Advisors ordered after it see each model call. Advisors ordered before it see the user turn once. MessageChatMemoryAdvisor uses Advisor.DEFAULT_CHAT_MEMORY_PRECEDENCE_ORDER , which is Ordered.HIGHEST_PRECEDENCE + 200 . It sits outside the loop. ToolCallingAdvisor.DEFAULT_ORDER is +300 . The budget advisor belongs after that, closer to the model. I use ToolCallingAdvisor.DEFAULT_ORDER + 100 . ToolCallingManager toolCallingManager = DefaultToolCallingManager.builder() .maxTotalToolCalls(12) .maxCallsPerTool(4) .onLimitExceeded(ToolCallLimitBehavior.THROW) .build(); ChatClient client = ChatClient.builder(chatModel) .defaultAdvisors( MessageChatMemoryAdvisor.builder(chatMemory).build(), ToolCallingAdvisor.builder().toolCallingManager(toolCallingManager).build(), budgetAdvisor) .build(); Now the mistake I nearly put in this article. Since 2.0.0, ToolCallingAdvisor keeps a UsageAccumulator and stamps the summed Usage of every hop onto the final response. So a budget advisor ordered outside the loop does reconcile the right total. It still fails as a budget, for a different reason: it reserves once, before the turn, without knowing whether the loop will take one hop or twelve. It cannot deny hop four. By the time it sees the bill, the tokens are spent. Inside the loop, the advisor sees one round at a time, before the accumulator adds it up. Keep settlement there and only there. If you also have an outer advisor that reads Usage (logging, a metrics hook), it is reading the turn total. Settle from both and you charge every hop twice. The limits on the manager are new since 2.0.1, and the defaults are generous: DEFAULT_MAX_CALLS_PER_TOOL is 40 and DEFAULT_MAX_TOTAL_TOOL_CALLS is 150 per turn. At the mid card from the calculator, 150 tool calls with a growing prompt is a turn you do not want to pay for. With THROW , ToolCallingAdvisor catches the ToolCallLimitExceededException and returns the breach as the final generation instead of looping back to the model. BaseAdvisor is the wrong base class here too. Its stream path calls after only when the finish reason matches, and onErrorResume turns a failure into an IllegalStateException without a release hook. A hold reserved in before then lives until someone notices. I implement CallAdvisor and StreamAdvisor directly so reserve, the provider call, and release or reconcile are in one method. The advisor This is the whole call path. The gateway does the SQL; the advisor only decides when to call it. @Component public class BudgetAdvisor implements CallAdvisor { private static final Logger log = LoggerFactory.getLogger(BudgetAdvisor.class); private final BudgetGateway gateway; private final CostEstimator estimator; BudgetAdvisor(BudgetGateway gateway, CostEstimator estimator) { this.gateway = gateway; this.estimator = estimator; } @Override public ChatClientResponse adviseCall(ChatClientRequest request, CallAdvisorChain chain) { BudgetScope scope = BudgetScope.from(request.context()); // missing scope throws: deny long estimateMicros = estimator.estimateMicros(request.prompt()); Reservation hold = gateway.reserve(scope, estimateMicros); // 0 rows throws BudgetExhaustedException ChatClientResponse response; try { response = chain.nextCall(request); } catch (RuntimeException providerFailure) { gateway.release(hold); throw providerFailure; } try { gateway.settle(hold, estimator.actualMicros(response, estimateMicros)); } catch (DataAccessException settleFailure) { log.warn("Settle failed for reservation {}; sweeper will charge the estimate", hold.id(), settleFailure); } return response; } @Override public int getOrder() { return ToolCallingAdvisor.DEFAULT_ORDER + 100; } @Override public String getName() { return "BudgetAdvisor"; } } Two choices in there that took me a while. A provider failure releases the hold and rethrows. No retry here. Retrying a model call inside a budget advisor is how one bad hop costs three times. A settle failure does not throw. The provider already answered, and the money is already spent. Throwing would discard a paid answer, and the caller would probably retry and pay again. The hold stays RESERVED , and the sweeper deals with it. More on what the sweeper charges below, because I got that wrong the first time. actualMicros falls back to the estimate when chatResponse() or its Usage is null. The stream version has the same shape on the Flux : reserve before subscribin...