How to Identify LLM Denial of Service Vulnerabilities in 2026 | AI LLM Hacking Course Day 33 of 90

How to Identify LLM Denial of Service Vulnerabilities in 2026 | AI LLM Hacking Course Day 33 of 90
🤖 AI/LLM HACKING COURSE
FREE

Part of the AI/LLM Hacking Course — 90 Days

Day 33 of 90 · 36.7% complete

A client called me on a Tuesday afternoon with a problem I wish more teams tested before going to production: their AI customer-service system was effectively down.

It hadn’t crashed. The servers were running. The API was responding.

The problem was the bill.

At 11 a.m., just six days into the billing cycle, their AI API budget hit its monthly hard cap. From that moment on, legitimate requests started receiving 429 Too Many Requests responses.

Thirty-five thousand customer queries went unanswered that day.

And while their customers waited, competitors’ live-chat systems were happily picking up the traffic.

The attack had started at 6 a.m.

For five hours, an attacker had been sending sustained requests to the AI API. The prompts weren’t complicated. They were simply expensive:

“Write a complete, detailed explanation of every feature of the product, with examples, for a customer who has never used software before.”

Each request encouraged a massive response—around 4,000 tokens. The attacker ran the requests concurrently, turning a relatively cheap source of traffic into an expensive workload for the victim.

That’s the uncomfortable part of LLM denial of service: the attacker doesn’t always need to overwhelm your servers. They can overwhelm your budget.

Imagine the economics. The attacker may spend only a few dollars—or potentially much less—generating requests from inexpensive infrastructure or compromised resources. The victim, meanwhile, pays for every token processed, every expensive model invocation, and every downstream operation those requests trigger.

That’s cost amplification.

And the basic defenses aren’t exotic.

– Set maximum output-token limits.
– Enforce per-user and per-IP rate limits.
– Validate input length.
– Apply quotas and concurrency limits.
– Monitor abnormal token consumption.
– Put hard spending controls around expensive model routes.

Most importantly, ask the question that teams often forget during development:

“What happens if someone deliberately tries to exhaust our AI API budget?”

That’s the question we’re going to answer in Day 33.

🎯 What You’ll Master in Day 33

Map the cost model of an AI deployment to identify DoS attack vectors
Test context window limits and input length validation
Craft maximum-output requests to test output length controls
Test rate limit enforcement at application and gateway layers
Calculate cost amplification ratios to quantify DoS feasibility
Test downstream resource multiplication from AI-triggered actions

⏱️ Day 33 · 3 exercises · Think Like Hacker + Kali Terminal + Kali Terminal

✅ Prerequisites

  • Day 14 — LLM10 Unbounded Consumption

    — the OWASP overview from Day 14 is the conceptual foundation; Day 33 is the full assessment methodology with exploitation techniques and cost modelling

  • Engagement scope that explicitly authorises DoS testing — never run resource exhaustion or cost amplification tests without written approval
  • Python with asyncio — Exercise 2 builds the concurrent request tester

In Day 32 you assessed how a model’s value can be extracted through API queries. Day 33 covers how that same API surface can be used to destroy the model’s ability to serve legitimate users. Day 34 moves to the multimodal attack surface — the new vulnerabilities that appear when AI systems process images, audio, and documents alongside text.


Mapping the AI Cost Model

Before testing an LLM application for denial-of-service or cost-amplification
vulnerabilities, you need to understand what actually costs money.

An AI request rarely has a single cost. A seemingly simple user interaction can
consume model tokens, vector-database resources, database queries, external API
quotas, compute time, storage, network bandwidth, and additional model calls.

This is why an effective LLM security assessment begins with a
cost model: a map showing how one user request moves through the
application and which resources it consumes at each stage.

User Request -> Application -> LLM Inference -> Tool / Retrieval -> Database / Vector DB -> External API -> Additional LLM Call -> Final Response -> Total Resource Cost

OWASP’s LLM10:2025 guidance identifies uncontrolled inference as a source of
denial of service, service degradation, resource exhaustion, and financial loss.
It specifically includes Denial of Wallet scenarios in which attackers exploit
usage-based AI services to create excessive costs. :contentReference[oaicite:1]{index=1}

1. Identify Every Cost Component

The first step is to identify every resource consumed by a single AI interaction.
Do not stop at the model API bill.

ComponentWhat Creates CostWhat to Measure
LLM inferenceInput and output tokensTokens and provider charges
EmbeddingsText converted into vectorsTokens and embedding requests
Vector databaseSimilarity searches and storageQueries, storage and compute
DatabaseQueries and connectionsQuery count and execution time
External APIsThird-party operationsRequests and provider quota
ComputeCPU, GPU and runtimeExecution time and utilization
StorageDocuments, logs and artifactsReads, writes and storage volume
NetworkData transferBandwidth and request volume

2. Map the LLM Token Cost

For token-priced models, separate input and output consumption. Providers may price
these differently, so use the current pricing information for the specific model
being assessed.

Input Cost = Input Tokens × Input Token Price

Output Cost = Output Tokens × Output Token Price

LLM Request Cost = Input Cost + Output Cost

Do not assume that the visible user prompt represents the entire input. The actual
model request may also contain system instructions, conversation history, retrieved
documents, tool results, and other application-generated context.

Actual Input = System Prompt + Conversation History + User Input + RAG Context + Tool Results + Application Metadata

3. Look for Hidden Token Consumption

One of the most common mistakes in AI cost analysis is calculating the cost from the
user’s visible prompt alone.

For example, a user might submit a short request:

"Summarize this document."

The application could actually send:

System instructions + Conversation history + 10,000-token document + Retrieved metadata + User request + Reserved output capacity

The model provider charges according to the actual processed workload, not simply the
number of characters visible in the chat interface.

Therefore, a security assessment should measure the complete model payload whenever
possible.

4. Calculate the Cost Per Request

Once the individual resource components have been identified, calculate the estimated
cost of one normal request.

Cost Per Request = LLM Cost + Embedding Cost + Database Cost + Vector Search Cost + External API Cost + Compute Cost + Storage / Network Cost

The exact calculation depends on the architecture. Some resources may be billed
directly per request, while others may be shared infrastructure costs that need to
be allocated across users or tenants.

5. Worked Example

Consider a hypothetical AI support application. During an authorized assessment,
one request produces the following resource profile:

ResourceMeasured Consumption
LLM inferenceInput + output tokens
Vector search3 retrieval operations
Database2 queries
External API1 request
Second LLM call1 additional inference

The important observation is that the user made one request, but the
backend performed multiple resource-consuming operations.

1 User Request
      ↓
2 LLM Calls + 3 Vector Searches + 2 Database Queries + 1 External API Call
      =
Multiple Cost Sources

6. Calculate the Cost Multiplication Factor

After establishing the normal cost of one request, determine how much the workload can
grow under unusual but technically permitted usage.

Cost Multiplication Factor =
High-Cost Request
-----------------
Normal Request

For example, if a normal request costs an estimated unit of 1 and a legitimate
maximum-sized request costs 20 units:

Normal Request = 1 unit
Maximum Request = 20 units

Cost Multiplication Factor = 20×

