Blog · · 11 min read

Denial of wallet: stop anonymous visitors from running up an embedded AI agent bill with session-bound cost budgets and separate spend pools

Denial of wallet: stop anonymous visitors from running up an embedded AI agent bill with session-bound cost budgets and separate spend pools

Your product's help widget, pricing-page assistant, or free-tier agent answers anyone who opens it, and every answer is billed per token. That makes it a denial of wallet target, where an attacker keeps the agent busy at your expense instead of taking it down. OWASP's LLM10:2025 Unbounded Consumption names denial of wallet as the risk where high-volume operations exploit pay-per-use AI pricing. This guide shows product teams how to put admission control in front of an embedded agent so a script, a freeloader using your bot as free ChatGPT, or a forged cross-site request cannot spend more than you decided in advance, while paying customers keep getting answers.

The short answer: admit cost before the first model call

Treat the public entry point as an admission boundary with six layers, applied in this order on every turn:

  1. Signed visitor session. Issue a short-lived, server-signed session only after a bot challenge passes server-side validation. Rate limits and budgets key on this session, never on a client-supplied ID.
  2. Cheap scope gate. Decide with rules or a small model whether the turn belongs to the product before the expensive agent runs.
  3. Worst-case cost reservation. Count input tokens, add the maximum output and the most retrieval and tool work the turn may trigger, and reserve that amount atomically.
  4. Layered ceilings with separate pools. Check session, IP, anonymous pool, verified-customer pool, tenant, and platform ceilings. Anonymous traffic never draws from the pool that logged-in customers use.
  5. Explicit failure direction. Volumetric checks may fail open; the spend ceiling fails closed.
  6. Degraded answers. When a cap trips, serve FAQ, cached, or handoff responses instead of an error page.

Why embedded agents become denial-of-wallet targets

A logged-out widget has to work for strangers, so the usual defenses are weaker than they look.

New identities are free. If a fresh anonymous session costs the caller nothing, per-identity limits accomplish nothing. Praesidia's denial-of-wallet analysis makes this point about demo widgets, public support bots, and self-service trials, and recommends hard per-principal ceilings that are checked before the call rather than budget alerts afterward.

Off-purpose requests cost more and look normal. CIO's April 2026 report on chatbot freeloaders quotes a CoSAI and ACM AISec program committee member estimating that an order-status question runs 200 to 300 tokens while a request to reverse a linked list in Python can exceed 2,000, roughly ten times the cost, and that these sessions do not show up as anomalies because they look like ordinary conversations. Treat those figures as an estimate. The same article quotes analysts who doubt the scale, noting that free consumer chatbots exist and that flat-rate model contracts soften the impact. The evidence supports a narrower conclusion. Without explicit limits, your exposure has no ceiling, whatever today's abuse rate is.

Forged requests borrow real visitors' addresses. The nr-llm endpoint-protection guide warns that another site can fire forged POSTs at your endpoint through its own visitors' browsers, spreading the load across many victim IPs so per-IP limits barely notice.

Agents fan out. One visitor turn can trigger retrieval, several tool calls, and retries. A practitioner report in Guidewise issue 29 describes an unauthenticated AI endpoint whose caller-controlled item count went straight into the prompt, with each returned item fanning out into paid Google Text Search, Details, and Distance Matrix calls. A limit that counts inbound messages never sees that multiplication.

One shared budget is a shared failure. The nr-llm guide also notes that an aggregate budget caps total spend but does not stop one IP from burning the whole budget and denying the feature to everyone else. In a SaaS product, "everyone else" includes your paying, logged-in customers.

Build denial-of-wallet admission control in five steps

Step 1: issue a signed visitor session behind a challenge

Put a challenge in front of session creation, not in front of every message. Cloudflare's Turnstile server-side validation docs state that the client widget alone does not protect anything: tokens can be forged unless your server calls Siteverify, each token is single-use, and it expires after 300 seconds. Validate the token once, check the returned hostname and action, then mint your own session.

Make that session the principal for everything downstream:

  • Sign it server-side and bind it to the tenant, the embedding surface, the allowed origin, and an expiry measured in minutes or hours.
  • Store it in an HttpOnly cookie or return it to the widget, and refuse turns that arrive without it.
  • Pass a stable, privacy-preserving value derived from it to your model provider. OpenAI's safety best practices recommend a safety_identifier per end user and say a session ID is appropriate when users are not logged in. That gives you per-principal attribution when you need to cut one caller off without disabling the surface.

