Bounding the Cost of an AI Request

Bounding the Cost of an AI Request

user avatar

by me1afon

14 minutes ago


AI tools helped gather research and write the first draft of this article. I edited it and checked every quote and figure against the source page listed at the end, read on 2 December 2026. The cover illustration is AI-generated. Details at the end.

In an AI feature, the person who types the request helps decide what it costs you. A long paste, a demand for a very long answer, a loop of tool calls or a script that sends a thousand messages all turn into bills. Put a ceiling on every dimension of a request, enforce it before the paid model call wherever you can, add a ceiling on the total per user and for the whole product, and decide in advance what the user sees when a ceiling is hit. This article shows how, and how to test it.

It covers the limit and abuse side of cost: what stops a request, a user or an attacker from spending more than you intended. It does not discuss what a resolved request costs on average, build or buy, or price comparison. It also does not tell you which numbers to choose; the numbers below are invented.

What the standards call this

OWASP's 2025 list for LLM applications names the problem "Unbounded Consumption": an application that "allows users to conduct excessive and uncontrolled inferences", with risks including denial of service, economic losses, model theft and service degradation [1]. Its examples include "Denial of Wallet", where attackers exploit the cost-per-use model of cloud-based AI services by initiating a high volume of operations, a variable-length input flood, and resource-intensive queries [1]. Its mitigations include input validation, rate limiting and user quotas, timeouts and throttling, logging and anomaly detection, and graceful degradation under load [1].

OWASP's API Security list covers the same ground for any API. It says an API is vulnerable if at least one limit is missing or set inappropriately, and the list includes execution timeouts, maximum upload file size, the number of operations in a single client request, and "Third-party service providers' spending limit" [2]. Its advice applies directly to an AI feature: configure spending limits for all service providers, and "When setting spending limits is not possible, billing alerts should be configured instead" [2].

Start with the worst-case request

Write down the most expensive request your system will accept today. Walk through what one user message can cause:

  • Input size. How much can the user send, including pasted documents and files? What does the system add: history, retrieved passages, tool results?
  • Output size. Most providers let you cap generation per call; Anthropic's rate-limit page, for instance, refers to the max_tokens parameter [3]. Check your provider's parameter and set it deliberately.
  • Steps per request. If the model can call tools and then call itself again, one message becomes many model calls. OpenAI's Agents SDK documents the loop: call the model, run any tool calls, append the results, run again, and raise MaxTurnsExceeded when the max_turns limit is exceeded. The same page says max_turns=None disables the limit [6]. A loop cap is a setting you choose, not a default to ignore.
  • Retries. A retried call is another paid attempt.
  • Media. If the product accepts voice or images, the conversion step may cost more than the text call. Check size and duration first.

Multiply the caps and you have a ceiling for one request. If one dimension has no cap, you cannot compute it, and that dimension is the first thing to fix.

Reject early and cheaply

A check that runs after the paid call has failed at its main job. Put the cheap checks first: identity, request count, input size, and only then the model call. Measuring text length or file size costs almost nothing, and so does rejecting with a clear message.

RFC 6585 defines HTTP 429, "Too Many Requests", for a user who sent too many requests in a given amount of time. The server MAY include a Retry-After header, and the document says it does not define how the server identifies the user or counts requests [5]. That is your design decision, and each choice has a weakness: counting by account does nothing if accounts are free and instant to create, and counting by IP address punishes shared networks. So a per-user limit needs a global limit behind it.

A request counter does not see price

Ten requests per minute sounds safe, but a request is not a unit of cost. A short question to a small model and a long document with several tool calls on a large model can differ greatly in cost, and both count as one. OWASP's API list makes a related point: rate limiting "should be fine tuned based on the business needs" [2].

So count what costs. Most model APIs return token usage with each response. Multiply by the price of the model you called and add it to a running total for the user and the day. When the total reaches the budget, stop using the expensive path for that user. This needs a fast, concurrency-safe store and a price table you keep current.

Keep two totals. A per-user budget stops one account from using the shared allowance. A global budget with a circuit breaker covers what the first cannot see: many accounts, each under its own limit, together exceeding the product's allowance. When the breaker trips, switch off the expensive path for everyone, or for new and unverified accounts first, while a cheaper path keeps the product usable.

Provider limits are a backstop, not a design

Your model provider sets limits too. Anthropic's documentation separates spend limits, a maximum monthly cost for an organization, from rate limits, a maximum number of requests over a period, and lets you set your own spend limits for the organization and for workspaces. It says rate limiting uses a token bucket algorithm, so capacity is continuously replenished rather than reset at fixed intervals [3].

Two details matter for design. When your own spend limit is reached, requests return HTTP 400 with error type invalid_request_error, while a rate limit gives a 429 [3]. For the organization's tier spend cap, the page describes a 429 with no retry-after header and says "Retrying, including the SDK’s automatic retries, fails until access resumes" [3]. Error handling must therefore tell a temporary rate limit from a spending stop, and must not retry the second.