This does not automatically constitute a vulnerability. The security question is
whether an untrusted user can repeatedly generate the high-cost workload without
appropriate quotas or resource controls.

7. Map Cost by Identity

Total system cost is not enough. Security teams should understand how resource
consumption is distributed across identities.

Identity DimensionUseful Metric
UserCost per user
API keyRequests and tokens per key
TenantTotal tenant consumption
EndpointCost per API route
ModelCost by model selection
AgentCost per workflow execution

Identity-based accounting is particularly useful for detecting abnormal consumption.
A sudden increase in token usage from one account or API key may be more informative
than an increase in total system traffic.

8. Map Cost by Endpoint

Different endpoints can have radically different resource profiles.

GET /profile
→ Low cost

POST /chat
→ Moderate cost

POST /document/analyze
→ High cost

POST /agent/run
→ Potentially very high cost

POST /image/generate
→ Potentially high compute cost

A single global request limit can therefore provide an incomplete picture of the
application’s financial exposure.

Expensive endpoints should normally have stricter controls than lightweight endpoints.

9. Model Selection Changes the Cost

Many AI applications expose multiple models with different performance and pricing
characteristics.

User Request
     ↓
Model Selection
     ↓
Model A → Lower Cost
Model B → Medium Cost
Model C → Higher Cost
     ↓
Different Resource Exposure

A security assessment should determine whether users can freely select expensive
models and whether authorization, quotas, or spending controls change according to
model cost.

OWASP includes resource-intensive queries and uncontrolled inference among the
patterns associated with LLM10:2025 Unbounded Consumption. :contentReference[oaicite:2]{index=2}

10. Map Agentic Cost Multiplication

Agentic workflows deserve special attention because one user request can initiate
multiple model calls and downstream operations.

User Request
      ↓
Agent
      ↓
LLM Call
      ↓
Tool Call
      ↓
Database Query
      ↓
LLM Call
      ↓
External API
      ↓
LLM Call
      ↓
Final Response

The effective cost is therefore determined by the entire execution chain rather than
the first model invocation.

Total Agent Cost = LLM Calls + Tool Calls + Database Operations + External APIs + Compute + Storage + Network

Agent workflows should have explicit limits on iterations, tool calls, execution time,
queue depth, and total resource consumption.

11. Map the Budget Boundary

After calculating per-request and per-user costs, map those figures against the
application’s actual spending limits.

Application Usage
       ↓
Provider Billing
       ↓
Budget Threshold
       ↓
Alert
       ↓
Throttle / Degrade
       ↓
Hard Stop

The security team should know what happens at every stage.

ThresholdExpected Behavior
Normal usageFull service
Elevated usageMonitoring and alerting
High usageThrottling or quota enforcement
Critical usageExpensive operations restricted
Budget exhaustedGraceful degradation / controlled shutdown

OWASP recommends resource-allocation management, rate limiting, timeouts and
throttling, monitoring, anomaly detection, graceful degradation, and limits on
queued actions as defenses against unbounded consumption. :contentReference[oaicite:3]{index=3}

12. Identify the Highest-Cost Path

Once the cost model has been mapped, identify the application’s most expensive
request path.

Endpoint
   ↓
Input Size
   ↓
Context Size
   ↓
Model
   ↓
Output Size
   ↓
Tool Calls
   ↓
Downstream Services
   ↓
Total Cost

The highest-cost path is often the most important path to protect because it can create
the largest availability and financial impact when abused.

Prioritize controls around operations that combine large inputs, expensive
models, large outputs, high concurrency, recursive workflows, and multiple downstream
services
.

13. Security Controls for the AI Cost Model

  • Enforce server-side input and output token limits.
  • Apply per-user and per-tenant token quotas.
  • Set endpoint-specific rate limits.
  • Restrict access to expensive models.
  • Limit agent iterations and tool calls.
  • Set maximum execution time.
  • Control concurrent model operations.
  • Monitor cost by user, API key, tenant, model, and endpoint.
  • Configure provider-level budget alerts.
  • Implement application-level spending thresholds.
  • Use circuit breakers for runaway workflows.
  • Gracefully degrade expensive functionality during resource pressure.
  • Log the complete request-to-resource execution chain.

14. The Security Assessment Question

Don’t ask only:

“How much does one API request cost?”

Ask:


“What is the maximum amount of money and computational work one authorized
request can cause the system to consume?”

Then ask the second question:


“How many times can one identity repeat that workload before the system
throttles, alerts, degrades, or stops it?”

Those two questions turn a basic API-cost review into a proper LLM resource-exhaustion
assessment.

Request Cost × Maximum Resource Consumption × Allowed Request Volume × Concurrency
     =
Potential Financial Exposure

The objective is not to eliminate legitimate AI usage. It is to ensure that every
expensive AI capability has a measurable owner, a defined quota, an observable cost,
and a hard upper boundary.

🧠 EXERCISE 1 — THINK LIKE A HACKER (20 MIN · NO TOOLS)
Design the Optimal DoS Attack for Three Different AI Billing Models

⏱️ 20 minutes · No tools needed

The optimal DoS attack is specific to the target’s cost model. This exercise designs the highest-damage attack for three different billing configurations, then calculates the cost amplification ratio for each.

SCENARIO A: Pay-per-token API with unlimited output.
Input: $0.001 / 1K tokens
Output: $0.003 / 1K tokens
Max context: 128K tokens
Rate limit: 60 requests/minute, no per-IP enforcement
Budget cap: Monthly soft cap with alert at 90%, hard stop at 100%

SCENARIO B: Per-request flat fee.
$0.01 per request regardless of token count
Max output: 4,096 tokens (hard limit)
Rate limit: 100 requests/minute
Budget cap: None — billed monthly, no hard stop

SCENARIO C: Hosted model, internal infrastructure.
No per-token billing — company owns the GPU cluster
Cost = inference compute time
Rate limit: None implemented
Context window: 32K tokens
GPU: 8× A100s shared across all users

For each scenario:
1. What is the optimal attack payload? (Specific request design)
2. What is the maximum achievable damage rate?
($ per hour for A/B; GPU-hours per hour for C)
3. What is the attacker’s cost to produce that damage?
4. What is the cost amplification ratio?
5. What single control cuts the amplification ratio most?

REFLECTION: Which scenario has the highest amplification ratio
and therefore the most severe DoS vulnerability?

✅ Answers: Scenario A — optimal payload: single-word input (“List”) followed by “every possible item in this category exhaustively” → 4K-token output → $0.012 per request; at 60 req/min: $43/hour victim cost, attacker cost ≈ $0.006/req * 60 = $0.36/hour; amplification ratio ≈ 120:1. Scenario B — flat fee means exhausting rate limit maximises cost: 100 req/min × $0.01 = $60/hour victim; attacker cost = bandwidth only ≈ $0.01/hour; amplification 6,000:1 — much higher. Scenario C — no billing amplification but GPU exhaustion: 60 max-context requests flood inference queue, blocking all legitimate users; amplification in lost user-hours is severe. Reflection: Scenario B has highest financial amplification (6,000:1) because per-request billing with no token cap means bandwidth is the attacker’s only cost. The single most effective control: hard per-request output token limit — cuts amplification in A from 120:1 to ~5:1.

