Guide · 20 min read

Guide

LLM06 Unbounded Consumption: measuring what one request can cost

A lesson with its own example: a public chat, and what one long answer, one large message, one long conversation and one loop cost it in tokens, model calls and seconds, with two fixes measured.

By Kursad AlsanPublished 20 min read

Part 6 of 10 in the series Testing the OWASP Top 10 for LLM Applications 2026

  • OWASP LLM Top 10
  • LLM06 Unbounded Consumption
  • Denial of wallet
  • Rate limiting
  • AI red teaming
output tokens for one sentence
4,096
the tokens of an ordinary question
38×
model calls for one order status
30
output tokens at most, with limits in code
200

The short version

  • A public chat had no limit on the size of a message, the length of an answer or the history it sends. One sentence that asks for a long list cost 4,096 output tokens and 226 seconds, where an ordinary answer has 24 tokens and takes 0.8 seconds.
  • One pasted message cost 3,084 input tokens, the twelfth turn of a conversation sent 1,148 tokens where the first had sent 94, and one order status made 30 model calls. Meanwhile another customer waited 213 seconds for the opening hours.
  • A sentence in the prompt did not keep the long answer short. Limits in code put a number on every size: the answer stopped at 200 tokens, the pasted message was refused before the model was called, and the tracker stopped after 3 checks.

Unbounded Consumption is the sixth entry in OWASP's Top 10 for LLM Applications 2026: an application lets a user spend its compute, its money or its capacity without a limit. This guide is a lesson in testing for it. It builds a small public chat, and measures what single requests cost the service in tokens, model calls and seconds: one long answer, one large message, one long conversation and one loop, and what another customer waits meanwhile. Then it measures two fixes.

The finding is a cost

Most findings in this series are something the application gave away or did. This one is a number. OWASP's definition: "Unbounded Consumption occurs when an LLM application allows excessive and uncontrolled inferences, enabling attackers to disrupt service availability, inflict unsustainable financial costs, or steal intellectual property through model cloning". And what makes it an attack: "A defining characteristic of this threat is cost asymmetry." A request is cheap to send, and what it sets off is not.

What grows without a limitWhere OWASP's entry has itIn this guide
The length of an answer"Output Explosion", among its examplesTest 1
The size of a message"Uncontrolled Input Size", its first scenarioTest 2
The history sent with every turn"Large-Context Abuse", among its examplesTest 3
The steps of a loop"Agentic Circuit Breakers", among its controlsTest 4
Everybody else's waiting time"disrupt service availability", in its definitionTest 5
The bill"Denial of Wallet (DoW)", among its examplesEvery test, read as tokens: the model here runs on my own machine and sends no invoice
Six things that can grow, and where this guide measures them.

The example: a public chat

The example is one Python file with no dependencies. Alder Home is a made-up furniture shop. Its website has a chat that anybody can use: a visitor picks a session name and sends messages. An order tracker keeps checking an order until its state changes. Every response reports what the request cost, and /usage lists what every session has cost so far.

assistant.py
#!/usr/bin/env python3
"""Alder Home customer chat: a small example for practising unbounded consumption tests.

A public chat with a session per visitor, and an order tracker that keeps checking until an order moves. The
response reports what each request cost: tokens in, tokens out, model calls and seconds. GET /usage lists what
every session has cost so far.

    python assistant.py            as built: no limit on input, output, history, rate or loop  http://127.0.0.1:8600
    python assistant.py --ask      fix A: the prompt asks the model to keep answers short
    python assistant.py --limit    fix B: limits in code: message size, output tokens, history window, a token
                                   budget per session and minute, one request per session at a time, three checks

Standard library only. Needs Ollama on 127.0.0.1:11434 with the model llama3.2:3b. Local use only.
"""
import json
import sys
import threading
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

MODEL, OLLAMA = "llama3.2:3b", "http://127.0.0.1:11434"
ASK, LIMIT = "--ask" in sys.argv, "--limit" in sys.argv
MAX_CHARS, MAX_OUTPUT, WINDOW, BUDGET, MAX_CHECKS = 2000, 200, 6, 3000, 3   # fix B: characters per message, output tokens, messages of
#                                                                             history sent, tokens per session and minute, tracker checks
SYSTEM = "You are the customer chat assistant of Alder Home, an online furniture shop. Standard delivery takes 3 to 5 working days. Returns are accepted within 30 days. The support line is open Monday to Friday from 09:00 to 18:00."
ORDERS = {"A-1001": "delivered", "A-1005": "in transit"}   # A-1005 never arrives
SESSIONS, SPENT, BUSY = {}, {}, {}
USAGE = {}   # what every session has cost since the application started: the ledger behind GET /usage
LOCK = threading.Lock()