Provider limits are organization-wide: when the cap is reached, every user of your product stops, including honest ones. Use them as the outer wall, set below what you could not afford to pay, and build per-user and global budgets inside it. Read current values on the provider's page; tiers and caps change.

Retries multiply cost

A retry policy written for reliability can multiply cost. OpenAI's rate-limit guide says each official SDK automatically retries eligible 429 and 503 responses, and that if you manage retries yourself you should disable SDK retries or account for them, "so nested retry loops don’t multiply requests". It also says to limit both the number of attempts and the total time spent retrying, to follow Retry-After when present, and not to retry quota, billing or other errors that require you to take action [4].

So count retries inside the request's ceiling: three attempts is three times the worst case. Give the whole operation a deadline, not just each attempt. Never retry an error that says money or quota has run out. If a retry could also repeat something the user asked for, see the earlier article "Retries That Do Not Repeat the User’s Action".

What the user sees at the ceiling

A bare error teaches users to retry harder. Decide the behaviour for each ceiling:

  • Over the size cap: say what the cap is and ask the user to shorten or split the input. Do not truncate silently.
  • Over the rate: return 429 with a Retry-After value and a short wait message.
  • Over the daily budget: switch to a cheaper path, such as a smaller model, a fixed menu, an FAQ search or a note that the assistant resumes tomorrow. OWASP lists graceful degradation, keeping partial functionality instead of complete failure, as a mitigation [1].
  • Global breaker tripped: say plainly that the service is limited right now, keep cheap features working, and alert a person.

A fictional worked bound

The following example is invented. Example Wallet Helper is a made-up chat assistant in a made-up wallet app. It answers questions about the app and can look up the user's own transaction history through one tool. The prices are placeholders chosen to make the arithmetic easy, not any provider's prices.

Assume 3 dollars per million input tokens and 15 dollars per million output tokens. The team sets these caps: 4,000 input tokens per model call (messages, history and tool results included), 500 output tokens per call, and at most 4 model calls per user message.

  • Worst-case input per call: 4,000 × 3 / 1,000,000 = 0.012 dollars.
  • Worst-case output per call: 500 × 15 / 1,000,000 = 0.0075 dollars.
  • Worst case per call: 0.0195 dollars. With 4 calls, the ceiling for one message is 0.078 dollars.

Now the totals. A per-user daily budget of 0.50 dollars allows about six worst-case messages (6 × 0.078 = 0.468), and far more ordinary ones. A rate of 6 messages per minute stops a script from reaching the budget in seconds. For the product, the team sets a global daily budget of 100 dollars with a breaker, and a provider spend limit above it as the outer wall. If 1,000 new accounts each spent their full 0.50 dollars, the total would be 500 dollars; the breaker stops that at 100.

Without the input cap, a pasted 100,000-token document would cost 0.30 dollars in input alone for one call, about fifteen times the 0.0195-dollar ceiling of a whole capped call. Without the call cap, a loop that keeps calling the history tool has no ceiling.

A fictional bound for Example Wallet Helper, drawn as a funnel: input cap, output cap and call cap give one message a ceiling of 0.078 dollars, a per-user daily budget and a global breaker sit below it, and a fallback path catches what is over budget.

At the budget the assistant does not go dark. It answers from a fixed set of help articles and offers to continue tomorrow. That path costs almost nothing per request, so it needs no limit beyond the rate limit.

How to test the bounds

A limit that has never been hit is a guess. Test each ceiling with ordinary scripted traffic against a test environment, with a test account and a provider key that has its own low spend limit:

  1. Send input just under and just over the size cap. The over-cap request must be rejected before any model call, and logs must show no model usage for it.
  2. Send more messages than the rate allows. Check the status code, the Retry-After value and that rejected requests never reached the model.
  3. Give the model a task whose tool keeps returning an error or a next step. The loop must stop at the call cap with a clear message.
  4. Simulate a provider error that says quota is exhausted. The code must not retry it.
  5. Spend a test account's daily budget with cheap requests. The next request must take the fallback path and explain why.
  6. Run many test accounts under their own limits and confirm the global breaker trips and recovers.
  7. Check that every rejection is logged with the reason and the limit that fired, and that no private user text is stored in that log. See the articles "Keeping Private Data Out of AI Context and Logs" and "Testing User Isolation in an AI Product" in this series.

Attack scenarios as a whole are the subject of a later article in this series, "Designing a Focused Red-Team Test for AI Chat"; here the aim is only to prove each limit fires.

A flow diagram of one request through Example Wallet Helper: account check, rate check, size check, then the model call with a call cap, then usage added to the per-user and global totals, with each rejected step labelled with its status and message.

Common mistakes