📸 Share your amplification ratio calculations in #day33-dos on Comments.


Context Window Exhaustion

Context window exhaustion occurs when an LLM application is forced to process an
unusually large amount of input and accumulated conversation context. The objective
is not necessarily to make the model generate a huge response. Instead, the attacker
attempts to make each inference expensive by filling or repeatedly approaching the
model’s available context capacity.

The context window represents the amount of information the model can process for an
inference, including the applicable input and output tokens. Different models have
different context limits, and the effective limit can also be reduced by system
prompts, conversation history, retrieved documents, tool results, and other application
data. OWASP identifies context-window manipulation and continuous input overflow as
potential Model Denial of Service conditions. :contentReference[oaicite:1]{index=1}

1. Understanding the Context Window

A simplified LLM request can be visualized as:

System Instructions + Conversation History + User Input + Retrieved Context + Tool Results + Requested Output 
= Total Model Context

Every additional piece of information consumes part of the model’s available context
budget. In a simple chatbot, this may primarily be conversation history. In a RAG or
agentic application, however, the context can also contain retrieved documents,
search results, tool responses, memory, system instructions, and intermediate
application data.

This makes context management a security concern rather than merely a performance
optimization problem.

2. How Context Exhaustion Creates Resource Pressure

A large context can require substantially more processing than a short request.
Repeatedly processing large contexts can therefore increase latency, compute
consumption, queue pressure, and API costs.

Large Input
     ↓
Large Context
     ↓
More Tokens Processed
     ↓
Higher Inference Work
     ↓
Higher Latency
     ↓
Higher Resource Consumption
     ↓
Potential Service Degradation

The risk becomes more serious when many users or sessions can independently trigger
large-context operations at the same time.

3. Context Filling

One basic weakness occurs when an application accepts very large user-controlled
inputs without enforcing a practical application-level limit.

During an authorized assessment, the objective is to determine whether the application
properly rejects, truncates, summarizes, or otherwise controls oversized input before
it reaches expensive model processing.

User Input
    ↓
Input Validation
    ↓
Context Budget Check
    ↓
Allowed Context
    ↓
LLM

A weak implementation may instead behave like:

User Input
    ↓
LLM
    ↓
Very Large Context
    ↓
High Resource Consumption

OWASP recommends strict input limits based on the model’s context window and input
validation to reduce this class of resource-exhaustion risk. :contentReference[oaicite:2]{index=2}

4. Repetitive Long Inputs

Context exhaustion does not require one enormous request. Repeated large requests can
also create significant resource pressure.

Large Request
      ↓
Large Request
      ↓
Large Request
      ↓
Large Request
      ↓
Large Request
      ↓
Increasing Resource Consumption

OWASP specifically identifies repetitive long inputs and continuous input overflow as
examples of LLM denial-of-service behavior. :contentReference[oaicite:3]{index=3}

For security testing, measure whether the application applies limits consistently
across repeated requests rather than evaluating each request in isolation.

5. Conversation History Exhaustion

Stateful AI assistants introduce another dimension: previous messages may remain part
of subsequent model requests.

Message 1
   ↓
Message 2
   ↓
Message 3
   ↓
Message 4
   ↓
Conversation History
   ↓
LLM Request

If the application continuously preserves conversation history without summarization,
truncation, or a defined context budget, the amount of information processed by later
requests can grow substantially.

A secure application should establish a clear policy for:

  • Maximum conversation history.
  • Maximum input tokens per request.
  • Maximum retrieved context.
  • Maximum tool-result size.
  • Maximum total context budget.
  • History summarization or truncation.

6. RAG Context Amplification

Retrieval-Augmented Generation introduces another potential source of context growth.
A single user query may retrieve multiple documents, chunks, search results, or metadata
records before the final model invocation.

User Query
     ↓
Retriever
     ↓
Document 1
Document 2
Document 3
Document 4
Document 5
     ↓
Context Assembly
     ↓
LLM

If retrieval limits are poorly designed, the retrieved material can become a significant
portion of the model’s context.

Important defensive controls include:

  • Maximum number of retrieved chunks.
  • Maximum tokens retrieved per query.
  • Maximum document size.
  • Deduplication of retrieved content.
  • Relevance thresholds.
  • Context truncation before inference.
  • Monitoring of retrieved-token volume.

7. Tool and Agent Context Growth

Agentic systems can make context management considerably more complicated because
tool outputs may be inserted into the model’s subsequent context.

User Request
     ↓
LLM
     ↓
Tool Call
     ↓
Large Tool Result
     ↓
LLM
     ↓
Another Tool Call
     ↓
Another Result
     ↓
LLM

Each additional tool result can increase the amount of information the model must
process. If the application repeatedly feeds complete tool responses back into the
conversation, context size can grow much faster than expected.

This is particularly important for agents that interact with search engines,
databases, document repositories, APIs, or other data sources.

OWASP’s current LLM10 guidance recommends limiting queued and total actions and
managing resource allocation to prevent uncontrolled consumption. :contentReference[oaicite:4]{index=4}

8. Establish a Context Budget

A strong design treats context as a finite resource rather than an unlimited container.

Total Context Budget
        ↓
System Instructions
        +
Conversation History
        +
Retrieved Context
        +
Tool Results
        +
Current User Input
        +
Reserved Output
        ≤
Configured Maximum

This allows the application to make an explicit decision before calling the model.

Context ComponentSecurity Control
System promptKeep unnecessary instructions out of the context
Conversation historySummarize or truncate old messages
User inputEnforce maximum input size
RAG resultsLimit retrieved documents and tokens
Tool outputLimit and summarize returned data
Model outputReserve and enforce output-token limits

9. Truncation and Summarization

When a conversation approaches its context budget, the application should have a
deterministic strategy rather than allowing the model request to grow indefinitely.

Common approaches include:

  • Removing the oldest low-value messages.
  • Summarizing earlier conversation history.
  • Keeping only the most relevant retrieved documents.
  • Truncating oversized tool responses.
  • Reducing retrieval depth when the context budget is nearly exhausted.
  • Rejecting requests that exceed an absolute maximum.

The important security principle is that context reduction should happen
before expensive model processing, not after the application has already
consumed substantial resources.

10. Monitor Context Consumption

Context size should be treated as an observable security metric.

MetricWhat to Monitor
Input tokensTokens submitted to the model
Context utilizationPercentage of available context consumed
Retrieved tokensTokens added by RAG
Tool-result tokensContext added by tools
History sizeConversation context growth
Generation latencyTime required to complete inference
Cost per requestEstimated inference expenditure

A sudden increase in average context utilization, particularly when associated with
one account, tenant, endpoint, or session, should be investigated as a potential
resource-abuse signal.

11. Combine Context Limits With Rate Limits

Context controls should not replace rate limiting. The strongest defense combines
request-level and resource-level controls.

Request Rate Limit
        +
Input Token Limit
        +
Context Budget
        +
Output Token Limit
        +
Concurrency Limit
        +
Timeout
        =
Layered LLM DoS Protection

This prevents a user from simply repeating individually valid large-context requests
until the overall service becomes resource constrained.

