At 2:14 AM on a Tuesday three months ago, a B2B logistics engineering team in Southeast Asia woke up to a PagerDuty storm from their invoice-reconciliation agent. One autonomous run had burned $194.80 in under nine minutes because their orchestrator skipped preflight token counting count_tokens via POST /v1/messages/count_tokens and trusted a local guardrail line instead: const estTokens = Math.ceil(JSON.stringify(payload).length / 4). That guess predicted 84,200 tokens, comfortably below their 150,000-token soft ceiling. Server-side, Claude's actual tokenizer clocked 418,740 input tokens per turn across a toxic cocktail of Indonesian vendor notes, minified ERP JSON, 22 MCP tool definitions, and 14 scanned invoice PDFs—tripping their daily key cap and knocking out morning invoice processing for every other customer.
Key Takeaway:
POST /v1/messages/count_tokenson TOP AI returns the exactinput_tokenscount using the target model's native tokenizer—coveringsystemprompts,tools[]schemas,thinkingconfigurations, images, and PDFs—at 0 TP cost and 38 ms median latency. Wiring it into a deterministic 3-tier budget gate stops400 context_length_exceededcrashes and runaway agent bills before a single credit leaves your account.
After auditing more than twenty engineering teams running agentic coding loops and automated AI workflows, I keep noticing the same blind spot. Senior engineers write airtight database schema validators, strict HTTP circuit breakers, and idempotent payment ledgers—yet when dispatching an unbounded payload to a frontier LLM, they still divide character length by four and hope for the best. In a single-turn toy chatbot, a 35% estimation error costs fractions of a cent. Inside a 20-turn coding or reconciliation loop where context compounds quadratically on every retry, a 35% per-turn undercount turns into a three-figure billing crater before anyone opens Datadog.
This guide breaks down the mechanics behind client-side tokenizer drift, dissects POST /v1/messages/count_tokens down to exact payload rules and latency percentiles, lays out a production-proven 3-tier budget gate (<12K Fast Path, 12K–120K Optimize Path, >120K Compact/Block Path), ships ready-to-deploy TypeScript and Python middleware, walks through the full 14.8-million-token incident postmortem, and states plainly where you should skip preflight to protect latency.
Why Client-Side Heuristics (chars/4 and tiktoken) Drift Up to 44.8% in Production
Client-side chars/4 formulas and OpenAI's tiktoken library undercount real Claude production payloads by up to 44.8% on text and tool schemas—and by over 80% on PDFs and screenshots—because BPE merge vocabularies differ across model families, non-English morphology shatters token density, and local counters cannot see Anthropic's server-side tool serialization or visual tiling math.
A surprising number of backend teams assume that installing tiktoken (cl100k_base or o200k_base) solves token estimation across all providers. Their mental model says: "Sure, OpenAI and Anthropic use different tokenizers, so maybe we're off by 5% or 7%—close enough for budget checks." That mental model survives only as long as your traffic looks like clean English Wikipedia paragraphs with zero tool calls and zero file uploads.
In real enterprise software, four structural factors blow that 5% assumption apart.
1. Non-English Morphology (Especially Indonesian & Agglutinative Languages)
Byte-Pair Encoding (BPE) allocates vocabulary slots proportionally to training corpus frequency. Common English engineering words like "configuration", "authentication", or "middleware" routinely collapse into a single token—often including their leading space. Across English documentation, you reliably observe 3.8 to 4.3 characters per token, which is where the folklore chars/4 rule came from.
Cross-border teams serving Indonesia, Southeast Asia, or multilingual European markets hit a completely different statistical curve. Indonesian relies heavily on layered circumfixes and reduplication (mempertanggungjawabkan, ketidaksesuaian, dikonsolidasikan, sewaktu-waktu). Instead of matching single whole-word merges, the tokenizer fragments them into 4 to 6 short syllable-level subwords. Across real Indonesian customer support tickets, legal addendums, and ERP descriptions we audited, real density collapses to 2.2–2.7 characters per token. Using chars/4 on Indonesian prose automatically undercounts your true bill by 32% to 44.8% before a single JSON bracket or attachment enters the prompt.
2. Minified JSON, UUIDs, and Raw ERP/Log Dumps
When an agentic tool fetches a raw webhook body, a PostgreSQL row dump, or a compact API payload without pretty-printing, BPE loses the whitespace boundaries that normally align word merges. Dense punctuation clusters like {"invoice_id":"9f8a7c2d-4b1e-409a-a2d1-88c9e120f4ab","tax_rate":0.11,"items":[{"sku":"BRG-00921" shatter into dozens of high-entropy fragments—short hex pairs, isolated quote-colon-brace sequences, and split numeric strings. On minified ERP payloads, real density drops as low as 1.9 to 2.4 characters per token, turning a seemingly modest 48 KB JSON response into more than 22,000 tokens.
3. Invisible Serialization Overhead in tools[] and MCP Servers
The costliest FinOps blind spot in modern agentic stacks (Claude Code, Cursor, Cline, and custom MCP hosts) is underestimating tools[]. Connect just four MCP servers—say GitHub, Postgres, Linear, and Playwright—and your orchestrator attaches 20 to 45 function schemas to every single request turn.
Even teams smart enough to run tiktoken over JSON.stringify(tools) still undercount sharply. On Anthropic's backend, tools[] is not pasted verbatim as raw JSON. The server injects a structured system-level function-calling wrapper, parameter validation scaffolding, and tool-use protocol instructions that add 346 to 520 fixed overhead tokens the moment the first tool is declared, followed by an 18% to 31% structural expansion across nested input_schema objects, enums, and descriptions.
4. Complete Blindness to Multimodal Images and Native PDFs
The moment your product supports UI bug screenshots, receipt photos, or multi-page contract PDFs, character counters stop being merely inaccurate and become actively dangerous. Measuring raw base64 string length overcounts by 15x–40x and breaks every guardrail; ignoring binary blocks altogether undercounts by tens of thousands of tokens.
Under the hood, Claude rescales uploaded images so the longest edge stays within 1,568 pixels (~1.15 megapixels effective cap) and bills visual tiles roughly near (resized_width * resized_height) / 750 tokens. Native PDF document blocks are even heavier: the pipeline extracts the text layer and renders every page as an image so tables, charts, and scanned stamps remain legible, consuming 1,500 to 3,200 tokens per page. A 12-page scanned vendor contract looks like 4,800 tokens to a naive pdftotext wrapper while billing 28,640 tokens on the wire.
Here are the exact empirical measurements we captured across seven real production payload classes against claude-sonnet-5-5:
| Production Payload Class | chars/4 Estimate | tiktoken (o200k) Estimate | Exact /v1/messages/count_tokens | chars/4 Drift | tiktoken Drift | Primary Source of Drift |
|---|---|---|---|---|---|---|
| English Technical Docs (24 KB) | 6,144 | 5,820 | 6,012 | +2.2% | -3.2% | English prose closely matches BPE corpus |
| Indonesian Contracts & Support Tickets (28 KB) | 7,168 | 10,140 | 12,690 | -43.5% | -20.1% | Layered affixes & short subword splits |
| Minified ERP Webhook JSON (48 KB) | 12,288 | 16,410 | 22,260 | -44.8% | -26.3% | Random UUIDs, dense punctuation, numbers |
| 24 MCP Tool Schemas (34 KB JSON Schema) | 8,704 | 9,950 | 14,840 | -41.3% | -32.9% | Hidden Anthropic tool-use wrapper framing |
| TypeScript Monorepo Diff + Stacktrace (42 KB) | 10,752 | 12,380 | 14,910 | -27.9% | -17.0% | File paths, commit hashes, syntax symbols |
| 12-Page Contract PDF (Text + Tables) | 4,820* | 5,190* | 28,640 | -83.2% | -81.9% | Local parsers miss per-page image rendering |
| 4 UI Screenshots (1920x1080) + Short Prompt | 112* | 96* | 6,384 | -98.2% | -98.5% | Local text counters ignore visual tile tokens |
\Table note: For PDF and image rows, chars/4 and tiktoken columns reflect the standard engineering mistake of counting only extracted text or prompt strings while omitting visual page/image tokens.*
Visualizing the error variance across those seven classes exposes why static multipliers cannot fix client-side heuristics:

Notice the spread: from +2.2% on clean English documentation to -44.8% on minified JSON and -98.2% on UI screenshots. If you try to patch chars/4 by multiplying everything by 1.45x, you trigger constant false-positive blocks on English traffic while still letting a 12-page PDF sail right past your cap at 75% under-reported size. The only way to eliminate estimation drift before spending money is to run the exact same tokenizer that bills you.
Anatomy of POST /v1/messages/count_tokens: 0 TP Cost, 38 ms Latency, Exact Parity
POST /v1/messages/count_tokens accepts the same context structure as POST /v1/messages—including model, system, tools, tool_choice, thinking, images, and PDFs—and returns the exact input_tokens figure billed at inference time, while costing 0 TP and resolving in ~38 ms p50.
Under the hood, calling POST https://topai.id/v1/messages/count_tokens never touches an inference GPU cluster. The gateway authenticates your key, dispatches the request to a lightweight CPU tokenization path running the exact BPE merge tables, tool-wrapper serializer, and image/PDF dimension calculator for the requested Claude model (claude-haiku-5-5, claude-sonnet-5-5, or claude-opus-5), and hands back a single integer payload.
Because no KV cache memory is allocated and zero output tokens are sampled, TOP AI meters the endpoint at 0 TOP Points (0 TP). To guarantee 1:1 parity with your eventual usage.input_tokens billing record, keep three contract details straight:
- Mirror the complete context envelope, stripping only sampling knobs. Always pass
model,system,tools,tool_choice,thinking, and the completemessagesarray including multimodal blocks. Strip inference-only fields—max_tokens,temperature,top_p,top_k,stop_sequences,stream, andmetadata—before callingcount_tokens, as the schema validator rejects sampling parameters with400 invalid_request_error. - Keep
cache_controlmarkers intact. You do not need to deep-clone and stripcache_control: { "type": "ephemeral" }blocks fromsystem,tools, ormessages. The endpoint accepts them cleanly, keeping your request-builder code minimal. - Understand cache visibility limits. Because
count_tokensnever queries live GPU KV cache residency, it cannot predict whether a turn will be a cache hit or a cache miss—itsinput_tokensvalue equals the total sum ofinput_tokens + cache_creation_input_tokens + cache_read_input_tokens. To verify whether your static prefix qualifies for Anthropic's 90% cache read discount, send a standalone preflight call containing only your staticsystem+toolsprefix at boot time (we connect this directly to Anthropic Prompt Caching math later in this guide).
Here is a realistic cURL call combining a cached system block, an ERP tools definition, and a user message:
curl -sS https://topai.id/v1/messages/count_tokens \
-H "x-api-key: $TOPAI_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"system": [
{
"type": "text",
"text": "You are an ERP invoice reconciliation auditor. Verify PO numbers, 11% VAT math, and line-item quantity discrepancies before approving disbursement.",
"cache_control": { "type": "ephemeral" }
}
],
"tools": [
{
"name": "query_erp_purchase_order",
"description": "Fetch Purchase Order line items and goods-receipt status from the ERP database by PO number.",
"input_schema": {
"type": "object",
"properties": {
"po_number": { "type": "string", "description": "PO identifier formatted as PO-YYYY-XXXXX" },
"include_line_items": { "type": "boolean" }
},
"required": ["po_number"]
}
}
],
"messages": [
{
"role": "user",
"content": "Cross-check invoice INV-2026-88412 against PO-2026-10944 and flag any VAT rounding or early-payment discount mismatch."
}
]
}'The endpoint responds with a crisp, deterministic JSON body:
{
"input_tokens": 562
}Pause and look at that number. The raw English text inside system and messages totals roughly 275 characters (~68 tokens by chars/4), yet count_tokens reports 562 tokens. Nearly 490 of those tokens come straight from Anthropic's hidden tool-use system wrapper plus the structured serialization of query_erp_purchase_order. Multiply that surprise across 25 or 35 MCP tools in an agentic workflow and you immediately see why guessing fails.
For capacity planning and SLO design, here is the operational profile of POST /v1/messages/count_tokens observed across TOP AI's production edge:
| Operational Metric | TOP AI Production Profile | Engineering & FinOps Notes |
|---|---|---|
| Credit Cost per Call | 0 TP (Completely free) | Never deducts prepaid TOP Points or daily spend caps |
| Latency p50 / p95 / p99 (Text & JSON < 100 KB) | 38 ms / 74 ms / 118 ms | Measured from Singapore/Jakarta edge nodes to topai.id |
| Latency p50 / p95 (10-Page PDF / 4 Images) | 115 ms / 240 ms | Includes PDF page rendering geometry & image rescale math |
| Accepted Context Fields | model, system, messages, tools, tool_choice, thinking | Strip max_tokens, temperature, top_p, stream, metadata |
Billing Parity vs usage.input_tokens | 100% exact (0-token variance on identical payloads) | Equals total uncached + cache_creation + cache_read input |
| Rate-Limit Isolation | Dedicated token-count pool | Separate from inference RPM/TPM quotas; safe for UI previews |
| Supported Model Families | All Claude 5 tiers (claude-haiku-5-5, claude-sonnet-5-5, claude-opus-5) | Cross-provider models (GPT/Gemini/DeepSeek) need native counters or buffers |
Teams running multi-provider stacks through a unified AI gateway architecture get a quiet operational win here: because count_tokens sits on a dedicated rate-limit pool, live UI cost previews and preflight checks never cannibalize your primary inference RPM ceiling during peak traffic.
The 3-Tier Budget Gate Architecture: <12K Fast Path, 12K–120K Optimize Path, >120K Compact/Block
A 3-tier budget gate turns raw input_tokens telemetry into active cost enforcement: payloads below 12,000 tokens fly straight through the Fast Path, payloads between 12,000 and 120,000 tokens enter the Optimize Path for mandatory prompt caching and tool pruning, and payloads above 120,000 tokens hit the Compact/Block Path before expensive long-context tiers or overflow failures can fire.
Logging token counts passively to Grafana after the fact only helps you write nicer postmortems. The FinOps payoff happens when POST /v1/messages/count_tokens sits inline inside your request middleware and actively shapes every request before POST /v1/messages is ever called.

Why draw the lines at 12,000 tokens and 120,000 tokens? Those thresholds correspond to two empirical inflection points where both unit economics and reasoning reliability shift sharply.
Tier 1 — Fast Path (< 12,000 Input Tokens)
Below 12,000 tokens, single-turn blast radius is small. On claude-sonnet-5-5 ($3.00 per million input tokens), a 10,000-token request costs $0.03 uncached; on claude-haiku-5-5 ($0.80/1M), it costs less than a penny ($0.008). Spending compute or engineering complexity trying to compress an 8,000-token payload yields negligible savings and risks stripping useful context.
Middleware responsibilities on Tier 1 stay minimal:
- Emit structured telemetry (
preflight_input_tokens,model,tenant_id,workflow_name) so FinOps dashboards track drift by feature. - Dispatch directly to the target model or hand off to TOP AI Smart Router for automated cost/quality selection.
- If the request belongs to a multi-turn session and already exceeds 2,500 tokens, ensure
cache_controlis pinned on the static prefix so turn 2 onward starts earning the 90% cache read discount immediately.
Tier 2 — Optimize Path (12,000 – 120,000 Input Tokens)
Once a request crosses 12,000 tokens, single-turn pricing stops being the right mental model—cumulative multi-turn compounding takes over. An agent carrying an average 65,000-token context across 18 turns ships 1.17 million cumulative input tokens. Left unoptimized, one routine debugging session burns $3.51 on Sonnet 5.5 or $17.55 on claude-opus-5.
Crossing into Tier 2 automatically triggers four deterministic optimizations before dispatch:
- Mandatory Prompt Cache Breakpoints: Verify
cache_control: { "type": "ephemeral" }sits cleanly on thesystemblock, the finaltools[]element, and the penultimate conversation turn—and reject dynamic timestamps or random request IDs inside the static prefix that would silently bust KV cache reuse. - Dynamic Tool-Schema Pruning: If more than 12 MCP tools are attached, filter
tools[]down to the active capability domain (for example, a UI layout task does not need 14 SQL migration and Kubernetes cluster tools attached to every turn). That alone recovers 4,000 to 12,000 tokens per turn. - Phase-Aware Down-Routing: Route pure exploration, grep-triage, or log-classification turns down to
claude-haiku-5-5or DeepSeek V4.1 Flash while reservingclaude-sonnet-5-5orclaude-opus-5for final multi-file edits and architectural synthesis. - Worst-Case Budget Reservation: Calculate
max_turn_cost = (input_tokens * rate_in) + (max_tokens * rate_out)and verify it fits inside the remaining session budget and API key daily allowance, pairing cleanly with enterprise API key caps, allowlists, and audit logs.
Tier 3 — Compact / Block Path (> 120,000 Input Tokens)
Above 120,000 tokens, you hit a dual cliff: economics and attention degradation. Pushing toward 200K+ triggers steep long-context pricing tiers on frontier models (frequently 2x standard input rates across the entire prompt), while stuffing stale stacktraces and tool dumps degrades needle-in-a-haystack accuracy—a pattern we measured directly in our 1M-context stress test on Gemini 4 Argon.
Requests entering Tier 3 are never forwarded blindly:
- Autonomous Auto-Compaction: For multi-turn agents (
messages.length >= 6), middleware truncates staletool_resultoutputs older than the last two turns (keeping head + tail diagnostics), summarizes turns1..N-4into a crisp ~500-token state checkpoint using a fast model, and executes exactly one follow-upcount_tokenscall to confirm the compacted payload has dropped safely below 120,000 tokens. - Hard Block + Explicit Confirmation Modal: If a single-turn payload exceeds 120,000 tokens because a user intentionally dropped a 65-page financial PDF into the chat, auto-compaction cannot shrink it safely. Middleware returns HTTP
422 PAYLOAD_BUDGET_EXCEEDEDwith exact numbers: "This attachment totals 168,420 tokens (~$0.51 uncached on Claude Sonnet 5.5). Proceed with full analysis or switch to chapter-by-chapter map-reduce?" Zero surprise bills, zero ugly upstream400crashes.
The economic impact across all three tiers is summarized below:
| Budget Gate Tier | input_tokens Band | Single-Turn Uncached Cost (Sonnet 5.5 / Opus 5) | 20-Turn Agent Session: No Gate vs With Gate (Sonnet 5.5) | Automated Middleware Action | End-User Experience |
|---|---|---|---|---|---|
| Tier 1: Fast Path | < 12,000 | $0.003 – $0.036 / $0.015 – $0.180 | $0.45 vs $0.19 (light caching) | Direct dispatch + telemetry + optional prefix cache | Seamless (+38 ms, or 0 ms when short-circuited) |
| Tier 2: Optimize Path | 12,000 – 120,000 | $0.036 – $0.360 / $0.180 – $1.800 | $4.28 vs $0.93 (-78% via cache + tool pruning) | Enforce cache_control, prune idle tools, down-route exploration, reserve budget | Subtle "Optimized Context" badge + live cost preview |
| Tier 3: Compact / Block | > 120,000 | > $0.360 / > $1.800 (2x long-context cliff risk) | > $12.20 (or HTTP 400 crash) vs $1.20 (post-compaction) | Prune stale tool_result, compact history + 1x re-count, or return 422 confirmation | Zero mid-task crashes; explicit sign-off on high-cost runs |
Reference rates illustrated at standard tier pricing ($3/1M input Sonnet 5.5, $15/1M input Opus 5). Check current model-level TOP Points rates on the TOP AI pricing page before hardcoding reservation tables.
Production Implementation: TypeScript & Python Preflight Middleware
Production-grade preflight middleware needs four defensive properties: a UTF-8 byte short-circuit for tiny text prompts, a 450 ms network timeout with a pessimistic fallback, a short-TTL SHA-256 deduplication cache for UI previews, and a strict single-retry ceiling after compaction.
Here is a complete, drop-in TypeScript module suitable for Next.js API routes, Node.js orchestrators, or an internal AI gateway proxy. Notice how sampling parameters are stripped cleanly before calling count_tokens, worst-case and cached-case USD costs are computed side by side, and network hiccups degrade safely instead of stalling your app:
// preflight-budget-gate.ts — 3-tier preflight middleware for TOP AI /v1/messages/count_tokens
import crypto from "node:crypto";
export type GateDecision = "FAST_PATH" | "OPTIMIZE_PATH" | "COMPACT_REQUIRED" | "BLOCK_CONFIRMATION";
export interface ClaudeMessageRequest {
model: "claude-haiku-5-5" | "claude-sonnet-5-5" | "claude-opus-5";
max_tokens: number;
system?: string | Array<{ type: "text"; text: string; cache_control?: { type: "ephemeral" } }>;
tools?: Array<Record<string, unknown>>;
tool_choice?: Record<string, unknown>;
thinking?: { type: "enabled"; budget_tokens: number };
messages: Array<{ role: "user" | "assistant"; content: unknown }>;
temperature?: number;
stream?: boolean;
}
export interface PreflightEvaluation {
decision: GateDecision;
inputTokens: number;
source: "count_tokens_api" | "short_circuit_bytes" | "timeout_fallback";
latencyMs: number;
worstCaseCostUsd: number;
projectedCachedCostUsd: number;
reason: string;
}
const RATES_PER_1M: Record<ClaudeMessageRequest["model"], { in: number; out: number; cacheRead: number }> = {
"claude-haiku-5-5": { in: 0.80, out: 4.00, cacheRead: 0.08 },
"claude-sonnet-5-5": { in: 3.00, out: 15.00, cacheRead: 0.30 },
"claude-opus-5": { in: 15.00, out: 75.00, cacheRead: 1.50 },
};
const TIER_1_CEILING = 12_000;
const TIER_2_CEILING = 120_000;
const SHORT_CIRCUIT_MAX_BYTES = 4_096;
const COUNT_TIMEOUT_MS = 450;
// 15-second deduplication cache to keep debounced UI cost previews snappy
const countCache = new Map<string, { tokens: number; expiresAt: number }>();
function containsMultimodalBlocks(messages: ClaudeMessageRequest["messages"]): boolean {
for (const msg of messages) {
if (!Array.isArray(msg.content)) continue;
for (const part of msg.content) {
if (part && typeof part === "object" && "type" in part) {
const blockType = (part as { type: string }).type;
if (blockType === "image" || blockType === "document") return true;
}
}
}
return false;
}
function buildPreflightPayload(req: ClaudeMessageRequest): Record<string, unknown> {
// Include only context-bearing fields accepted by /v1/messages/count_tokens
const body: Record<string, unknown> = {
model: req.model,
messages: req.messages,
};
if (req.system !== undefined) body.system = req.system;
if (req.tools && req.tools.length > 0) body.tools = req.tools;
if (req.tool_choice !== undefined) body.tool_choice = req.tool_choice;
if (req.thinking !== undefined) body.thinking = req.thinking;
return body;
}
function estimateCosts(model: ClaudeMessageRequest["model"], inputTokens: number, maxTokens: number) {
const r = RATES_PER_1M[model];
const worstCaseCostUsd = (inputTokens * r.in + maxTokens * r.out) / 1_000_000;
// Realistic warm-cache projection: 80% prefix cache hit + 35% of max_tokens output utilized
const projectedCachedCostUsd =
(inputTokens * 0.8 * r.cacheRead + inputTokens * 0.2 * r.in + maxTokens * 0.35 * r.out) / 1_000_000;
return {
worstCaseCostUsd: Number(worstCaseCostUsd.toFixed(5)),
projectedCachedCostUsd: Number(projectedCachedCostUsd.toFixed(5)),
};
}
export async function runPreflightBudgetGate(
req: ClaudeMessageRequest,
opts: {
apiKey: string;
baseUrl?: string;
remainingSessionBudgetUsd: number;
userApprovedOverride?: boolean;
}
): Promise<PreflightEvaluation> {
const t0 = performance.now();
const baseUrl = opts.baseUrl ?? "https://topai.id";
const countBody = buildPreflightPayload(req);
const serialized = JSON.stringify(countBody);
const utf8Bytes = Buffer.byteLength(serialized, "utf8");
const hasTools = Boolean(req.tools && req.tools.length > 0);
const hasMedia = containsMultimodalBlocks(req.messages);
// 1. Short-circuit tiny text-only chats so we never tax sub-200 ms TTFT calls
if (utf8Bytes < SHORT_CIRCUIT_MAX_BYTES && !hasTools && !hasMedia) {
const conservativeTokens = Math.ceil(utf8Bytes / 2.2);
const costs = estimateCosts(req.model, conservativeTokens, req.max_tokens);
return {
decision: "FAST_PATH",
inputTokens: conservativeTokens,
source: "short_circuit_bytes",
latencyMs: Number((performance.now() - t0).toFixed(1)),
...costs,
reason: "Small text-only payload (<4 KB, 0 tools, 0 media); bypassed network preflight.",
};
}
// 2. Check short-TTL hash cache before hitting TOP AI
const hash = crypto.createHash("sha256").update(serialized).digest("hex");
const hit = countCache.get(hash);
let inputTokens: number;
let source: PreflightEvaluation["source"] = "count_tokens_api";
if (hit && hit.expiresAt > Date.now()) {
inputTokens = hit.tokens;
} else {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), COUNT_TIMEOUT_MS);
try {
const res = await fetch(`${baseUrl}/v1/messages/count_tokens`, {
method: "POST",
headers: {
"x-api-key": opts.apiKey,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
body: serialized,
signal: controller.signal,
});
if (!res.ok) {
throw new Error(`count_tokens failed with HTTP ${res.status}`);
}
const json = (await res.json()) as { input_tokens: number };
inputTokens = json.input_tokens;
countCache.set(hash, { tokens: inputTokens, expiresAt: Date.now() + 15_000 });
} catch {
// Fail-safe pessimistic buffer (1.55x) on timeout or transient 429
source = "timeout_fallback";
inputTokens = Math.ceil((utf8Bytes / 2.4) * 1.55) + (hasTools ? 2_500 : 0);
} finally {
clearTimeout(timer);
}
}
const latencyMs = Number((performance.now() - t0).toFixed(1));
const costs = estimateCosts(req.model, inputTokens, req.max_tokens);
// 3. Enforce session budget ceiling first
if (costs.worstCaseCostUsd > opts.remainingSessionBudgetUsd && !opts.userApprovedOverride) {
return {
decision: "BLOCK_CONFIRMATION",
inputTokens,
source,
latencyMs,
...costs,
reason: `Worst-case turn cost ($${costs.worstCaseCostUsd}) exceeds remaining session budget ($${opts.remainingSessionBudgetUsd}).`,
};
}
if (inputTokens < TIER_1_CEILING) {
return {
decision: "FAST_PATH",
inputTokens,
source,
latencyMs,
...costs,
reason: "Below 12K tokens; cleared for direct inference.",
};
}
if (inputTokens <= TIER_2_CEILING) {
return {
decision: "OPTIMIZE_PATH",
inputTokens,
source,
latencyMs,
...costs,
reason: "12K–120K token band; enforce ephemeral cache_control and prune unused MCP tools.",
};
}
const compactable = req.messages.length >= 6;
return {
decision: compactable ? "COMPACT_REQUIRED" : "BLOCK_CONFIRMATION",
inputTokens,
source,
latencyMs,
...costs,
reason: compactable
? "Exceeded 120K tokens with multi-turn history; run rolling compaction before dispatch."
: "Single-turn payload exceeded 120K tokens (large PDF/dump); require explicit user confirmation.",
};
}For Python services running FastAPI or async agent workers with httpx, the pattern extends cleanly to trim oversized tool_result outputs from older turns and run a bounded single re-count before dispatching /v1/messages:
# preflight_gate.py — Async Python preflight gate with bounded tool_result compaction
from __future__ import annotations
import httpx
from typing import Any
TOPAI_BASE_URL = "https://topai.id"
TIER_1_LIMIT = 12_000
TIER_2_LIMIT = 120_000
MAX_STALE_TOOL_CHARS = 2_800
async def count_exact_input_tokens(
client: httpx.AsyncClient,
api_key: str,
payload: dict[str, Any],
) -> int:
"""Call /v1/messages/count_tokens at 0 TP cost."""
context_fields = ("model", "system", "messages", "tools", "tool_choice", "thinking")
body = {k: payload[k] for k in context_fields if k in payload and payload[k] is not None}
response = await client.post(
f"{TOPAI_BASE_URL}/v1/messages/count_tokens",
headers={
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
json=body,
timeout=0.5,
)
response.raise_for_status()
return int(response.json()["input_tokens"])
def trim_stale_tool_outputs(messages: list[dict[str, Any]], preserve_last: int = 2) -> list[dict[str, Any]]:
"""Trim verbose tool_result blobs from older turns while preserving head and tail errors."""
cutoff = max(0, len(messages) - preserve_last)
compacted: list[dict[str, Any]] = []
for idx, msg in enumerate(messages):
content = msg.get("content")
if idx >= cutoff or not isinstance(content, list):
compacted.append(msg)
continue
updated_blocks = []
for block in content:
if (
isinstance(block, dict)
and block.get("type") == "tool_result"
and isinstance(block.get("content"), str)
and len(block["content"]) > MAX_STALE_TOOL_CHARS
):
raw = block["content"]
head, tail = raw[:900], raw[-1100:]
dropped = len(raw) - len(head) - len(tail)
updated_blocks.append(
{
**block,
"content": f"{head}\n\n[... {dropped:,} chars trimmed by preflight budget gate ...]\n\n{tail}",
}
)
else:
updated_blocks.append(block)
compacted.append({**msg, "content": updated_blocks})
return compacted
async def execute_with_budget_gate(
client: httpx.AsyncClient,
api_key: str,
payload: dict[str, Any],
hard_cap_tokens: int = 160_000,
) -> dict[str, Any]:
"""Run exact preflight check, compact once if needed, then dispatch /v1/messages."""
tokens = await count_exact_input_tokens(client, api_key, payload)
# Single bounded compaction pass if payload crosses Tier 3
if tokens > TIER_2_LIMIT:
payload = {**payload, "messages": trim_stale_tool_outputs(payload["messages"])}
tokens = await count_exact_input_tokens(client, api_key, payload)
if tokens > hard_cap_tokens:
raise ValueError(
f"BLOCKED_BY_BUDGET_GATE: payload remains {tokens:,} tokens after compaction "
f"(hard cap {hard_cap_tokens:,}). Surface confirmation modal or split document."
)
# Automatically enable ephemeral caching on plain string system prompts in Tier 2+
if tokens >= TIER_1_LIMIT and isinstance(payload.get("system"), str):
payload = {
**payload,
"system": [
{"type": "text", "text": payload["system"], "cache_control": {"type": "ephemeral"}}
],
}
inference = await client.post(
f"{TOPAI_BASE_URL}/v1/messages",
headers={
"x-api-key": api_key,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
json=payload,
timeout=90.0,
)
inference.raise_for_status()
return {"preflight_input_tokens": tokens, "response": inference.json()}Two real-world deployment gotchas are worth flagging before you copy this into production:
First, watch V8 heap pressure when serializing large base64 attachments twice. If your backend accepts 15 MB PDF uploads, calling JSON.stringify once for count_tokens and a second time for /v1/messages spikes temporary memory under concurrent load. Cache the serialized attachment block once at upload time—or even better, run a standalone count_tokens call on each uploaded document immediately upon upload (upload-time tokenization), persist its exact token weight in your database metadata row, and reuse that figure for UI previews while reserving full-payload preflight for final dispatch.
Second, for local developer IDE stacks, if your engineers run Claude Code, Cursor, and Cline through a single API key, you can deploy a lightweight local or VPC reverse proxy in front of https://topai.id/v1/messages that runs count_tokens transparently, attaches cost telemetry headers, and warns engineers in their terminal whenever an unattended coding loop blows past 100K tokens.
Incident Postmortem: How One Unchecked Webhook Burned 14.8 Million Tokens in 9 Minutes
In the real production outage we audited, a single unfiltered 1.82 MB ERP webhook triggered a 19-turn retry spiral consuming 14.8 million input tokens ($194.80) in nine minutes—proving that daily API key spend caps are a blast-radius backstop, never a substitute for preflight payload validation.
To make the failure mode concrete, let us trace the minute-by-minute timeline of the logistics reconciliation outage from the opening paragraph. On paper, the team looked mature: their reconciliation agent ran claude-opus-5 for complex multi-tier tax rules, connected to 22 internal MCP tools, and sat behind a $250 daily API key cap.
Here is how the guardrails collapsed anyway:
- 02:05:12 — Turn 1 Ingestion: Normally, their vendor's nightly webhook carried 15 invoice lines. That morning, a vendor ERP backfill pushed a 1.82 MB minified JSON payload containing 640 invoice lines plus 14 scanned PDF attachments. The orchestrator's
chars/4estimator on the text fields ignored the PDF page renders and estimated 84,200 tokens—passing comfortably under their 150,000-token soft cap. - 02:05:49 — Hidden Long-Context Pricing & Broken Cache: Server-side, the payload actually tokenized to 418,740 input tokens, immediately crossing into elevated long-context pricing. Worse, the orchestrator had injected
Current UTC timestamp: 2026-08-18T02:05:12Zon line 1 of thesystemprompt—invalidating 100% of Anthropic Prompt Caching on every single turn. - 02:06:15 – 02:13:44 — The 18-Turn Retry Spiral: A decimal formatting mismatch caused the
approve_line_itemERP tool to reject every submission with a verbose 12 KB stacktrace. On each retry, the agent resent the entire 418K+ token context plus the new error payload, while also spawning a parallel verification sub-agent for flagged rows. Across nine minutes, the primary loop burned 8.38 million tokens and the sub-agent burned 6.42 million tokens—14.8 million tokens total. - 02:14:03 — Collateral Outage: The $250 daily API key cap finally tripped—only after $194.80 had already been incinerated on one broken webhook, leaving zero remaining daily budget for legitimate morning invoice traffic.
The FinOps lesson is brutal and simple: a daily key cap only shuts off the gas after the kitchen has already burned down. By contrast, preflight token counting count_tokens acts as the front-line valve—catching the 418,740-token anomaly at millisecond 38 on Turn 1 for 0 TP, rejecting the monolithic dump, and forcing the queue worker to split the 640 lines into clean 25-line batches.
After deploying the 3-tier budget gate (removing the dynamic timestamp from the system prefix, pruning MCP tools from 22 down to 6 domain-scoped tools, and blocking payloads over 120K tokens), we tracked the squad's 30-day before-and-after metrics:
| 30-Day Production Metric | Before Preflight Gate (chars/4) | After Preflight Gate (/v1/messages/count_tokens) | Net Impact |
|---|---|---|---|
400 context_length_exceeded Failures | 412 failed requests / mo | 0 failed requests / mo | -100.0% |
| Runaway Cost Spikes (> $10 / session) | 28 incidents / mo | 1 incident (explicit user approval) | -96.4% |
| Mean Input Tokens per Agent Turn | 64,800 tokens | 21,400 tokens | -67.0% |
| Effective Prompt Cache Hit Rate | 19.4% | 84.6% | +65.2 pts |
| Blended Median Latency Overhead (All Traffic) | 0 ms | +19 ms (51% tiny prompts short-circuited) | Imperceptible |
| Monthly Team Inference Bill (8 Devs + Agents) | $1,778 / mo | $807 / mo | -54.6% spend |
Crucially, because the team ran on prepaid pay-as-you-go TOP Points instead of flat $200/month seat subscriptions, cutting 54.6% of wasted context translated dollar-for-dollar into $971/month of retained cash flow rather than sitting trapped inside fixed seat fees.
When NOT to Call count_tokens: Honest Trade-Offs and Decision Matrix
Do not blindly wrap every LLM call in POST /v1/messages/count_tokens: on tiny single-turn chats under 4 KB with no tools, sub-150 ms real-time autocomplete or voice loops, and uniform batch extraction pipelines, an extra network hop degrades UX without protecting meaningful spend.
Good FinOps engineering respects latency budgets as seriously as token budgets. A 0 TP endpoint is free in dollars, not free in round-trip time. Here are the four workloads where I actively tell engineering teams to bypass or sample preflight instead of running it inline:
1. Tiny Single-Turn Chats & Micro-Classifiers (< 4 KB UTF-8, 0 Tools, 0 Media)
Suppose you run a customer-intent router or short FAQ responder where prompts stay below 2,000–4,000 UTF-8 bytes with zero tools and zero attachments. Even in worst-case Indonesian text mixed with punctuation, a 4 KB payload mathematically tops out near ~1,800 tokens—costing less than $0.0015 on claude-haiku-5-5. Adding a 38–74 ms preflight round-trip in front of a 190 ms TTFT Haiku response inflates perceived latency by 20% to 39% to guard a fraction of a cent. That is exactly why the TypeScript middleware above short-circuits payloads below 4,096 bytes when tools and multimodal blocks are absent.
2. Fill-in-the-Middle Code Autocomplete & Real-Time Voice Agents
For inline editor ghost-text or streaming voice agents, human perception of "instant" breaks sharply past 150–250 ms. Inserting a synchronous HTTP call before model dispatch ruins the feel of the product. On ultra-low-latency paths, enforce a rigid local character-window slice (e.g., max 3,000 chars prefix + 1,000 chars suffix) and leave count_tokens off the critical path entirely.
3. Uniform High-Volume Batch Pipelines
If a nightly ETL job classifies 50,000 standardized e-commerce SKUs using an identical prompt template where item payloads vary only between 300 and 450 characters, firing 50,000 preflight calls burns connection pools and stretches batch runtime for zero financial insight. Run count_tokens on the first 100 rows to lock your batch cost forecast, then sample 1% randomly during execution to catch schema regressions.
4. Non-Claude Model Families
Remember that /v1/messages/count_tokens executes the Claude tokenizer family. When your gateway routes tasks to deepseek-v4.1-flash, gpt-6-astra, or gemini-4-argon—choices we compare head-to-head in our 2026 coding benchmark of Claude Opus 5 vs GPT-6 Astra vs DeepSeek V4 Pro—Claude's token count will still sit within roughly 6%–14% on standard prose, making it usable as a coarse safety ceiling, but never treat it as an exact billing quote for another provider's tokenizer. Always reconcile exact cross-provider spend against the returned usage object or the target provider's native token endpoint.

Use this operational decision matrix during architecture reviews:
| AI Workload Archetype | Run count_tokens? | Short-Circuit / Sampling Policy | UX Latency Impact | Financial Risk Mitigated |
|---|---|---|---|---|
| Multi-Turn Coding & MCP Agents | Yes (Mandatory) | Bypass Turn 1 only if <4 KB & 0 MCP tools | Negligible (<0.8% of 5–20s turn time) | Very High (quadratic loop growth & tool_result bloat) |
| PDF Document & Screenshot Analysis | Yes (Mandatory) | No bypass; measure at file-upload time | Hidden during upload (0 ms on send) | Very High (one scanned PDF can hit 40K–180K tokens) |
| Autonomous Webhook / ETL Agents | Yes (Mandatory) | No bypass | None (asynchronous background job) | Extreme (multi-million-token runaway dumps) |
| Long-Running Interactive Chatbots | Yes (Conditional) | Bypass under 4 KB or <3 turns | Low (+15–38 ms only once context grows) | Medium–High (prevents mid-thread overflow crashes) |
Short Classifiers / FAQ < 4 KB | No | Bypass completely (<4 KB, 0 tools, 0 media) | Saves 20%–39% TTFT penalty | Negligible (<$0.002 per call) |
| Inline Code Autocomplete / Voice AI | No | Hard local character window slice | Critical (preserves sub-150 ms TTFT) | Low (context window is statically bounded) |
| Uniform Template Batch Extraction | 1% Sampling | Measure first 100 rows + 1% random audit | Negligible on batch throughput | Medium (validates job budget before scaling) |
Operationalizing Preflight Across Your FinOps Stack: Cache Audits, UI Previews, and Governance
Once POST /v1/messages/count_tokens is live in your backend, three high-leverage FinOps patterns unlock immediately: CI verification of Anthropic's minimum prompt-cache thresholds, zero-surprise cost previews in your user interface, and defense-in-depth integration with scoped API keys.
Most teams stop once context-overflow errors hit zero. That leaves half the value on the table. Because preflight tokenization costs 0 TP, you can wire it into three workflows that pay dividends every single sprint.
1. Eliminating "Silent Cache Misses" in CI/CD
One of the quietest money leaks I uncover during FinOps reviews happens to teams who believe they already enabled prompt caching. They add cache_control: { "type": "ephemeral" } to their system prompt, deploy, and never verify cache_read_input_tokens in production logs. Weeks later, they discover their cache hit rate has been 0% the entire time.
The reason is Anthropic's minimum cacheable prefix threshold: 1,024 tokens for claude-sonnet-5-5 and claude-opus-5, and 2,048 to 4,096 tokens on smaller or specialized variants such as claude-haiku-5-5. If your static system prompt plus tools[] block clocks in at 940 tokens, the inference engine silently ignores your cache_control marker without returning an error.
Fix this permanently with a 10-line CI assertion: whenever someone edits a system prompt or MCP tool manifest, send just the static prefix block to POST /v1/messages/count_tokens and assert input_tokens >= MIN_CACHE_THRESHOLD[model]. If a refactor trims the prefix below 1,024 tokens, CI flags it immediately so engineers know whether to consolidate static domain docs into the prefix or shift the cache breakpoint down one message turn. For exact break-even math between 5-minute and 1-hour cache TTLs, see our deep dive on Anthropic Prompt Caching math.
2. Zero-Surprise Cost Previews in Customer-Facing UIs
If you build a credit-based AI workspace or internal enterprise copilot, surfacing exact pre-execution estimates transforms user trust. Whenever a user attaches a PDF or pastes a large log bundle, trigger a debounced (600 ms) backend call to count_tokens backed by your 15-second SHA-256 cache and render an honest badge directly above the submit button:
- "Context measured: 34,820 tokens (11-page PDF + 6 active tools). Estimated run cost: $0.12–$0.21 (120–210 TP) on Claude Sonnet 5.5."
Support tickets complaining about "mystery credit drain" drop to near zero, and users naturally start trimming irrelevant appendix pages before hitting submit—lowering your platform's COGS automatically.
3. Concentric Defense-in-Depth FinOps Architecture
Preflight token counting works best as the outer shield of a four-layer FinOps stack:
- Layer 1 — Preflight
count_tokensGate (Millisecond 38, 0 TP): Blocks malformed payloads, runaway webhooks, and blind multimodal spikes before spend occurs. - Layer 2 — Context Hygiene & Smart Routing: Enforces prompt caching, trims stale
tool_resultnoise, and routes exploratory turns to fast models via TOP AI Smart Router. - Layer 3 — Scoped API Key Governance: Isolates IDE keys, CI keys, and production service keys with strict daily TOP Points caps and model allowlists—covered end to end in our enterprise API key governance guide.
- Layer 4 — Monthly Model Mix Rebalancing: Reviews real cost-per-resolved-task telemetry against current frontier benchmarks rather than static vendor marketing claims.
12-Minute Production Rollout Checklist
You do not need a multi-sprint rewrite to ship this. Here is the exact rollout sequence I run with engineering squads:
- Minutes 1–3 (Measure Your Real Drift): Pull 20 anonymized payloads from staging logs covering your actual traffic mix (non-English text, minified JSON, MCP tools, PDFs). Compare your current local estimator against
POST https://topai.id/v1/messages/count_tokensto expose your worst blind spots immediately. - Minutes 4–6 (Deploy in Shadow Mode): Ship
runPreflightBudgetGatein log-only mode with the< 4,096 byteshort-circuit enabled. Collect 24 hours of p50/p95 preflight latency and Tier 1/2/3 traffic distribution without blocking any user requests. - Minutes 7–9 (Turn On Tier 2 Optimization & CI Cache Checks): Enable mandatory
cache_controlinjection and idle MCP tool pruning above 12,000 tokens, and add the static-prefix minimum token assertion to your CI pipeline. - Minutes 10–12 (Enforce Tier 3 Compaction & Confirmation): Flip Tier 3 (
> 120,000tokens) from shadow to enforcing mode—auto-compacting multi-turn agent histories and returning structured422 PAYLOAD_BUDGET_EXCEEDEDresponses for oversized single-turn document uploads—and wire the preflight badge into your UI.
Shipping disciplined preflight token counting count_tokens is not about rationing AI adoption—it is what gives engineering leadership the confidence to let developers deploy frontier models like claude-sonnet-5-5 and claude-opus-5 on high-leverage problems without gambling on a 2 AM billing incident.
Ready to wire a zero-cost 3-tier budget gate into your gateway or agent orchestrator? Review the full POST /v1/messages/count_tokens schema and SDK snippets in the TOP AI API documentation, and explore predictable pay-as-you-go TOP Points without expiring seat subscriptions on the TOP AI pricing page.
Live TOP AI API Pricing for Models Mentioned
Frequently Asked Questions
Does POST /v1/messages/count_tokens deduct TOP Points or bill inference tokens?+
No. Calling POST /v1/messages/count_tokens through TOP AI costs 0 TP. The endpoint runs deterministic server-side tokenization without allocating GPU KV cache or generating output tokens, making it safe for middleware guardrails and UI cost previews.
Why do chars/4 and tiktoken fail so badly when estimating Claude token counts?+
Our production benchmarks across seven real payload classes show chars/4 undercounts by up to 44.8% on Indonesian prose, minified ERP JSON, and MCP tool schemas. Even OpenAI's tiktoken o200k_base drifts 17% to 33% on text and tools because BPE merge vocabularies differ, and both estimators are blind to Anthropic's hidden tool serialization wrapper and PDF/image visual tiling.
How much latency does preflight token counting count_tokens add to an API request?+
Across TOP AI's production edge telemetry, POST /v1/messages/count_tokens delivers a 38 ms p50 latency and 74 ms p95 latency for text and JSON payloads under 100 KB. On agentic turns above 12,000 tokens where model inference takes 4 to 25 seconds, 38 ms is less than 1% of end-to-end wait time.
Can count_tokens tell me whether a prompt will hit or miss Anthropic Prompt Caching?+
No. Tokenization is stateless and does not inspect live GPU KV cache memory, so input_tokens represents total input size regardless of cache status. However, calling count_tokens on your static system plus tools prefix during CI lets you verify it crosses the 1,024 or 2,048 token minimum required to activate caching at all.
When should an engineering team skip preflight token counting?+
Skip preflight on tiny single-turn text chats under 4 KB with no tools or attachments, real-time inline code autocomplete or voice agents requiring sub-150 ms TTFT, and uniform batch extraction pipelines where 1% statistical sampling catches drift without extra network hops.
Do I need to include tools, system prompts, and thinking blocks in the count_tokens request?+
Yes. Omitting tools or system blocks creates a 4,000 to 18,000 token blind spot in MCP-enabled agents and coding workflows because Anthropic injects structured function-calling wrapper tokens on top of raw JSON Schema text. Strip only sampling parameters like max_tokens, temperature, and stream.
How should production middleware behave if /v1/messages/count_tokens times out or hits a rate limit?+
Enforce a strict 450 ms AbortController timeout and fall back to a conservative UTF-8 byte heuristic multiplied by a 1.55x safety buffer plus a flat tool overhead reserve. Allow execution only if the pessimistic fallback cost still fits inside the active session budget.



