
foojay · 10 min readBackend & APIs
Building Token Budgets for Spring AI: The Problems I Didn't Expect
Token Allowance is a Spring Boot starter that enforces per-user, per-tenant, and global token and dollar budgets on Spring AI ChatClient calls. It reserves estimated costs before each model call, rejects requests that would exceed limits, and returns 429 responses when budgets are hit. This ensures predictable billing and protects against runaway tool loops.
- Reserve estimated cost atomically before each model call to avoid race conditions.
- Place a metering advisor after the tool loop to count per-call usage.
- Use micro-dollar integers for exact budget comparisons and deterministic tests.