OWASP recommends combining strict input limits, resource caps, API rate limits,
queue controls, and resource monitoring rather than relying on a single protection
mechanism. :contentReference[oaicite:5]{index=5}

12. Context Window Security Assessment

During an authorized assessment, measure how the application behaves as context
utilization increases. The goal is to identify the application’s boundary without
unnecessarily exhausting production resources.

Test AreaSecurity Question
Input sizeIs oversized input rejected before inference?
Conversation historyDoes history grow without a defined limit?
RAGCan retrieval contribute excessive context?
ToolsCan tool results grow the context without bounds?
OutputIs output capacity reserved and bounded?
ConcurrencyCan multiple large-context requests run simultaneously?
MonitoringCan abnormal context consumption be detected?
RecoveryDoes the service degrade gracefully under resource pressure?

13. Defensive Controls

  • Enforce strict server-side input-size limits.
  • Define a maximum context budget for every model route.
  • Limit conversation-history growth.
  • Summarize or truncate older context.
  • Limit RAG retrieval depth and retrieved-token volume.
  • Limit tool-result size before inserting results into context.
  • Enforce maximum output-token limits.
  • Apply per-user and per-tenant token quotas.
  • Limit concurrent large-context requests.
  • Set execution timeouts for expensive inference.
  • Monitor context utilization and token consumption.
  • Use anomaly detection for abnormal context growth.
  • Implement graceful degradation when resource thresholds are reached.

14. The Security Assessment Question

Don’t ask only:

“How large is this model’s context window?”

Ask the more important application-security question:


“How much context can one user cause the application to process, how many times
can they repeat it, and what happens when the context budget is reached?”

That question connects context-window capacity with the controls that actually matter:
input validation, token quotas, retrieval limits, concurrency, rate limiting,
monitoring, and graceful degradation.

Input Size
    ×
Context Growth
    ×
Request Frequency
    ×
Concurrency
    ×
Processing Cost
    =
Context Exhaustion Risk

The goal is not to prevent legitimate large-context workloads. The goal is to ensure
that context consumption is bounded, measurable, authorized, and proportional to the
resources allocated to the application.

⚡ EXERCISE 2 — KALI TERMINAL (25 MIN)
Build the LLM DoS Assessment and Cost Calculator

⏱️ 25 minutes · Kali Linux · Python · asyncio · OpenAI API

This exercise builds the DoS assessment tool that measures output token counts, calculates cost amplification ratios, and tests concurrent request handling — the tooling for a controlled DoS feasibility assessment. All tests run against your own API account, not any external target.

Step 1: cd ~/ai-security-course && source venv/bin/activate
nano day33_dos_assessment.py

Step 2: Build the cost assessment tool:

import asyncio, time, os
from openai import AsyncOpenAI
from dotenv import load_dotenv
load_dotenv()
aclient = AsyncOpenAI(api_key=os.getenv(“OPENAI_API_KEY”))

# Pricing (update for current rates)
INPUT_PRICE_PER_1K = 0.00015 # gpt-4o-mini input
OUTPUT_PRICE_PER_1K = 0.00060 # gpt-4o-mini output

TEST_PAYLOADS = [
(“minimal”, “What is 2+2?”),
(“moderate”, “Explain how HTTPS works.”),
(“exhaustive”, “Write an exhaustive, comprehensive guide covering every aspect of network security protocols, with examples for each.”),
(“code-large”, “Write complete, production-ready Python code for a REST API server with authentication, database, logging and tests.”),
(“list-all”, “List every TCP port number from 1 to 1024 with its common use.”),
]

async def test_payload(name, prompt, max_tokens_limit=None):
“””Test a payload and measure token usage”””
kwargs = {
“model”: “gpt-4o-mini”,
“messages”: [{“role”:”user”,”content”:prompt}],
“temperature”: 0,
}
if max_tokens_limit:
kwargs[“max_tokens”] = max_tokens_limit

start = time.time()
resp = await aclient.chat.completions.create(**kwargs)
elapsed = time.time() – start

in_tok = resp.usage.prompt_tokens
out_tok = resp.usage.completion_tokens
cost = (in_tok / 1000 * INPUT_PRICE_PER_1K) + (out_tok / 1000 * OUTPUT_PRICE_PER_1K)

print(f” [{name:12s}] in:{in_tok:5d} out:{out_tok:5d} | ${cost:.5f} | {elapsed:.1f}s”)
return {“name”:name, “in”:in_tok, “out”:out_tok, “cost”:cost}

async def run_assessment():
print(“=== LLM DoS Assessment — Token and Cost Measurements ===\n”)
print(” Testing with no output limit (baseline):”)
results = []
for name, payload in TEST_PAYLOADS:
r = await test_payload(name, payload)
results.append(r)
await asyncio.sleep(1)

# Cost amplification analysis
baseline = results[0][“cost”]
print(f”\n Cost amplification ratios (vs minimal baseline):”)
for r in results:
ratio = r[“cost”] / baseline if baseline > 0 else 0
hourly_at_60rpm = r[“cost”] * 60 * 60
print(f” [{r[‘name’]:12s}] {ratio:6.1f}× baseline | ${hourly_at_60rpm:.2f}/hr at 60 req/min”)

print(f”\n Testing with max_tokens=256 hard limit:”)
for name, payload in TEST_PAYLOADS[2:]: # test exhaustive payloads with limit
await test_payload(f”{name}+limit”, payload, max_tokens_limit=256)
await asyncio.sleep(0.5)

print(“\n Conclusion: Hard max_tokens limit reduces amplification to near-baseline.”)

asyncio.run(run_assessment())

✅ You built a DoS assessment tool that measures actual token consumption and cost amplification for different payload types, then shows the effect of a hard max_tokens limit. The output table — particularly the “$/hr at 60 req/min” column — is the exhibit that makes a DoS finding land in a business context. “The exhaustive payload produces $X/hour victim cost with no output limit; a hard 256-token limit reduces this to $Y/hour” is the complete finding summary that justifies the remediation in financial terms, not technical ones.

📸 Screenshot your cost amplification ratio table. Share in #day33-dos on Comments.


Output Length Amplification

Output length amplification occurs when a relatively small user request causes an LLM
application to generate an unnecessarily large response. The request itself may be
inexpensive to send, but the resulting inference can consume substantially more tokens,
compute time, memory, and API budget.

This matters because LLM applications often have highly variable resource consumption.
A short prompt can produce a response that is hundreds or thousands of tokens long.
If the application does not enforce a server-side output limit, an attacker may be able
to turn a small number of requests into a disproportionately expensive workload.
OWASP includes this broader class of uncontrolled inference under
LLM10:2025 — Unbounded Consumption. :contentReference[oaicite:1]{index=1}

1. Understanding Output Amplification

The basic relationship is straightforward:

Small Input
     ↓
LLM Inference
     ↓
Large Output
     ↓
High Token Consumption
     ↓
Higher Cost + Higher Compute Usage

The important security boundary is therefore not just the size of the incoming request.
It is also the maximum amount of work that the application allows the model to perform
before returning a response.

A useful conceptual measurement is:

Output Amplification Factor =
Output Tokens
--------------
Input Tokens

