codewithkarani

Denial of wallet: how a public AI chatbot can run up your API bill, and the limits that stop it

Karani GeoffreyKarani Geoffrey6 min read
On this page
  1. What OWASP calls it
  2. Work out what one abusive request costs
  3. The limits that stop it, in order
  4. A guarded endpoint, in outline
  5. Provider limits are the backstop
  6. For business owners
  7. Sources

You put an AI chatbot on your website. Every answer costs you a little money, because the AI provider bills for each piece of text it reads and writes. That is fine while real customers use it. The trouble starts when a script sends thousands of long messages, or someone finds your API key in the page source and uses it for their own app.

Nothing breaks. You only find out when the invoice arrives or your prepaid credit runs out. This is called denial of wallet.

Never put the provider key in the browser. Send every chat message through your own server, and there limit messages per visitor, check for bots, cap input length, set max_tokens, cache repeated answers and keep a switch that turns the bot off. Then set a spend limit with the provider as a last line, not the first.

What OWASP calls it

The OWASP Top 10 for LLM Applications 2025 files this under LLM10:2025 Unbounded Consumption: an application that lets users run excessive, uncontrolled inferences, which leads to denial of service, economic loss, model theft and degraded service. Denial of Wallet (DoW) is one of its named examples. Attackers exploit the pay-per-use pricing of cloud AI by starting a high volume of operations until the cost becomes unsustainable. Its prevention list includes strict input size limits, rate limiting and quotas per source, resource allocation so no single user takes too much, timeouts and throttling, and monitoring with anomaly detection.

Work out what one abusive request costs

Do not trust a price you remember. Providers charge separately for input tokens (what you send, including your system prompt and the chat history) and output tokens (what the model writes), each priced per million tokens. Read today's numbers from the provider's pricing page, then compute:

cost per request = input_tokens  x input price  / 1,000,000
                 + output_tokens x output price / 1,000,000

On Anthropic's pricing page output tokens cost several times more than input tokens, and tools can add charges of their own. Multiply your worst case per request by the requests one attacker can send in a day: that is the number your limits must keep small. Each response reports real token counts in its usage field, so log them. For pricing AI features properly, see the true cost of AI beyond the subscription.

The limits that stop it, in order

  1. Keep the key on the server. OpenAI's key safety guide says never to deploy a key in client-side environments like browsers or mobile apps, and to route requests through your own backend. Store it the way our secrets workflow describes.
  2. Rate-limit per visitor. Count messages per user or session, with a looser limit per IP, and protect the whole site as in surviving a bot flood on a cheap VPS.
  3. Challenge bots. Cloudflare Turnstile issues a token in the browser that your server must check with the Siteverify API. The docs say the client-side widget alone does not protect your forms.
  4. Cap the input. Reject messages over a fixed length and trim old chat history, because the whole history is resent and billed on every turn.
  5. Cap the output. Set max_tokens to what a good answer needs. One caveat from Anthropic's docs: a request that uses server tools can call the model more than once, so usage.output_tokens can exceed max_tokens.
  6. Cache repeated work. Store answers to common questions, and use the provider's prompt caching for the fixed system prompt.
  7. Keep a kill switch. One setting that makes the endpoint answer "paused" without calling the provider.
  8. Watch it. Log tokens per visitor per day and alert on spikes. The metering approach in metering, model routing and the regression suite applies directly.

A guarded endpoint, in outline

This illustrative Next.js route handler puts the first five limits in front of the model. The calls follow the official Anthropic TypeScript SDK, Upstash Ratelimit and Turnstile docs. Error handling is left out.

import Anthropic from "@anthropic-ai/sdk";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

const client = new Anthropic(); // key read from server env only
const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, "60 s"),
});
const MAX_CHARS = 2000;

export async function POST(request: Request) {
  if (process.env.CHAT_ENABLED !== "true") {
    return Response.json({ error: "Chat is paused" }, { status: 503 });
  }
  // In production take sessionId from your own signed cookie, not the body.
  const { message, sessionId, turnstileToken } = await request.json();

  const { success } = await ratelimit.limit(`chat:${sessionId}`);
  if (!success) return Response.json({ error: "Slow down" }, { status: 429 });

  const check = await fetch(
    "https://challenges.cloudflare.com/turnstile/v0/siteverify",
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        secret: process.env.TURNSTILE_SECRET_KEY,
        response: turnstileToken,
      }),
    },
  ).then((r) => r.json());
  if (!check.success) return Response.json({ error: "Failed check" }, { status: 403 });

  if (typeof message !== "string" || message.length > MAX_CHARS) {
    return Response.json({ error: "Message too long" }, { status: 400 });
  }

  const reply = await client.messages.create({
    model: "claude-haiku-5-5",
    max_tokens: 500,
    messages: [{ role: "user", content: message }],
  });
  console.log("usage", sessionId, reply.usage); // feed your daily budget
  return Response.json({ content: reply.content });
}

Provider limits are the backstop

Set them in a workspace or project used only by the public chatbot, so a runaway bot cannot stop your internal tools.

  • Anthropic has spend limits (a maximum monthly cost) and rate limits per usage tier. You can set your own monthly spend limit below your tier's cap, and custom spend and rate limits per workspace.
  • OpenAI lets you set spend limits for an organization or project; affected requests return a 429. A spend alert only sends a notification and traffic continues, so do not mistake an alert for a limit.

Tiers and caps change, so check your own console. A provider limit saves your wallet by switching the chatbot off for everyone, which is why your per-visitor limits come first.

For business owners

  • Ask your developer: "Is our AI key anywhere in the website code?" The answer must be no.
  • Ask for a daily message limit per visitor and a short maximum answer length.
  • Set a monthly spend limit with the AI provider that you can afford to lose, and a spend alert below it.
  • Know who can turn the chatbot off, and how fast.

Sources

Frequently asked questions

What is a denial of wallet attack on an AI chatbot?
It is an attack that sends a public AI chatbot a high volume of requests, often long ones, so the owner's pay-per-token bill grows until it becomes unaffordable. OWASP lists Denial of Wallet as an example under LLM10:2025 Unbounded Consumption in its Top 10 for LLM Applications.
Is a spend limit from the AI provider enough to protect my chatbot?
No. Anthropic and OpenAI both let you set spend limits, and you should, ideally on a workspace or project used only by the chatbot. But when the limit is reached the chatbot stops for every visitor. Per-visitor rate limits, bot checks, input caps and max_tokens on your own server stop abuse before it reaches that point. Note that an OpenAI spend alert only notifies you; it does not stop traffic.
How do I estimate what one abusive chatbot request costs?
Read the current input and output prices per million tokens from your provider's pricing page. Cost per request is input tokens times the input price divided by one million, plus output tokens times the output price divided by one million. Use your longest allowed input, your chat history and system prompt, and your max_tokens setting for the worst case, then multiply by the requests one visitor could send in a day.
#LLM Security#OWASP LLM#Rate Limiting#LLM Cost#AI Costs#Cloudflare#API Security

Written by

Karani Geoffrey

Software engineer in Nairobi and founder of Upeosoft. I build ERPNext, AI and web systems that businesses run on, and write down what I learn along the way. More about me

Keep reading