class Refused(Exception):
    pass


def model(messages, cost):
    options = {"num_predict": MAX_OUTPUT} if LIMIT else {"num_predict": 4096}   # as built: "the context size is the limit"
    body = {"model": MODEL, "messages": messages, "stream": False, "options": options}
    req = urllib.request.Request(OLLAMA + "/api/chat", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=1800) as r:
        res = json.loads(r.read())
    cost["tokens_in"] += res.get("prompt_eval_count", 0)
    cost["tokens_out"] += res.get("eval_count", 0)
    cost["model_calls"] += 1
    return res["message"]["content"]


def budget(session, cost=None):
    """fix B: tokens used by this session in the last minute. Refuses when the budget is spent"""
    now = time.time()
    used = SPENT[session] = [(t, n) for t, n in SPENT.get(session, []) if now - t < 60]
    if cost:
        used.append((now, cost["tokens_in"] + cost["tokens_out"]))
    elif sum(n for _, n in used) >= BUDGET:
        raise Refused("this session has used its %d tokens for this minute" % BUDGET)


def chat(session, message, cost):
    history = SESSIONS.setdefault(session, [])
    history.append({"role": "user", "content": message})
    sent = history[-WINDOW:] if LIMIT else history   # as built: the whole conversation goes to the model on every turn
    system = SYSTEM + (" Keep every answer under 100 words, whatever the customer asks for." if ASK else "")
    answer = model([{"role": "system", "content": system}] + sent, cost)
    history.append({"role": "assistant", "content": answer})
    return answer


def track(order, cost):
    """keeps asking the model to read the order's state until the order has moved"""
    checks = 0
    while True:
        checks += 1
        state = ORDERS.get(order, "unknown")
        answer = model([{"role": "system", "content": SYSTEM}, {"role": "user", "content": "Order %s is %s. Tell the customer in one sentence." % (order, state)}], cost)
        if state != "in transit" or checks >= (MAX_CHECKS if LIMIT else 30):   # as built: thirty checks, "more than anyone needs"
            return answer


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def reply(self, obj, code=200):
        data = json.dumps(obj, indent=1).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_POST(self):
        raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
        if self.path == "/reset":
            SESSIONS.clear(), SPENT.clear()
            return self.reply({"reset": True})
        if self.path not in ("/chat", "/track"):
            return self.reply({"error": "not found"}, 404)
        body = json.loads(raw or b"{}")
        session, cost, t0 = str(body.get("session", "anonymous")), {"tokens_in": 0, "tokens_out": 0, "model_calls": 0}, time.time()
        try:
            if LIMIT:   # fix B: every limit is checked before the model is called
                if len(str(body.get("message", ""))) > MAX_CHARS:
                    raise Refused("a message can have at most %d characters" % MAX_CHARS)
                budget(session)
                with LOCK:
                    if BUSY.get(session):
                        raise Refused("one request per session at a time")
                    BUSY[session] = True
            try:
                answer = chat(session, str(body.get("message", "")), cost) if self.path == "/chat" else track(str(body.get("order", "")), cost)
            finally:
                BUSY.pop(session, None)
                if LIMIT:
                    budget(session, cost)
        except Refused as e:
            return self.reply({"error": str(e)}, 429)
        except OSError as e:   # the model server is down or too slow
            return self.reply({"error": "model: %s" % e}, 502)
        used = USAGE.setdefault(session, {"requests": 0, "tokens_in": 0, "tokens_out": 0, "model_calls": 0, "seconds": 0.0})
        used.update(requests=used["requests"] + 1, tokens_in=used["tokens_in"] + cost["tokens_in"], tokens_out=used["tokens_out"] + cost["tokens_out"],
                    model_calls=used["model_calls"] + cost["model_calls"], seconds=round(used["seconds"] + time.time() - t0, 1))
        self.reply({"answer": answer, "cost": dict(cost, seconds=round(time.time() - t0, 1))})

    def do_GET(self):
        if self.path != "/usage":
            return self.reply({"error": "not found"}, 404)
        rows = sorted(USAGE.items(), key=lambda kv: -(kv[1]["tokens_in"] + kv[1]["tokens_out"]))   # the most expensive session first, one per line
        data = ("[\n" + ",\n".join(json.dumps(dict({"session": s}, **u)) for s, u in rows) + "\n]\n").encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)