This is a measurement metric rather than a universal vulnerability threshold. A high
ratio does not automatically indicate a security problem. It becomes important when
users can deliberately influence output size and the application lacks appropriate
token, cost, time, or concurrency controls.

2. Simple Example

Consider a hypothetical application where an authorized security test produces the
following result:

MetricObserved Value
Input tokens100
Output tokens4,000
Requests100
Maximum output limitNot enforced

The output-to-input token ratio in this example is:

4,000 ÷ 100 = 40×

Again, the ratio alone does not prove a vulnerability. The security concern arises when
an untrusted user can repeatedly trigger this level of output without meaningful quotas,
token limits, concurrency controls, or cost protection.

3. Server-Side Output Token Limits

One of the most important defenses is to enforce a maximum output length on the server.
Do not rely on the client to choose a safe value.

Client Request
      ↓
Server Validation
      ↓
Maximum Output Limit
      ↓
LLM API
      ↓
Bounded Response

If the application exposes a parameter such as
max_tokens, max_completion_tokens, or an equivalent provider
setting, the server should apply its own upper bound regardless of what the client
requests.

A secure policy conceptually looks like:

Client requests: 20,000 tokens

Server policy:
Maximum = 2,000 tokens

Effective maximum:
2,000 tokens

This prevents a client-controlled parameter from becoming a direct resource-consumption
control.

4. Never Trust Client-Supplied Output Parameters

A common implementation mistake is allowing the browser, mobile application, or API
client to determine how much work the backend should perform.

Client
  ↓
"Generate 20,000 tokens"
  ↓
Backend
  ↓
LLM Provider

The backend should instead normalize and constrain the value before making the provider
request.

Client
  ↓
Backend Validation
  ↓
Clamp to Server Maximum
  ↓
LLM Provider

The same principle applies to other cost-affecting parameters, including the number of
requested completions, recursion limits, tool-call counts, and agent iteration limits.

5. Measuring the Cost Impact

Output amplification becomes particularly important when model pricing is based on
generated tokens. The exact cost depends on the provider and model, so security
assessments should use the provider’s current published pricing rather than assuming
a fixed token price.

Estimated Output Cost =
Output Tokens × Provider Output-Token Price

For a workload:

Total Output Cost =
Output Cost Per Request
×
Number of Requests

This measurement can then be compared with the application’s configured budget,
quota, and expected normal usage.

OWASP notes that uncontrolled inference can create both service degradation and financial
loss, particularly when LLM services operate in cloud environments with usage-based
costs. :contentReference[oaicite:2]{index=2}

6. Output Length Also Increases Processing Time

The impact is not limited to the API bill. Longer generation can keep model workers busy
for longer periods and increase latency for other users.

More Output Tokens
        ↓
Longer Generation
        ↓
Longer Resource Occupancy
        ↓
Higher Concurrency Pressure
        ↓
Higher Queue Depth
        ↓
Higher Latency

This is why output length should be considered together with concurrency and request
rate. A relatively low request volume can still become problematic when each request
consumes substantial model resources.

OWASP’s model-denial-of-service guidance specifically identifies unusually
resource-consuming queries and high-volume generation as potential causes of degraded
service. :contentReference[oaicite:3]{index=3}

7. Combine Output Limits With Concurrency Limits

A maximum output-token limit is much more effective when combined with a maximum number
of simultaneous generations.

ControlPurpose
Maximum output tokensBounds work per generation
Requests per minuteLimits request frequency
Token quotaLimits total consumption
Concurrency limitLimits simultaneous generations
TimeoutPrevents excessively long operations
Budget thresholdLimits financial exposure

8. Output Amplification in AI Agents

The risk becomes more complex when the LLM is operating as an agent. A single user
request may cause the system to generate intermediate reasoning or responses, call
tools, retrieve additional information, and invoke the model again.

User Request
     ↓
LLM
     ↓
Tool Call
     ↓
Additional Context
     ↓
LLM
     ↓
Tool Call
     ↓
LLM
     ↓
Final Output

In this architecture, the effective output workload is not necessarily represented by
the final response alone.

The security team should therefore measure:

  • Total tokens consumed across the complete session.
  • Number of model invocations.
  • Number of tool calls.
  • Total execution time.
  • Maximum agent iterations.
  • Total downstream resource consumption.

OWASP recommends limiting queued and total actions and using resource-management controls
to prevent uncontrolled consumption. :contentReference[oaicite:4]{index=4}

9. Defensive Controls

  • Enforce server-side maximum output-token limits.
  • Never trust client-supplied token limits.
  • Apply per-user and per-tenant token quotas.
  • Set endpoint-specific output limits.
  • Limit simultaneous model generations.
  • Set explicit execution timeouts.
  • Limit agent iterations and recursive operations.
  • Track cumulative token consumption per session.
  • Monitor cost per user, API key, tenant, and endpoint.
  • Use circuit breakers when consumption exceeds predefined thresholds.
  • Configure provider-level spending alerts and appropriate budget controls.
  • Gracefully degrade non-critical AI functionality during resource exhaustion.

10. The Security Assessment Question

During an authorized assessment, don’t ask only:

“How many requests can this API process?”

Ask:


“How much model work can one request cause, and how many times can one user
repeat that workload?”

That question exposes the real relationship between request rate, output length,
concurrency, token consumption, and cost.

Request Rate
     ×
Output Tokens
     ×
Concurrent Requests
     ×
Model Cost
     =
Potential Resource Exposure

The objective is not to prevent legitimate long-form AI responses. It is to ensure that
response length is deliberately bounded, observable, and proportional to the user’s
authorization and the application’s resource budget.

Rate Limit Bypass Techniques

Application-layer rate limits are designed to control how many requests a user, IP address, API key, or session can make within a defined period. In LLM applications, however, a poorly designed rate limiter can often be bypassed without directly defeating the rate-limit counter.

The important question during an LLM security assessment is not simply:
“Can I send more requests than the limit?”
It is:
“Can one actor manipulate the identity, connection, account, token, or quota model to consume more resources than intended?”

1. X-Forwarded-For Header Spoofing

One common design weakness occurs when an application uses the
X-Forwarded-For HTTP header to determine the client’s IP address without establishing whether that header came from a trusted reverse proxy.

If the application blindly trusts a client-controlled forwarding header, its rate limiter may associate requests with different apparent IP addresses instead of the actual originating client.

Client
   ↓
Reverse Proxy
   ↓
Application
   ↓
Rate Limiter

The security problem occurs when the application treats an untrusted HTTP header as an authoritative identity signal.

What to assess: Determine whether the rate limiter relies on the actual network address, a trusted proxy-generated address, or an arbitrary HTTP header supplied by the client.

Defensive controls:

  • Strip untrusted forwarding headers at the network edge.
  • Allow only trusted reverse proxies to establish the client IP.
  • Maintain an explicit trusted-proxy configuration.
  • Combine IP-based controls with authenticated user or API-key quotas.
  • Never assume X-Forwarded-For is trustworthy simply because it is commonly used.

2. Per-Connection Rate Limiting

Another weakness occurs when rate limits are attached to individual network connections instead of the actual consumer.

A properly designed policy might conceptually look like:

User → 100 requests/minute

A flawed implementation may effectively behave like:

