Token counting is performed before API calls to prevent hard limit errors
Why it matters
Sending an oversized payload to the AI API is never free — even when the provider rejects it. The request consumes a full network round-trip, counts toward rate limit quotas on some configurations, and surfaces to the user as a generic 500 error rather than an actionable message. CWE-770 and CWE-400 both apply: unguarded resource allocation with no application-side limit check. NIST AI RMF MANAGE 1.3 requires predictable failure modes; a silent hard crash on context overflow is the opposite. A pre-flight guard converts this crash into a recoverable, user-friendly state.
Severity rationale
High because without a pre-flight guard, context overflow errors surface as generic failures — burning rate limit quota and giving users no actionable recovery information.
Remediation
Add a synchronous token check before every AI call that returns a structured 422 response when the payload would exceed the model's limit. Reserve headroom for the expected response length.
// src/app/api/chat/route.ts
const RESPONSE_RESERVE = 1000;
const totalTokens = countMessageTokens([
{ role: "system", content: systemPrompt },
...boundedMessages,
], model);
if (totalTokens > MODEL_CONFIG[model].contextWindow - RESPONSE_RESERVE) {
return Response.json(
{ error: "Conversation is too long. Please start a new chat to continue." },
{ status: 422 }
);
}
Verify by constructing a payload that exceeds the limit and confirming the UI displays the specific error rather than a generic failure screen.
DetectionPro
The detection method for this pattern is part of AuditBuffet Pro.
The full method (what to look for, pass and fail conditions, and how results get reported) ships inside the AI Token Optimization Audit. The pattern definition, severity rationale, and remediation remain openly licensed under CC-BY-4.0.
External references
- owasp-llm:2025 · LLM10 — Unbounded Consumption
- cwe · CWE-770 — Allocation of Resources Without Limits or Throttling
- cwe · CWE-400 — Uncontrolled Resource Consumption
- nist-ai-rmf:1.0 · MANAGE 1.3 — Responses to identified AI risks are developed
- iso-25010:2011 · reliability.fault-tolerance — Fault Tolerance — pre-flight guard prevents context-overflow crashes
Taxons
History
- 2026-04-18·v1.0.0·Initial import from ai-token-optimization·automated