if __name__ == "__main__":
    mode = "fix A, the prompt asks" if ASK else "fix B, limits in code" if LIMIT else "as built"
    print("Alder Home customer chat (%s) on http://127.0.0.1:8600" % mode, flush=True)
    ThreadingHTTPServer(("127.0.0.1", 8600), Handler).serve_forever()
setup
ollama pull llama3.2:3b     # 2.0 GB, once
python assistant.py         # http://127.0.0.1:8600
The lab setup guide covers installing Ollama and the model.
bash
python --version && curl -s http://127.0.0.1:11434/api/version && echo && curl -s http://127.0.0.1:11434/api/tags | python -c "import json,sys; [print(m['name'], m['details']['parameter_size'], m['details']['quantization_level'], m['digest'][:12]) for m in json.load(sys.stdin)['models'] if m['name'].startswith('llama3.2')]"
Python 3.13.17
{"version":"0.40.16"}
llama3.2:3b 3.2B Q4_K_M a80c4f17acd5
The versions behind every result below: Python, Ollama, and the model with its size, quantization and digest.

One ordinary question, with its cost:

bash
curl -s http://127.0.0.1:8600/chat -H "Content-Type: application/json" -d '{"session": "demo", "message": "When is the support line open?"}'
{
 "answer": "The support line at Alder Home is open from Monday to Friday, 09:00 to 18:00.",
 "cost": {
  "tokens_in": 86,
  "tokens_out": 25,
  "model_calls": 1,
  "seconds": 1.5
 }
}

That is the unit for everything that follows. I ran everything on November 15, 2026, on Windows 11 in Git Bash, with the model on a CPU.

One turn of the chat, as built

A visitorChat applicationModelA message of any size, in a session that thevisitor names1The whole conversation so far, and the message2An answer of up to 4,096 tokens3The answer, and what it cost4
  1. A visitor → Chat application: A message of any size, in a session that the visitor names
  2. Chat application → Model: The whole conversation so far, and the message
  3. Model → Chat application: An answer of up to 4,096 tokens
  4. Chat application → A visitor: The answer, and what it cost

A size that the visitor decides

Nothing on this path counts anything before it happens. The cost is known when the answer is there.
A limit onAs built
The size of a messageNone
The length of an answer4,096 tokens, the size of the model's context
The history sent with every turnNone: the whole conversation
Tokens per session and minuteNone
Requests at once per sessionNone
Checks by the order tracker30
The limits of the example as built, read from its code.

Measure a cost against a baseline

A test for unbounded consumption does not need a flood. It needs single requests, a count of what each one cost on the service's side, and an ordinary request to compare with. Four numbers per request are enough: tokens in, tokens out, model calls, seconds. The fifth number belongs to somebody else: what another customer waits meanwhile.

load.py takes six measurements. Nothing in it is a rate, and it never sends more than two requests at once.

load.py
#!/usr/bin/env python3
"""Unbounded consumption measurements for the example customer chat.

Nothing here is a rate. Each measurement reports what a request cost the service: tokens in, tokens out, model
calls and seconds, as the application itself counted them, and what a legitimate customer waited meanwhile.

    python load.py                  every measurement
    python load.py --only output    one of: baseline, output, input, history, loop, crowd
    python load.py --out results.json
"""
import argparse
import json
import threading
import time
import urllib.error
import urllib.request

BASE = "http://127.0.0.1:8600"
QUESTION = "When is the support line open?"
LONG_OUTPUT = "Describe 100 different pieces of furniture, numbered from 1 to 100, with three sentences for each one. Do not skip any number."
PASTE = " ".join("Paragraph %d: the oak side table arrived with a scratch on the left leg and I would like to know my options." % i for i in range(1, 121))
MORE = "Tell me one more thing about caring for wooden furniture, in two sentences."