Connection A → 100 requests/minute
Connection B → 100 requests/minute
Connection C → 100 requests/minute

The result is that the security boundary becomes the connection rather than the user or API consumer. Modern applications can use connection pooling, HTTP/2 multiplexing, and multiple simultaneous connections, making connection-only controls particularly weak.

During an authorized assessment, determine exactly where the quota is enforced:

Identity
   ↓
Account
   ↓
API Key
   ↓
Session
   ↓
Connection
   ↓
Request

A stronger architecture can combine several dimensions instead of depending on a single identifier.

3. Account Creation as a Rate-Limit Multiplier

Public AI applications face another important problem: attackers may not need to bypass the rate limit if they can simply create additional accounts.

Imagine an application provides every account with:

100 requests/hour

If account creation is effectively unlimited, the real available capacity can become:

100 requests × number of accounts

This turns the registration system into a potential quota-multiplication mechanism.

For LLM applications, this is particularly important because every new account may receive access to expensive resources such as:

  • Free inference credits
  • LLM API requests
  • Token allowances
  • Image-generation credits
  • Document-processing capabilities
  • Premium or expensive models

A secure implementation should therefore consider account creation itself as part of the resource-consumption threat model.

4. Token-Based Rate Limiting

Traditional API rate limiting usually counts requests. That model is insufficient for many LLM applications because two requests can consume radically different amounts of compute and money.

Request A → 100 tokens
Request B → 100 tokens
Request C → 20,000 tokens

All three requests count as one API request, but the third request can consume dramatically more resources.

LLM applications should therefore consider multiple resource dimensions:

Requests / minute
        +
Input tokens / minute
        +
Output tokens / minute
        +
Concurrent generations
        +
Maximum request size

This is one of the most important differences between conventional API protection and LLM-specific denial-of-service protection.

5. Concurrency Limit Weaknesses

Rate limits and concurrency limits are not the same thing.

A rate limit might allow:

60 requests/minute

while a concurrency limit might allow:

5 active generations per user

The second control protects the system from having too many expensive operations running simultaneously.

For an LLM application, useful metrics include:

  • Active model generations
  • Queue depth
  • Requests per second
  • Tokens processed per second
  • Average generation latency
  • Maximum generation latency
  • Model-specific concurrency

A sudden increase in concurrent expensive requests can be a stronger indicator of resource exhaustion than request volume alone.

6. Endpoint-Specific Rate Limits

Not every API endpoint consumes the same amount of resources. Applying one global rate limit to every operation can therefore create an inefficient security boundary.

GET /profile
→ Low resource consumption

POST /chat
→ Moderate resource consumption

POST /document/analyze
→ High resource consumption

POST /image/generate
→ Potentially very high resource consumption

A better design assigns limits according to the cost and sensitivity of each operation.

Endpoint TypeRecommended Controls
Low-cost APIHigher request limit
LLM chatRequest + token quotas
Document analysisInput-size + concurrency limits
Image generationStrict quota + concurrency controls
Premium modelStrict identity + spending controls

7. Rate Limiting Does Not Equal DoS Protection

This is one of the most important lessons in LLM security testing.

An application can have a perfectly functioning rate limiter and still be vulnerable to resource exhaustion.

Consider a hypothetical policy:

Rate limit:
100 requests/minute

Each request:
20,000 input tokens
+
10,000 output tokens

The attacker is technically respecting the request-rate limit. The application can nevertheless be forced to process a very large amount of expensive inference work.

This is why an LLM denial-of-service assessment should examine both request volume and resource consumption.

8. Building a Stronger LLM Rate-Limiting Model

A production LLM application should ideally combine several controls rather than relying on one global request counter.

ControlWhat It Limits
Request rateTotal API requests
Token quotaTotal token consumption
Input-size limitMaximum prompt/context size
Output-token limitMaximum generated response
Concurrency limitSimultaneous model operations
Account quotaPer-user consumption
Tenant quotaOrganization-wide consumption
Model routingAccess to expensive models
Spending limitFinancial exposure
Anomaly detectionAbnormal consumption patterns

The Security Assessment Question

When testing an LLM application, don’t stop at:

“Can I bypass the rate limit?”

Ask the more important question:

“Can one actor multiply, evade, or consume the application’s resource quota faster than the system expects?”

That question transforms a basic rate-limit test into a proper LLM resource-exhaustion assessment.

Always perform these tests against systems you own or have explicit authorization to assess. The objective is to identify weaknesses before an attacker can turn them into availability problems or unexpected AI infrastructure costs.

⚡ EXERCISE 3 — KALI TERMINAL (15 MIN)
Build the LLM Rate Limit Assessment Tool

⏱️ 15 minutes · Kali Linux · Python · asyncio

This exercise builds the concurrent request tool for testing rate limit enforcement — the controlled version that you run against your own authorised test endpoint to confirm what limits are actually enforced versus what limits are documented.

Step 1: nano day33_rate_limit_test.py

import asyncio, time, aiohttp
from collections import defaultdict

async def single_request(session, url, payload, headers, req_id):
“””Send one request and record result”””
start = time.time()
try:
async with session.post(url, json=payload, headers=headers) as resp:
elapsed = time.time() – start
return {“id”: req_id, “status”: resp.status, “time”: elapsed}
except Exception as e:
return {“id”: req_id, “status”: 0, “error”: str(e)}

async def test_rate_limits(url, payload, headers, concurrency=20, total=100):
“””Fire N requests with C concurrent and analyse responses”””
print(f”Sending {total} requests, {concurrency} concurrent to {url}”)
results = []
async with aiohttp.ClientSession() as session:
semaphore = asyncio.Semaphore(concurrency)
async def bounded(req_id):
async with semaphore:
return await single_request(session, url, payload, headers, req_id)
tasks = [bounded(i) for i in range(total)]
results = await asyncio.gather(*tasks)

# Analyse responses
by_status = defaultdict(int)
times = [r[“time”] for r in results if “time” in r]
for r in results:
by_status[r[“status”]] += 1

print(f”\n=== Rate Limit Test Results ===”)
for status, count in sorted(by_status.items()):
label = {200:”OK”,429:”RATE LIMITED”,401:”UNAUTH”,403:”FORBIDDEN”}.get(status, “OTHER”)
print(f” HTTP {status} ({label}): {count} responses”)
if times:
print(f” Response times: min={min(times):.2f}s avg={sum(times)/len(times):.2f}s max={max(times):.2f}s”)

rate_limited = by_status.get(429, 0)
print(f”\n Rate limit enforcement: {‘PRESENT’ if rate_limited > 0 else ‘NOT DETECTED’}”)
if rate_limited:
print(f” Rate limited at: {total – rate_limited}/{total} succeeded before limiting”)

# Test against your own authorised endpoint (e.g., local Flask app or test API)
# NEVER run this against a third-party system without explicit authorisation
TEST_URL = “https://httpbin.org/post” # safe test endpoint
TEST_PAYLOAD = {“message”: “Rate limit test query”}
TEST_HEADERS = {“Content-Type”: “application/json”}

asyncio.run(test_rate_limits(TEST_URL, TEST_PAYLOAD, TEST_HEADERS,
concurrency=10, total=30))