Proof-of-work sessions are another option. AskMerra documents a widget that solves a small cryptographic puzzle before the first message and receives a short-lived signed session bound to the shop, visitor, and page, so a script that wants a thousand sessions has to solve a thousand puzzles. Either way, each new identity should cost the caller something.

Step 2: gate scope before the expensive model runs

Off-purpose turns should never reach the expensive model. Before the full agent loop, classify the turn with deterministic rules or a small model and route it:

  • In scope and answerable from known content: answer from the FAQ or a cached response.
  • In scope and needs the agent: continue to reservation.
  • Out of scope: return a short, fixed refusal with a link to the product's real support channel.

OpenAI's safety guidance supports the same direction: limit user input length, limit output tokens, and prefer routing a query to an existing support article over generating an answer from scratch. Run this gate as a cost control, separate from your safety guardrails, so an off-purpose turn costs a small, fixed amount.

Step 3: reserve worst-case cost instead of counting messages

Meter reserved worst-case cost per signed visitor session, including retrieval and tool fan-out, because message and reply counts treat a 200-token status check and a 2,000-token off-purpose request as the same unit.

Many widget products document count-based limits. Agentkit's rate limiting counts messages per visitor IP in a rolling window, and There There's support-bubble docs state that its anonymous allowances count reply attempts, not model tokens. Counts are useful volumetric brakes, but the enforced unit for spend should be money or tokens.

The OpenAI Cookbook per-run spending controller gives the core primitive: count input tokens exactly, reserve the most the response could cost at the highest applicable input price plus max_output_tokens, settle the actual cost when the response arrives, and release the unused amount. It also says what the primitive leaves out: hosted tools and streaming are excluded, and several workers sharing one budget need a shared store that checks and reserves in one operation. For an embedded agent, extend the reservation to cover what the turn may trigger:

on visitor_turn(session, message):
  require session.valid and session.tenant == request.tenant
  route = scope_gate(message)                 # faq | cached | agent | refuse
  if route != "agent": return cheap_answer(route)

  input_tokens  = count_tokens(system + context + history + message)
  worst_case    = price(input_tokens, worst_input_rate)
                + price(MAX_OUTPUT_TOKENS, output_rate)
                + MAX_RETRIEVAL_COST
                + MAX_TOOL_CALLS * max_tool_cost(tools_allowed_for(session))

  hold = atomic_reserve(worst_case, keys=[
           session, ip_hash, pool(session),   # pool = anonymous | verified
           tenant, platform])
  if hold.refused: return degraded_answer(hold.reason_code)

  try:
    result = run_agent(message, max_output=MAX_OUTPUT_TOKENS,
                       max_tool_calls=MAX_TOOL_CALLS,
                       safety_identifier=hash(session.id))
    settle(hold, actual_cost(result))
  except unknown_charge:
    keep_reserved(hold)                        # cost unknown: do not refund
    raise

Cap tool calls and output per turn on anonymous surfaces so the worst case is finite. Price tools the session is allowed to call, not every tool the agent has. Run the reservation as one atomic script in your counter store; Praesidia calls a separate read-then-decrement the most common defect in homegrown budget enforcement, because parallel calls each see the same remaining balance.

Step 4: layer the ceilings and split anonymous from verified pools

Keep anonymous visitors in their own spend pool below the tenant ceiling, so a scripted flood exhausts only the anonymous allowance and logged-in customers keep getting answers.

Per-user and global limits leave a gap when the tenant pays for both logged-out prospects and logged-in customers, so add a pool layer between them. There There already behaves this way: anonymous visitors get a per-browser daily allowance plus a workspace-wide anonymous allowance, and a visitor who hits it can verify an email and continue under the verified-user limits in the same conversation. Use a table like this as a starting design, then set values from your own observed p99 usage:

LayerKeyed onPurposeWhen exceeded
SessionSigned session IDStops one browser loopingShort wait, then degraded answer
IPHashed client IPCatches session rotation from one hostDegraded answer for that IP
Anonymous poolTenant plus surfaceCaps total logged-out spendAnonymous turns degrade; verified turns continue
Verified poolTenant plus verified userProtects paying customersPer-user limit, then handoff
TenantTenantContract or plan ceilingProtection mode for that tenant
PlatformAll tenantsProtects your own billPlatform-wide protection mode

Trust only the IP header your edge controls. For example, behind Cloudflare, read CF-Connecting-IP rather than a client-settable X-Forwarded-For. Praesidia's advice to run in observe-only mode first, then set ceilings at a multiple of observed p99, applies to every row. Use vendor defaults only for a sense of scale. AskMerra publishes 20 messages per visitor per minute and $5 per shop per hour before protection mode.

Step 5: choose the failure direction for every control

