Anthropic Token Counting Belongs in Request Preflight
Anthropic provides POST /v1/messages/count_tokens to estimate input tokens for a structured Messages request before generation. A gateway preflight should count the final routed payload, bind the result to the model and request digest, reserve output headroom, handle unsupported inputs explicitly, and repeat the check after any policy rewrite.

Anthropic exposes POST /v1/messages/count_tokens for estimating the input-token count of a Messages request before generation. The endpoint accepts the same structured inputs used to create a message, including system prompts and tools, plus images and PDFs, subject to documented exceptions. That makes token counting useful at request preflight, but only when the counted payload matches the payload that will cross the provider boundary.
I would reject any design that counts an early prompt string and later adds tools, history, or a policy-generated system block. The displayed number looks precise while describing a different request.
TL;DR
- Count the final structured request with Anthropic's
/v1/messages/count_tokensendpoint before generation. - Bind the count to the resolved model, request digest, policy version, and counted timestamp.
- Reserve room for
max_tokensand a route-defined safety margin inside the model context window. - Recount after any rewrite that changes messages, tools, images, documents, or system content.
The count belongs to a specific payload
Anthropic's token counting guide says the endpoint accepts the structured inputs used for message creation and returns total input_tokens. A production preflight should serialize the exact model, system content, messages, tool definitions, and supported media inputs intended for the later Messages request.
Calculate a canonical digest over that serialized provider payload. Store the digest beside the returned count, resolved model, Anthropic API version, route, and policy version. Before dispatch, calculate the digest again. A mismatch invalidates the count and triggers another preflight or a local rejection.
This catches quiet changes between application layers. An SDK may inject tool schemas. A gateway can add a system instruction. A conversation service can append the latest tool result after the user interface calculated its estimate. Each change affects the actual request.
The LLM API parameter allowlisting guide covers which fields may cross the route. Token preflight measures the approved request after that field decision.
An estimate still supports a deterministic gate
Anthropic labels the token count an estimate and says the actual input-token count can differ by a small amount. The documentation also notes that counts may include tokens Anthropic adds for system optimizations, although customers are not billed for those system-added tokens.
Do not turn the estimate into a billing promise. Use it as one input to a conservative admission rule. The route can require that estimated input tokens and the enforced output allowance fit within the resolved model's context window after a configured margin. Keep the margin explicit and versioned. Avoid claiming that one universal percentage is correct for every request shape.
A request close to the boundary deserves stricter handling. Recount after final serialization and reject when the remaining room falls below the route's minimum. The Anthropic max_tokens route cap explains the output side of that equation and the handling of truncated responses.
Store the actual input usage reported by the Messages response beside the preflight estimate. That pair supports drift monitoring without rewriting history.
Unsupported inputs need a named branch
The current token counting guide lists request forms that the Messages API accepts but the counting endpoint rejects with invalid_request_error. Those include server tools other than the advisor tool and the MCP connector. They also include image or document blocks supplied by URL or Files API reference. Anthropic instructs clients to send images and PDFs as base64 for counting. For requests using server tools or MCP servers, actual usage is available on the Messages response.
A governed route should decide what happens when exact preflight through this endpoint is unavailable. It can reject the request or route it to a separately budgeted path. It can also allow the request under a documented exception with post-response usage review. An input_tokens: 0 placeholder is dangerous because downstream code can mistake missing evidence for an empty prompt.
Record count_supported, count_attempted, provider error type, request digest, and exception reason as separate fields. Do not silently remove a server tool merely to make counting pass. That mutation changes the requested operation.
Picture the release console with a yellow count_unsupported badge beside the route name. That physical marker is more honest than a green zero-token row produced by a fallback default.
Context admission needs the resolved model
Anthropic's Messages API reference requires a model and describes the request fields that reach Claude. Resolve the approved model before token preflight because context capacity and supported features are model properties. A count detached from the model cannot establish admission.
The application should calculate the estimated input count and the enforced max_tokens. It should also calculate the route margin. Compare their sum with the current context-window entry for the resolved model. If the request exceeds the route's allowed envelope, reject it before generation with a stable local outcome such as context_budget_exceeded.
Avoid trimming conversation history inside a generic gateway helper. Removing old turns can change instructions and tool state. It can also change the meaning of the latest request. Compaction or summarization belongs to an application strategy with explicit provenance. After the application produces a smaller payload, the full preflight runs again.
The per-route AI policies guide supplies the policy owner for model selection, maximum input budget, output cap, margin, and unsupported-count behavior.
Cache and count records need separate semantics
Token counting is free according to Anthropic's guide, but the count response is still an external provider exchange. Cache it only when the cache key covers every input that can change tokenization or payload size. At minimum, include the provider payload digest, resolved model, relevant API version, and any feature flag that changes serialization.
Set a short, deliberate lifetime. Reuse can reduce duplicate preflight calls for identical queued work, yet a stale model mapping or altered serializer should force a miss. Record whether admission used a fresh provider count or a cached count.
Prompt caching on the generation request has its own usage fields. Anthropic splits reported input usage between ordinary tokens and cache reads. It reports cache creation separately. Every portion counts toward the context window. A token-count preflight should therefore protect context admission rather than assume cached content consumes no window space.
Keep provider billing and context accounting in separately named fields. Give local budget accounting its own field. One number called tokens cannot serve all three jobs.
A release fixture should invalidate stale counts
Send a small request through the deployed route and capture the exact count payload and digest, together with the returned input_tokens. Then mutate one field at a time after counting: add a tool definition, append a system sentence, add a prior assistant turn, change the model, and replace a short document with a larger base64 document.
Every mutation should invalidate the stored count before the Messages dispatch. Verify that the gateway either recounts the new payload or returns the route's named rejection. Confirm that an unchanged payload reuses a cached count only when the full cache key matches.
Test the documented unsupported forms. Supply a URL image, a Files API document reference, a server tool, and an MCP connector. Preserve Anthropic's actual invalid_request_error, then check that the route follows its approved exception behavior instead of substituting zero.
Finally, return a Messages response whose actual usage differs slightly from the estimate. The operation should remain valid when it stayed inside the margin, while the telemetry records the delta for review.
DeepInspect
DeepInspect can enforce token-preflight policy for authenticated user or agent HTTP traffic deliberately routed through its proxy to Anthropic. It can bind an observed count request and Messages request to identity, route, model, request digest, policy version, and an allow or deny decision.
The application owns conversation construction, compaction, serializer behavior, unsupported-input strategy, and the user-facing correction flow. DeepInspect sees routed HTTP exchanges. Direct provider calls and payload mutations after the proxy remain outside its decision record.
Book a technical deep dive at deepinspect.ai.
Frequently asked questions
- Is Anthropic token counting exact?
Anthropic describes the result as an estimate and says actual input usage can differ by a small amount. Use a route-defined margin, then record the actual usage reported by the Messages response beside the estimate.
- Does count_tokens include tools and system prompts?
The endpoint accepts structured inputs including system prompts and tool definitions. It also accepts messages and media such as images and PDFs. Count the exact final payload because any later addition invalidates the result.
- Can every valid Messages request be counted first?
The current guide documents exceptions. Server tools other than the advisor tool and MCP connectors can produce
invalid_request_erroron the counting endpoint even though the Messages API accepts them. URL or Files API media sources can produce the same error. Define an explicit route branch for those cases.- Should the gateway trim prompts that exceed the budget?
A generic gateway should reject the over-budget payload or invoke a separately approved transformation contract. Conversation trimming and summarization can change instruction and tool state. The application should produce a revised payload, then submit it through token preflight again.