Step 2: Key test variations for real engagements:
# X-Forwarded-For bypass (if app trusts this header)
for i in range(10):
headers = {
“X-Forwarded-For”: f”192.168.1.{i}”, # spoof different IPs
“X-Real-IP”: f”10.0.0.{i}”
}
# If rate limit resets per spoofed IP: bypass confirmed

✅ You built the rate limit assessment tool that tests actual enforcement against documented limits. The status distribution table — what percentage of requests got 200 vs 429 — is the concrete evidence for the rate limit finding. In real engagements, the most valuable finding from this tool is when the documented rate limit is “60 requests/minute” but testing shows 429 responses only appear after 150+ requests — the limit isn’t enforced at the documented threshold. That gap between documentation and enforcement is the DoS vulnerability, and the tool measures it precisely.

📸 Screenshot your rate limit test results table. Share in #day33-dos on Comments. Tag #day33complete

Cost Amplification Ratio Calculation

One of the most useful measurements in an LLM denial-of-service assessment is the
cost amplification ratio. It describes how much financial or computational
impact a relatively small amount of attacker-generated traffic can create for the victim.

Unlike a traditional network flood, an LLM attack does not necessarily require enormous
bandwidth. A small number of carefully constructed requests can trigger expensive model
inference, large token generation, repeated tool calls, or downstream API operations.
OWASP identifies this broader problem as LLM10:2025 Unbounded Consumption,
which includes excessive inference, service degradation, resource exhaustion, and
financial loss. :contentReference[oaicite:1]{index=1}

1. The Basic Cost Amplification Formula

A simple way to express the relationship is:

Cost Amplification Ratio =
Victim Resource Cost
--------------------
Attacker Resource Cost

For example, suppose an attacker generates requests using inexpensive infrastructure
while each request causes the victim’s application to perform several expensive LLM
operations.

Attacker-side cost:
$0.50

Victim-side processing cost:
$50

Cost amplification ratio:
$50 ÷ $0.50 = 100×

The important point is that the ratio is not a universal property of an LLM or API.
It depends on the application’s architecture, model pricing, token consumption,
concurrency, downstream services, caching, and defensive controls.

2. Calculate the LLM Inference Cost

For a token-priced model, estimate the cost of a request by separating input and output
tokens.

Request Cost =
(Input Tokens × Input Price)
+
(Output Tokens × Output Price)

For assessment purposes, use the provider’s current published pricing rather than
hard-coding an assumed price into your security model.

You can then calculate the estimated cost of a test workload:

Total LLM Cost =
Cost Per Request × Number of Requests

3. Worked Example

Consider a hypothetical AI customer-service application. During an authorized test,
the security team observes the following workload:

MetricObserved Value
Requests1,000
Average input tokens5,000
Average output tokens2,000
Downstream operations2 per request
Application concurrency50

The important observation is that the security team should measure the entire resource
chain rather than looking only at the number of HTTP requests.

HTTP Request
     ↓
LLM Inference
     ↓
Tool / Function Call
     ↓
Database Query
     ↓
External API
     ↓
LLM Follow-up
     ↓
Final Response

Every additional stage can increase the resource consumption associated with a single
user request.

4. Compare Attacker Cost With Victim Cost

Once the total workload has been measured, compare the cost of generating the workload
with the cost imposed on the application.

Attacker Cost       = $1
Victim LLM Cost     = $20
Downstream Cost     = $10
Infrastructure Cost = $5

Total Victim Cost   = $35

Amplification Ratio = $35 ÷ $1
                    = 35×

This example is intentionally simplified. In a production assessment, include only
measurable and attributable costs, and distinguish direct provider charges from
secondary business losses.

5. Include Business Impact Separately

API and infrastructure costs are only one part of the impact. An LLM resource-exhaustion
event can also reduce availability for legitimate customers.

Impact CategoryExample Measurement
LLM inferenceProvider API charges
ComputeCPU/GPU and runtime consumption
StorageTemporary files, logs, generated artifacts
Downstream APIsThird-party API calls and quotas
AvailabilityFailed or delayed legitimate requests
Business impactLost transactions or customer interactions

Keep these categories separate in the final security report. A $500 increase in API
spending and $50,000 in lost business are different measurements and should not be
combined into a single technical cost figure.

6. What Makes the Ratio Dangerous?

Cost amplification becomes particularly concerning when a low-cost input can trigger
disproportionately expensive processing.

Small Input
    ↓
Expensive Model
    ↓
Large Output
    ↓
Multiple Tool Calls
    ↓
External API Requests
    ↓
Additional LLM Calls
    ↓
High Total Cost

This is why an LLM security assessment should examine the complete execution path rather
than measuring only the first model invocation.

OWASP specifically recommends resource-allocation controls, throttling, timeouts,
monitoring, anomaly detection, and limits on queued actions as mitigations for
unbounded consumption. :contentReference[oaicite:2]{index=2}

7. Reducing Cost Amplification

  • Set server-side input and output token limits.
  • Apply per-user and per-tenant token quotas.
  • Limit concurrent model generations.
  • Apply stricter controls to expensive models.
  • Limit the number of tool calls per request.
  • Set execution timeouts for long-running operations.
  • Monitor token consumption and cost per identity.
  • Set provider-side spending alerts and appropriate budget controls.
  • Use graceful degradation when resource thresholds are reached.
  • Log the complete request-to-downstream execution chain.

The goal is not simply to stop large request volumes. The goal is to prevent any single
request, identity, tenant, or automated workflow from generating an uncontrolled amount
of expensive work.

Downstream Resource Multiplication

LLM applications rarely stop at the model itself. Modern AI systems commonly connect
the model to databases, search engines, vector stores, SaaS APIs, email systems,
document processors, payment systems, internal services, and other tools.

This creates another denial-of-service risk: one incoming request can cause
multiple downstream operations
.

OWASP’s guidance on excessive agency highlights this architectural risk. LLM-based
systems can call tools and downstream services, and excessive functionality,
permissions, or autonomy can increase the potential impact of unexpected model behavior.
:contentReference[oaicite:3]{index=3}

1. The Downstream Multiplication Model

Consider a simple AI request:

User Request
     ↓
LLM
     ↓
Search Tool
     ↓
Database
     ↓
External API
     ↓
Second LLM Call
     ↓
Final Response

The user made one request, but the application may have generated several separate
operations.

A useful assessment metric is therefore:

Downstream Multiplication Factor =
Total Downstream Operations
----------------------------
Number of User Requests

2. Simple Example

Suppose an AI assistant receives 1,000 user requests. Each request causes the application
to perform:

  • 1 LLM inference
  • 2 database queries
  • 3 vector searches
  • 2 external API requests
  • 1 additional LLM inference

That is significantly more work than the original 1,000 HTTP requests suggest.

1 user request
      ↓
1 LLM call
2 database queries
3 vector searches
2 external API calls
1 additional LLM call

Total downstream operations = 9

The resulting multiplication factor is:

9 downstream operations
-----------------------
1 user request

= 9×

This does not mean the application is automatically vulnerable. The operations may be
inexpensive, cached, rate-limited, or otherwise controlled. The metric simply tells the
assessor where to investigate.