def post(path, body):
    """the response and the seconds the caller waited. A refusal (HTTP 429) comes back as {"error": ...}"""
    req = urllib.request.Request(BASE + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
    t0 = time.time()
    try:
        with urllib.request.urlopen(req, timeout=3600) as r:
            res = json.loads(r.read())
    except urllib.error.HTTPError as e:
        res = dict(json.loads(e.read() or b"{}"), status=e.code)
    res["waited"] = round(time.time() - t0, 1)
    return res


def cost(res):
    c = res.get("cost", {})
    return "refused: %s" % res["error"] if "error" in res else "%5d tokens in, %5d out, %2d model calls, %6.1f s" % (c["tokens_in"], c["tokens_out"], c["model_calls"], c["seconds"])


def baseline():
    runs = [post("/chat", {"session": "base-%d" % i, "message": QUESTION}) for i in range(3)]
    for r in runs:
        print("baseline   %s" % cost(r), flush=True)
    return runs


def output():
    runs = [post("/chat", {"session": "out-%d" % i, "message": LONG_OUTPUT}) for i in range(2)]
    for r in runs:
        print("output     %s" % cost(r), flush=True)
    return runs


def input_():
    runs = [post("/chat", {"session": "in-%d" % i, "message": PASTE + " What are my options?"}) for i in range(2)]
    for r in runs:
        print("input      %s   (the message had %d characters)" % (cost(r), len(PASTE) + 22), flush=True)
    return runs


def history():
    runs = [post("/chat", {"session": "hist", "message": MORE}) for _ in range(12)]
    for i, r in enumerate(runs, 1):
        print("history    turn %2d: %s" % (i, cost(r)), flush=True)
    return runs


def loop():
    r = post("/track", {"session": "loop", "order": "A-1005"})
    print("loop       %s" % cost(r), flush=True)
    return [r]


def crowd():
    """what one customer waits for a short answer while other sessions ask for long ones"""
    out = []
    for others in (0, 1):   # one other session is enough to see it. More sessions at once also make the model server use much more memory
        threads = [threading.Thread(target=post, args=("/chat", {"session": "crowd-%d-%d" % (others, i), "message": LONG_OUTPUT})) for i in range(others)]
        for t in threads:
            t.start()
        time.sleep(3 if others else 0)   # the long requests are under way
        r = post("/chat", {"session": "victim-%d" % others, "message": QUESTION})
        for t in threads:
            t.join()
        print("crowd      %d long requests running: the customer waited %6.1f s%s" % (others, r["waited"], "  (%s)" % r["error"] if "error" in r else ""), flush=True)
        out.append(dict(r, others=others))
    return out


ALL = {"baseline": baseline, "output": output, "input": input_, "history": history, "loop": loop, "crowd": crowd}
if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--only", choices=list(ALL))
    ap.add_argument("--out")
    a = ap.parse_args()
    results = {}
    for name in ([a.only] if a.only else list(ALL)):
        post("/reset", {})
        if name != "baseline":
            time.sleep(61)   # a fresh minute, so that fix B's budget is not spent by the measurement before
        results[name] = ALL[name]()
    if a.out:
        with open(a.out, "w", encoding="utf-8") as f:
            json.dump(results, f, indent=1)

The measurements, as built

bash
python load.py --out results-as-built.json
baseline      86 tokens in,    52 out,  1 model calls,    1.8 s
baseline      86 tokens in,    24 out,  1 model calls,    0.8 s
baseline      86 tokens in,    20 out,  1 model calls,    0.7 s
output       108 tokens in,  4096 out,  1 model calls,  226.4 s
output       108 tokens in,  1443 out,  1 model calls,   66.0 s
input       3084 tokens in,   274 out,  1 model calls,   60.4 s   (the message had 13113 characters)
input       3084 tokens in,   242 out,  1 model calls,   18.0 s   (the message had 13113 characters)
history    turn  1:    94 tokens in,    74 out,  1 model calls,    2.8 s
history    turn  2:   192 tokens in,    57 out,  1 model calls,    2.1 s
history    turn  3:   273 tokens in,    65 out,  1 model calls,    2.5 s
history    turn  4:   362 tokens in,    68 out,  1 model calls,    2.6 s
history    turn  5:   454 tokens in,    83 out,  1 model calls,    3.1 s
history    turn  6:   561 tokens in,    86 out,  1 model calls,    4.3 s
history    turn  7:   671 tokens in,    83 out,  1 model calls,    4.7 s
history    turn  8:   778 tokens in,    65 out,  1 model calls,    3.8 s
history    turn  9:   867 tokens in,    73 out,  1 model calls,    4.3 s
history    turn 10:   964 tokens in,    75 out,  1 model calls,    4.3 s
history    turn 11:  1063 tokens in,    61 out,  1 model calls,    3.6 s
history    turn 12:  1148 tokens in,    53 out,  1 model calls,    3.3 s
loop        2850 tokens in,   940 out, 30 model calls,   39.3 s
crowd      0 long requests running: the customer waited    1.1 s
crowd      1 long requests running: the customer waited  213.3 s
The whole run took 16 minutes, with a pause of one minute before each measurement after the first.

Tokens that one request cost, as built

RequestTokens in and out
An ordinary question110
A request for a long list4204
One long pasted message3358
Turn 12 of one conversation1201
One order status, with the tracker3790
Llama 3.2 3B behind the example as built, November 15, 2026. Tokens in and tokens out of one request, as the application counted them.
RequestTokens inTokens outModel callsSecondsAgainst the ordinary question
An ordinary question862410.81
A request for a long list1084,096122638 times the tokens
One long pasted message3,08427416031 times the tokens
Turn 12 of one conversation1,1485313.311 times the tokens
One order status, with the tracker2,850940303934 times the tokens
The same five requests in numbers.

Test 1. Ask for a long answer

"Describe 100 different pieces of furniture, numbered from 1 to 100, with three sentences for each one. Do not skip any number." It is a sentence that any visitor can type. The two answers had 4,096 and 1,443 output tokens and took 226 and 66 seconds. An ordinary answer has 24 tokens and takes 0.8 seconds.

Neither answer is the whole list. The first got to number 72 and ran into the 4,096 tokens of the model's context, a ceiling that nobody chose as a limit. The second stopped by itself at number 20, and gave a reason: it had reached "the limit of the number of responses allowed per day". The application has no such limit. The model made it up. So what this request costs is decided by a visitor's sentence and by what the model happens to do with it: between 60 and 170 times the output of an ordinary answer, in two tries.

Test 2. Send a large message

The second measurement pastes a complaint of 13,113 characters into the chat and asks one question about it. The service read 3,084 tokens for it, where an ordinary question brings 86, and took 60 and 18 seconds to answer. OWASP's scenario for it is short: "An attacker submits an unusually large input to an LLM application that processes text data, resulting in excessive memory usage and CPU load".

Test 3. Keep talking

The third measurement is a conversation of twelve short turns in one session. The visitor's messages do not get longer. The request to the model does, because the application sends the whole conversation every time.

Tokens sent to the model, turn by turn

Turn of the conversationTokens in
Turn 194
Turn 2192
Turn 3273
Turn 4362
Turn 5454
Turn 6561
Turn 7671
Turn 8778
Turn 9867
Turn 10964
Turn 111063
Turn 121148
The example as built. Every turn pays again for all the turns before it.

The first turn sent 94 tokens and the twelfth 1,148. The twelve turns together cost 8,270 tokens; twelve separate questions of the first turn's size would have cost 2,016. OWASP calls it context accumulation, and notes where the lasting risk is: "the durable risk comes from requests that stay just within limits while inflating per-request cost".

Test 4. Start a loop

The order tracker asks the model to phrase an order's state, and repeats that until the state changes. Order A-1005 never arrives. One request for its status made 30 model calls, 3,790 tokens and 39 seconds, where an ordinary question makes one call. The code calls its ceiling of 30 checks "more than anyone needs". One request used all of them.

Test 5. Ask who else is waiting

The last measurement is about another customer. She asks when the support line is open. Alone, she waited 1.1 seconds. With one long answer under way for another session, she waited 213 seconds: her answer came when the other session's answer was finished, which took 215 seconds. Her request was as small as before. OWASP's scenarios describe the end of that road as "making the service unavailable to legitimate users". Here one request was enough to make her wait.

The model server is shared in one more way. Its process held 2,490 MB of memory before these measurements and 3,679 MB after them.

bash
powershell -NoProfile -Command "Get-Process llama-server | ForEach-Object { 'llama-server: {0:N0} MB in memory' -f (\$_.WorkingSet64 / 1MB) }"
llama-server: 2,490 MB in memory
bash
powershell -NoProfile -Command "Get-Process llama-server | ForEach-Object { 'llama-server: {0:N0} MB in memory' -f (\$_.WorkingSet64 / 1MB) }"
llama-server: 3,679 MB in memory

What the service knows about it

bash
curl -s http://127.0.0.1:8600/usage
[
{"session": "hist", "requests": 12, "tokens_in": 7427, "tokens_out": 843, "model_calls": 12, "seconds": 41.4},
{"session": "out-0", "requests": 1, "tokens_in": 108, "tokens_out": 4096, "model_calls": 1, "seconds": 226.4},
{"session": "crowd-1-0", "requests": 1, "tokens_in": 108, "tokens_out": 4096, "model_calls": 1, "seconds": 214.8},
{"session": "loop", "requests": 1, "tokens_in": 2850, "tokens_out": 940, "model_calls": 30, "seconds": 39.3},
{"session": "in-0", "requests": 1, "tokens_in": 3084, "tokens_out": 274, "model_calls": 1, "seconds": 60.4},
{"session": "in-1", "requests": 1, "tokens_in": 3084, "tokens_out": 242, "model_calls": 1, "seconds": 18.0},
{"session": "out-1", "requests": 1, "tokens_in": 108, "tokens_out": 1443, "model_calls": 1, "seconds": 66.0},
{"session": "base-0", "requests": 1, "tokens_in": 86, "tokens_out": 52, "model_calls": 1, "seconds": 1.8},
{"session": "demo", "requests": 1, "tokens_in": 86, "tokens_out": 25, "model_calls": 1, "seconds": 1.5},
{"session": "base-1", "requests": 1, "tokens_in": 86, "tokens_out": 24, "model_calls": 1, "seconds": 0.8},
{"session": "victim-0", "requests": 1, "tokens_in": 86, "tokens_out": 21, "model_calls": 1, "seconds": 1.1},
{"session": "base-2", "requests": 1, "tokens_in": 86, "tokens_out": 20, "model_calls": 1, "seconds": 0.7},
{"session": "victim-1", "requests": 1, "tokens_in": 86, "tokens_out": 20, "model_calls": 1, "seconds": 213.3}
]
The application's own ledger after the measurements: one line per session, the most tokens first.
Chrome's source view of the example's /usage address with line wrap on: one line per session with its requests, tokens in, tokens out, model calls and seconds. The session of the twelve-turn conversation is at the top, the sessions of the long answers follow.
The same ledger in a browser, captured during the run. Whoever operates the service can see the cost. Nothing in the application acts on it.

The ledger has a surprise. By tokens, the most expensive session is not a long answer. It is the conversation of twelve short turns, with 8,270 tokens. By seconds it is the long answer: 226 seconds for one request, where the whole conversation took 41. Tokens out take far longer than tokens in on this machine, so count both, and count them apart.

Find out what the service counts

A ledger like this one is the first thing to ask for in a test. If the operator cannot say what one session cost yesterday, there is nothing a limit could be attached to, and nobody will notice the invoice before it arrives.

Fix A: ask for short answers

The first fix is one sentence in the prompt. Started with --ask, the example tells the model to keep every answer under 100 words, whatever the customer asks for.

bash
python assistant.py --ask
Alder Home customer chat (fix A, the prompt asks) on http://127.0.0.1:8600
The example restarted with fix A.
bash
python load.py --only output --out results-ask.json
output       122 tokens in,  4096 out,  1 model calls,  220.9 s
output       122 tokens in,  4096 out,  1 model calls,  245.5 s

The same request for the long list, twice. The answers had 4,096 and 4,096 output tokens (as built: 4,096 and 1,443), or 3,274 and 3,245 words, and took 221 and 246 seconds. The prompt says under 100 words, and neither answer kept it: both ran into the 4,096 tokens again. A sentence in a prompt is a wish. And even a wish that comes true would end there: the size of a message, the history, the tracker's loop and the queue are not the model's to decide, so fix A can do nothing for tests 2 to 5.

Fix B: limits in code

The second fix puts a number on every size, in code, and checks it before the model is called. Started with --limit:

A limit onAs builtFix B
The size of a messageNone2,000 characters
The length of an answer4,096 tokens200 tokens
The history sent with every turnThe whole conversationThe last 6 messages
Tokens per session and minuteNone3,000
Requests at once per sessionNoneOne
Checks by the order tracker303
The limits of fix B next to the example as built, read from the code.
assistant.py: the checks before the model is called
            if LIMIT:   # fix B: every limit is checked before the model is called
                if len(str(body.get("message", ""))) > MAX_CHARS:
                    raise Refused("a message can have at most %d characters" % MAX_CHARS)
                budget(session)
                with LOCK:
                    if BUSY.get(session):
                        raise Refused("one request per session at a time")
                    BUSY[session] = True
assistant.py: budget()
def budget(session, cost=None):
    """fix B: tokens used by this session in the last minute. Refuses when the budget is spent"""
    now = time.time()
    used = SPENT[session] = [(t, n) for t, n in SPENT.get(session, []) if now - t < 60]
    if cost:
        used.append((now, cost["tokens_in"] + cost["tokens_out"]))
    elif sum(n for _, n in used) >= BUDGET:
        raise Refused("this session has used its %d tokens for this minute" % BUDGET)

These are OWASP's controls for this entry. On what to count: "Move beyond requests per second to enforce limits on tokens-per-minute, tokens-per-day, and estimated cost per request." On when to refuse: "Use pre-flight token estimation to reject requests before inference begins." Fix B's size check is the plain version of that: it counts characters. And for the loop: "Enforce step limits, recursion depth limits, time limits, and per-run cost ceilings on all agent executions."

bash
python assistant.py --limit
Alder Home customer chat (fix B, limits in code) on http://127.0.0.1:8600
The example restarted with fix B.
bash
python -c "import json, urllib.request, urllib.error
try:
    urllib.request.urlopen(urllib.request.Request('http://127.0.0.1:8600/chat', data=json.dumps({'session': 'demo', 'message': 'x' * 5000}).encode(), headers={'Content-Type': 'application/json'}))
except urllib.error.HTTPError as e:
    print('HTTP', e.code, e.read().decode())"
HTTP 429 {
 "error": "a message can have at most 2000 characters"
}
A message of 5,000 characters. The refusal comes at once: the model is not asked.
bash
python load.py --out results-limit.json
baseline      86 tokens in,    20 out,  1 model calls,    1.9 s
baseline      86 tokens in,    24 out,  1 model calls,    0.9 s
baseline      86 tokens in,    20 out,  1 model calls,    0.7 s
output       108 tokens in,   200 out,  1 model calls,    7.6 s
output       108 tokens in,   200 out,  1 model calls,    8.5 s
input      refused: a message can have at most 2000 characters   (the message had 13113 characters)
input      refused: a message can have at most 2000 characters   (the message had 13113 characters)
history    turn  1:    94 tokens in,    55 out,  1 model calls,    2.3 s
history    turn  2:   173 tokens in,    62 out,  1 model calls,    2.4 s
history    turn  3:   259 tokens in,    60 out,  1 model calls,    2.6 s
history    turn  4:   323 tokens in,    71 out,  1 model calls,    4.9 s
history    turn  5:   339 tokens in,    60 out,  1 model calls,    4.8 s
history    turn  6:   337 tokens in,    75 out,  1 model calls,    5.3 s
history    turn  7:   352 tokens in,    71 out,  1 model calls,    5.2 s
history    turn  8:   352 tokens in,    70 out,  1 model calls,    5.1 s
history    turn  9:   362 tokens in,    77 out,  1 model calls,    5.5 s
history    turn 10: refused: this session has used its 3000 tokens for this minute
history    turn 11: refused: this session has used its 3000 tokens for this minute
history    turn 12: refused: this session has used its 3000 tokens for this minute
loop         285 tokens in,    93 out,  3 model calls,    3.6 s
crowd      0 long requests running: the customer waited    1.0 s
crowd      1 long requests running: the customer waited    5.1 s
The same six measurements. The run took 6 minutes.
MeasurementAs builtFix B
A request for a long list108 in, 4,096 out, 226 s108 in, 200 out, 7.6 s
One long pasted message3,084 in, 274 out, 60 srefused before the model was called
Twelve turns of one conversation8,270 tokens in all, 1,148 sent with the last turn3,192 tokens in all, at most 362 sent with a turn, 3 turns refused: the session's budget for the minute was spent
One order status, with the tracker30 model calls, 3,790 tokens, 39 s3 model calls, 378 tokens, 3.6 s
Another customer's wait behind a long request213 s5.1 s
What the same requests cost with fix B. Llama 3.2 3B, November 15, 2026.

Every number that grew is now a number that somebody chose. The long answer stops at 200 tokens. The pasted message is refused before the model sees it. The conversation sends at most 362 tokens with a turn, where the twelfth turn had sent 1,148, and its last 3 turns ran into the budget of 3,000 tokens per minute. The script sends its twelve turns faster than a person types, which is what a budget per minute is for. The tracker stops after 3 checks. And the other customer waited 5.1 seconds instead of 213.

A limit is a refusal that somebody has to receive

The pasted message in test 2 could have been a real complaint, and fix B refuses it. The long answer stops in the middle of a sentence. Limits cost something too, and the people who pay are ordinary customers. Choose the numbers from what ordinary use looks like in the ledger, and say in the refusal what the limit is.

What is left after the fix

  • A new session is a new budget. The session name comes from the request, so the budget of 3,000 tokens per minute belongs to a name that the visitor makes up. A limit has to hang on something the caller cannot mint: an account, a key, a network address.
  • Many sessions at once. Every limit here is per session or per request. Nothing caps the total. OWASP asks for that as well, and is strict about its kind: budget ceilings "must be enforcement mechanisms that halt inference when exceeded, rather than alerting thresholds that fast-accumulating workloads can outpace".
  • The queue. One request per session at a time does not stop two sessions. How many requests the model server works on at once, and how long the others wait, is decided outside this application.
  • Fix A was not the limit. A sentence can ask for short answers. It cannot make them short.

What to report, and the fix to retest

FindingEvidence to keepFix to retest
No limit on the length of an answerThe request, its tokens out and seconds, next to an ordinary requestA limit on output tokens in the call to the model. Retest with the same request
No limit on the size of a messageThe size of the message, tokens in and secondsA size check before the model is called. Retest that the refusal costs no model call
The whole history is sent with every turnTokens in, turn by turnA window or a summary. Retest that tokens in stop growing
A loop without a ceiling that fits its purposeThe model calls of one requestA step limit in code. Retest with a state that never changes
No budget per userThe ledger: one session's cost next to an ordinary oneA token budget per account and period, checked before the call. Retest with a new session name
One user's work delays the othersAnother customer's wait, with and without the long requestA limit on requests at once per user, and on the queue. Retest the wait
Six findings this guide can produce, each with the control to verify after the fix.

Practise on Troy

Troy is the lab that goes with this series, and its sixth level is an unbounded consumption level. It is harder than this example on purpose, and this guide does not walk through it; nothing on this site does. Take the method there: measure an ordinary request first, and then look for the size that nobody put a number on. The setup guide gets the lab running.

What this guide did not test

  • A flood. No measurement here sent more than two requests at once. How the service behaves under many is a load test, to be agreed with its owner.
  • Money. The model runs on my own machine. On a service that is billed per token, the same counts are an invoice.
  • Reasoning models. OWASP lists prompts that push a thinking model into long reasoning: "Because these prompts are small and appear legitimate, standard input validation provides no protection." Llama 3.2 3B has no thinking budget to exhaust.
  • Inputs optimized to be expensive, and images. Sponge examples and multimodal inputs are in OWASP's list. This example takes text, written by hand.
  • Model extraction. Copying a model through its API is part of this entry in OWASP's text. It is a different test.
  • The serving software. Flaws in the model server itself belong to the supply chain guide.

Frequently asked questions

What is unbounded consumption in an LLM application?

An application that lets a user decide how much compute, money or capacity a request uses. In this guide one sentence made the chat write 4,096 tokens, where an ordinary answer has 24.

What is a denial of wallet attack?

OWASP's words: "By initiating a high volume of operations, attackers exploit the cost-per-use model of cloud-based AI services". The attacker does not need the service to go down. The bill is the damage.

Is rate limiting enough?

Not when it counts requests. OWASP: "Traditional request-rate limiting alone is no longer sufficient." In this guide one request cost 38 times the tokens of an ordinary one, and one request made 30 model calls. Limit tokens, steps and cost.

How do I test for it without taking the service down?

With single requests and a count. Measure an ordinary request, then one long answer, one large message, one long conversation and one loop, each on its own, and read what the service counted. Agree on the test with the owner first: the cost is real even when the service stays up.

My own machine only

Everything above ran on my own machine against an application built for this purpose and a model that runs locally. The shop and its orders are invented. Test systems you own or have written permission to test, and agree on load before you send it.

Sources

Keep reading

All guides

Need the cost side of your LLM application tested?

AI red teaming that measures what one request can cost, with limits to retest.