Decide the failure direction of every control: Origin and Fetch Metadata checks fail open by design and are only defense in depth, while the spend ceiling must fail closed when its counter store is unavailable.

The nr-llm guide rejects Sec-Fetch-Site: cross-site to stop forged cross-site POSTs, and says plainly that a request without the header is not blocked, because non-browser clients never send it. That is the right design for the check, and it also means the check does nothing against curl. A practitioner report in MarkSight issue 84 describes a same-origin guard that ran only when an Origin header was present, so a client that omitted the header skipped it and reached an LLM call on the owner's key. Keep Origin and Fetch Metadata checks, but never let them stand in for the signed session or the spend ceiling.

The counter store is the other half. Check what your limiter does when its Redis or KV store is unreachable. Failing open is a reasonable choice for a request-rate limit whose job is fairness. Applied to the spend ceiling, the same choice turns a cache outage into unmetered inference. Recommendation: let volumetric limits fail open with an alert, and make the spend reservation fail closed, or fall back to a small per-process emergency allowance that resets on recovery. The Cookbook adds two reasons not to lean on provider controls instead: project spending limits may not take effect immediately, and alerts do not stop requests.

Handle failure and recovery: degrade instead of going dark

When a reservation is refused, return a cheaper answer and keep the page working.

  • Protection mode. AskMerra's breakers put a shop into protection mode where greetings, FAQ answers, and cached answers keep working and everything else gets a "we're busy" message with a contact form. Copy that shape so cheap paths stay up, expensive paths pause, and a human can resume.
  • Verify to continue. When the anonymous pool is exhausted, offer sign-in or email verification and move the visitor into the verified pool, as There There does, rather than ending the conversation.
  • Handoff. Route the visitor to a form or human queue with the conversation attached.
  • Uniform errors. The nr-llm guide recommends returning the same generic message for rate-limited and failed requests, because distinguishable responses tell an attacker which control they tripped. Log the real reason server-side with the session and pool.
  • Unknown charges. If a stream is cut or a provider call times out after submission, keep the reservation. The Cookbook keeps the run blocked when cost cannot be confirmed, because the provider may still bill the request.
  • Deterministic fallback. A practitioner backlog item in ai-assistant-automations issue 49 specifies a global cost cap that trips under a synthetic flood and degrades to deterministic-only behavior. That acceptance test belongs in your plan too.

Verify the solution

Run these drills in staging with a real counter store and a cheap model:

  1. Session minting. A script that requests 1,000 sessions without solving the challenge causes zero model calls. A replayed Turnstile token is rejected.
  2. Off-purpose load. A batch of long coding and recipe prompts is routed to the fixed refusal, and the measured cost per refused turn stays under your target.
  3. Cross-site forging. A form on another origin that posts to your chat endpoint is rejected by browsers, and the same request from curl still needs a valid session.
  4. Fan-out ceiling. A prompt engineered to trigger many tool calls stops at the per-turn tool cap, and a turn whose worst case exceeds the remaining balance never dispatches.
  5. Pool isolation. Exhaust the anonymous pool with a load script, then confirm verified-customer turns still succeed and draw only from the verified pool.
  6. Limiter outage. Stop the counter store. Volumetric limits may pass with an alert; new paid agent turns must be refused or limited to the emergency allowance.
  7. Attribution. Every model request carries a safety_identifier, and your spend dashboard can show the top sessions, IPs, and tenants by reserved and settled cost within minutes.

Common mistakes

  • Keying limits on a client-supplied ID. Praesidia notes that a tenant identifier the client supplies is one the attacker can forge. Derive tenant and session from the signed session.
  • Treating the provider dashboard as a control. Alerts notify a person; they do not refuse the next request.
  • Granting public surfaces the most expensive defaults. Cap model tier, context length, and max_output_tokens on anonymous routes. Praesidia calls frontier-model access with a large context window the most expensive default in most deployments.
  • Counting retries as free. Retries draw from the same reservation, or the attacker controls your multiplier.
  • Letting the anonymous allowance and the customer allowance share one number. That is the configuration in which a flood becomes an outage for paying users.

What to do next

Pull last month's model usage for your embedded agent and split it by logged-out versus logged-in sessions and by scope-gate route. If you cannot produce that split, start there: issue signed sessions, send a safety_identifier, and log reserved and settled cost per session in observe-only mode for two weeks. Then set the anonymous pool and the spend ceiling from the observed p99, switch the spend ceiling to fail closed, and run the limiter-outage drill before you raise any limit.

Be first in line.

Join the waitlist and we'll email you the moment it's ready. No sales call.

Try the demo →
or talk to us