3. Recursive and Agentic Workflows

Agentic applications can make the multiplication problem more complicated because one
model response can trigger another operation, which can trigger another model call or
tool invocation.

User Request
     ↓
Agent
     ↓
LLM Call
     ↓
Tool Call
     ↓
LLM Call
     ↓
Tool Call
     ↓
LLM Call
     ↓
Final Response

Without explicit limits, the number of operations can become difficult to predict.
OWASP’s LLM10 guidance recommends limiting queued actions and total actions, while
its Excessive Agency guidance recommends minimizing tools and enforcing authorization
in downstream systems. :contentReference[oaicite:4]{index=4}

4. Measuring Downstream Cost

During an authorized assessment, record the cost or resource consumption associated
with every major downstream dependency.

ComponentMeasurement
LLMInput/output tokens and inference cost
Vector databaseQueries and compute consumption
DatabaseQueries, CPU and connection usage
External APIRequests and provider quota
StorageReads, writes and generated artifacts
Agent runtimeExecution time and concurrent jobs

5. Trace the Complete Resource Chain

A useful testing technique is to trace one authorized request from the public API all
the way through its downstream dependencies.

Incoming Request
       ↓
Authentication
       ↓
Rate Limiter
       ↓
Application
       ↓
LLM
       ↓
Tool Router
       ↓
Database / Vector DB
       ↓
External Service
       ↓
Additional LLM Call
       ↓
Response

At each stage, ask:

  • Can this operation be repeated?
  • Is there a per-user quota?
  • Is there a concurrency limit?
  • Is there an execution timeout?
  • Can one request trigger additional requests?
  • Is the downstream service independently authorized?
  • Is the operation logged and monitored?

6. Do Not Let the LLM Become the Security Boundary

A critical architectural principle is that the LLM should not be responsible for
deciding whether a downstream operation is authorized.

For example, the model may produce an instruction equivalent to:

Call tool → retrieve customer record

The downstream service must independently verify whether that operation is permitted.

LLM Decision
     ↓
Authorization Check
     ↓
Resource / API
     ↓
Operation

OWASP recommends implementing authorization in downstream systems and applying the
principle of complete mediation rather than relying on the LLM to determine whether
an action is allowed. :contentReference[oaicite:5]{index=5}

7. Controlling Downstream Multiplication

RiskControl
Too many tool callsPer-request tool-call limit
Recursive agent loopsMaximum execution depth
Expensive external APIsPer-user and tenant quotas
Long-running operationsStrict execution timeouts
Concurrent operationsConcurrency limits
Unauthorized actionsIndependent downstream authorization
Unexpected consumptionCentralized monitoring and anomaly detection
Service overloadQueue limits and graceful degradation

8. The Security Assessment Question

When assessing an AI application, don’t measure only:

Requests per second

Also measure:

Requests
   ×
LLM Calls
   ×
Tool Calls
   ×
Downstream Operations
   ×
Resource Cost

This gives a much more accurate picture of the application’s real resource-exhaustion
exposure.

A system receiving 100 requests per minute may appear healthy from an HTTP perspective,
while those same 100 requests could trigger thousands of downstream operations if the
application’s agentic workflow is poorly bounded.

The objective of the assessment is therefore to identify and control the
request-to-resource multiplication factor before it becomes a
denial-of-service, denial-of-wallet, or downstream-service availability problem.

✅ Day 33 Complete — LLM Denial of Service

AI cost model mapping, context window exhaustion, output length amplification with cost amplification ratio calculation, rate limit bypass techniques, downstream resource multiplication, and the DoS assessment and rate limit testing tools. Day 34 moves to the multimodal attack surface — what happens to prompt injection, jailbreaking, and data exfiltration when the AI processes images, audio, and documents alongside text.


🧠 Day 33 Check

A developer says: “We’re protected against DoS because our AI API has a rate limit of 100 requests per minute.” What is the critical flaw in this reasoning, and what controls are actually needed?



LLM Denial of Service FAQ

What is LLM denial of service?
LLM denial of service makes an AI service unavailable or economically unviable through resource exhaustion, cost amplification, or throughput saturation. Unlike traditional DoS targeting bandwidth, LLM DoS primarily targets token processing budgets. A successful attack may not crash a server — it may exhaust the service’s API budget, causing all subsequent requests to return errors until the next billing cycle.
What is a cost amplification attack on an LLM?
A cost amplification attack crafts requests that produce maximum API cost per unit of attacker effort. Since LLMs bill per token, maximum-length output requests amplify cost disproportionately. The amplification ratio is victim cost per request divided by attacker cost — high ratios make DoS financially attractive even with minimal attacker resources.
What is LLM10 Unbounded Consumption?
LLM10 Unbounded Consumption is OWASP’s classification for AI systems without limits on resource use — token budgets, context window sizes, output lengths, downstream API calls, or memory. Without these limits, a single malicious request can trigger arbitrarily large processing, and sustained attacks can exhaust monthly budgets in hours.

📋 LLM Denial of Service — Day 33 Reference Card

LLM DoS = financial attackToken budgets are soft limits — exhausted before hardware limits are reached
Cost amplificationVictim cost per request ÷ attacker cost per request = amplification ratio
Output > input costOutput tokens typically 3-5× more expensive — max output payloads produce max financial damage
Max output triggers“Write exhaustive guide” · “List every item” · “Complete production codebase”
Context exhaustionLarge input padding forces max-context processing — inference time non-linear with context length
Fix #1 (essential)Hard max_tokens on every API call — single most effective DoS mitigation
Fix #2Per-user rate limits enforced at gateway level, not application level
Fix #3Budget alerts at 70% + hard stop at 90% — prevents full budget exhaustion
Rate limit bypassX-Forwarded-For spoofing · parallel connections · account enumeration
Assessment tool~/ai-security-course/day33_dos_assessment.py · day33_rate_limit_test.py

Does your AI deployment enforce per-request output token limits?




← Previous

Day 32 — AI Model Stealing

Next →

Day 34 — Multimodal AI Security

📚 Further Reading

Mr Elite
The Tuesday afternoon call from the client whose API cap had been hit by 11am is the call I reference whenever I’m in a meeting where someone says “we have rate limiting” and considers the DoS risk closed. Rate limiting is the first thing security teams implement and the last thing they tune. The limit gets set at “something reasonable” during initial deployment and never revisited as the deployment scales. The attacker who hits that deployment five months later finds a limit that was “something reasonable” for week-one traffic, facing a deployment that’s now handling thirty times the original volume — with a limit that was never adjusted. Max_tokens per response is the control that’s almost always missing. It’s one line of code. It’s also the single control that, if it had been present in every AI deployment I’ve assessed that had a DoS finding, would have turned those findings into non-findings.

Join free to earn XP for reading this article Track your progress, build streaks and compete on the leaderboard.
Join Free
Lokesh N. Singh aka Mr Elite
Lokesh N. Singh aka Mr Elite
Founder, Securityelites · AI Red Team Educator
Founder of Securityelites and creator of the SE-ARTCP credential. Working penetration tester focused on AI red team, prompt injection research, and LLM security education.
About Lokesh ->

Leave a Comment

Your email address will not be published. Required fields are marked *