1. Only a request-per-minute limit. It does not see price. Add a cost budget.

2. A cap on the answer but not on the loop. Each call is bounded, the number of calls is not.

3. Retrying a spending stop. The provider's page says it fails until access resumes [3]. Classify errors first.

4. One shared limit for everybody. One abusive account locks out honest users. Keep per-user budgets inside the global one.

5. A budget with no alert. A limit that trips silently looks like an outage. Alert a person when the breaker trips and when spend nears it; OWASP's API list suggests billing alerts where a spending limit is not possible [2].

What this article cannot tell you

It does not give correct numbers for any limit; the figures and prices in the example are invented. It does not say how to price a product. It does not say how to detect a determined attacker who rotates accounts, networks and devices: a per-user limit can be sidestepped when accounts are free, and the global breaker bounds the damage without identifying anyone. It does not claim that these controls stop denial of service by themselves; they limit cost and abuse, and a serious attack needs infrastructure-level defences outside this article. The sources describe standards and documentation; none measures how much any control saves.

How this article was made

Task What the AI did What a person did How it was checked
Research Gathered candidate sources and drafted notes Chose the question and which pages to rely on Every quote checked against the page named in the sources, read on 2 December 2026
Draft Wrote the first draft from the notes Edited the text, the example and the test list An independent review compares claims with the sources before publication
Arithmetic Computed the example bound Checked the sums The example prices are invented and labelled as such
Images Generated the cover illustration Chose and checked it Labelled as AI-generated in the disclosure line and alt text
Not done by AI — The decision to publish and responsibility for the text —

Conflicts of interest: none. The author has no commercial relationship with the organisations named here.

Responsible for this article: Dmitriy Lastovka, author. Corrections: contact form.

Sources

Labels: standard (a published security framework), documentation (a provider's or project's own documentation), specification (an internet standard). Quotes are as on the pages read on 2 December 2026.

  1. OWASP GenAI Security Project, "LLM10:2025 Unbounded Consumption". https://genai.owasp.org/llmrisk/llm102025-unbounded-consumption/ Standard.
  2. OWASP API Security Top 10, "API4:2023 Unrestricted Resource Consumption". https://owasp.org/API-Security/editions/2023/en/0xa4-unrestricted-resource-consumption/ Standard.
  3. Anthropic, Claude API documentation, "Rate limits" (spend limits, rate limits, max_tokens, 429 and 400 behaviour). https://docs.anthropic.com/en/api/rate-limits Documentation.
  4. OpenAI, API documentation, "Rate limits" (retrying with exponential backoff). https://platform.openai.com/docs/guides/rate-limits Documentation.
  5. IETF, RFC 6585, "Additional HTTP Status Codes", section 4, "429 Too Many Requests". https://www.rfc-editor.org/rfc/rfc6585 Specification.
  6. OpenAI Agents SDK, "Running agents" (the runner loop and max_turns). https://openai.github.io/openai-agents-python/running_agents/ Documentation.

Tier I

Sector: #18291

Sealed Hiding Place Room

Resource Cache

Resource Cache

Tier I

Requires 25% Tier Progress to Claim
Meme Cache

Meme Cache

Tier I

Requires 50% Tier Progress to Claim
Equipment Cache

Equipment Cache

Tier I

Requires 75% Tier Progress to Claim

After collecting, hiding places will be stored in your inventory and can be opened with Keys.

Other articles

Testing User Isolation in an AI Product

How to test that one user's data never reaches another in an AI chat: canary data, two accounts, a test matrix, and a fictional bug a cache introduced.

user avatarme1afon

Keeping Private Data Out of AI Context and Logs

Where a chat message gets copied, what to strip before it reaches the model, what logs should not hold, and a canary test to check it.

user avatarme1afon

Validating Model Output Before an Action

Where to check an AI reply before it acts: in code, at a boundary beside each executor, with checks set by the destination. A fictional order bot and a test.

user avatarme1afon

Giving an Agent Only the Access It Needs

How to limit what an AI agent can do through its tools: fewer tools, narrower functions, scoped credentials, user context and approvals. A fictional example.

user avatarme1afon

When Retrieved Text Tries to Become an Instruction

Why text an AI agent reads from a document cannot be treated as a command, what OWASP and the research say, and a checkable rule for your own chat.

user avatarme1afon

Teaching a Chat to Say It Does Not Know

When a chat should decline to answer: four kinds of no-answer, what research says models do instead, a fictional help-chat example and a test plan.

user avatarme1afon

Important disclaimer: The information presented on the Dapp.Expert portal is intended solely for informational purposes and does not constitute an investment recommendation or a guide to action in the field of cryptocurrencies. The Dapp.Expert team is not responsible for any potential losses or missed profits associated with the use of materials published on the site. Before making investment decisions in cryptocurrencies, we recommend consulting a qualified financial advisor.