Skip to navigation

Claude Code Long-Context Latency: Prefill, First Token and Quota Burn

In short: A large repository prompt can spend heavily before the first visible token. Separate prefill, decode and tool-loop latency in every test.

Published 20 min read
On this page

Direct answer

A large Claude Code prompt can consume input allowance and add waiting before the first visible token. Context capacity is not response speed. Separate prompt processing, time to first token, output decoding, tool execution and retries before deciding whether the model, the prompt or the surrounding workflow is slow.

Use a fixed task, record input and output tokens, and measure each stage the client exposes. Stabilize reusable prefixes for caching, retrieve focused code instead of reading whole repositories, and bound tool loops. Do not invent a tokens-per-second figure. The supplied official sources publish no universal prefill or decode rate for Claude Code.

Official: Anthropic’s large-codebase guidance recommends scoped search, read-only exploration and layered instruction files. Unknown: the evidence does not provide a controlled token-reduction percentage or one latency threshold that means a repository prompt is too large.

Why the quiet wait matters

The first visible token is an easy milestone. It looks like the moment the model starts working, yet a request may already have consumed substantial input and spent time processing the prompt. A developer who watches only the streaming text misses that earlier stage.

Long-context work magnifies the gap. A repository scan can place many candidate files, tool definitions and prior results into the request. The eventual answer may be short, but the path to that answer can be expensive.

This changes how a team should investigate a slow session. “The model is slow” is not a useful diagnosis. A better question is whether the delay happened before output, during output, inside a tool, or while a request waited to retry.

The idle-session cache-miss analysis covers one reason a resumed prompt may need fresh processing. Cache state belongs in a latency record because it can change the input treatment even when the visible task stays the same.

Quota pressure adds a second cost. Input tokens can be consumed before a useful change exists. The usage tracking and historical cost API guide helps place those tokens in a broader record, while the cost per verified change framework keeps review and rework in the denominator.

Long-context evidence map separating prompt tokens, prefill time, first token and decode rate
Evidence map based on Anthropic’s troubleshooting, caching and large-codebase guidance, checked 2026-11-27. The visual names measurement stages; it supplies no universal tok/s value.

Prefill, first token and decode are different events

Prompt processing, often called prefill, is the work of taking the input into account before generated output begins. Time to first token measures how long the caller waits for visible output. Decode is the generation stage after that first token appears.

The definitions do not make the intervals identical. Time to first token can include prompt processing, queueing, network travel and client overhead. If the instrumentation does not expose server-side prefill directly, label the visible interval as time to first token rather than claiming a pure prefill measurement.

Output decoding also differs from total response time. A response that streams quickly at first can slow later, pause for a tool call or finish with a retry. Capture the full request duration alongside the first-token interval.

Tool execution sits outside model decoding. A test suite, repository search or package command can dominate elapsed time even when the model responds promptly. The MCP output truncation guide explains another tool-loop issue: a large result can hide the decisive failure even when it arrives quickly.

Stage What it measures Common confusion
Prompt processing Input is prepared for generation Calling all first-token wait pure prefill
Time to first token Caller waits for visible output Treating it as total latency
Decode Output tokens are generated Comparing responses with different output lengths
Tool execution Local or remote command runs Blaming the model for a slow test
Retry or queueing Request waits before another attempt Counting access failure as model speed

Official: the supplied sources document stop reasons but do not publish a universal latency budget for Claude Code. Use observed intervals under stated conditions. Do not convert context-window size into a speed claim.

A useful report says what was measured. “First visible token arrived after the recorded interval” is defensible. “Prefill took exactly that long” needs instrumentation that separates the other contributors.

Input size is more than a file count

A large repository prompt is not simply a pile of files. Instructions, conversation history, tool schemas, search results and command output can all contribute. Counting files gives a rough sense of scope, but token usage gives the request-level measure needed for cost and latency analysis.

Some material is stable, such as reviewed project guidance. Other material changes every turn, including the newest question and current tool result. Separating the two helps with both cache design and measurement.

The prompt-caching economics guide documents the general rates: five-minute writes at 1.25 times base input price, one-hour writes at 2 times and reads at 0.1 times, with model-specific exceptions. A warm prefix can change cost treatment, but it does not make every later stage instantaneous.

Minimum cacheable prompt size also varies by model family. A small stable instruction block may be below the documented minimum, while a large retrieved context may qualify. Check the selected model rather than assuming every prefix is cacheable.

Input source Why it grows Control to test
Repository files Broad reads or repeated searches Package-scoped retrieval
Tool results Verbose logs and full command output Structured summaries with decisive errors
Conversation history Long task with many turns Checkpoint and deliberate compaction
Tool definitions Several connected servers Remove unused capabilities
Instruction files Broad root and nested guidance Layered, specific conventions
Retry context Repeated request after failure Classify the error before retrying

File count and token count should both stay in the worksheet. They answer different questions. Files show retrieval breadth; tokens show request weight. Neither alone proves that the selected context was relevant.

Tool results can dominate the next prompt

A tool loop multiplies context. The model requests a search, receives results, requests a file read, receives more content, and then continues. Each round can add material that the next request must process.

Such growth is sometimes useful. A broad search may locate the right module after several attempts. The problem is unbounded discovery with no decision about when enough evidence exists.

Official: Anthropic’s large-codebase guidance describes agentic grep search, optional language-server symbol search, ignore files, read-only subagents for exploration, per-subdirectory commands and codebase maps. These are ways to narrow the path from a question to relevant code.

The monorepo search and token-budget guide turns that guidance into a retrieval plan. It does not claim grep is always wrong or promise a fixed reduction. Scoped search is a hypothesis to measure against the actual repository.

A practical loop budget has three parts: a search scope, a candidate limit and a stopping condition. For example, search the affected package first, inspect a small set of candidate files, then stop when the relevant symbol and its caller are identified. The numbers should fit the repository; they are workflow choices, not official limits.

Latency workflow moving from prompt tokens through prefill, first token, decode and the next tool result
Editorial workflow derived from documented stop reasons and large-codebase practices. Tool output returns to the next prompt, so loop shape matters as well as individual request speed.

Bound the loop before measuring it

An unbounded agent loop is difficult to benchmark. The task may expand, the context may fill, or the run may stop for a reason unrelated to the original latency question. Set a finish condition first.

Official: the Agent SDK supports max_turns and max_budget_usd, with stop conditions including error_max_turns and error_max_budget_usd. Read-only tools can run concurrently, while state-modifying tools execute sequentially. The controls apply to the documented SDK loop; do not present them as identical switches in every Claude Code surface.

Task budgets are different. Official: they count thinking, tool calls, tool results and output, but remain advisory hints rather than hard caps. The task budgets versus hard stops guide explains where enforcement belongs.

A benchmark should also specify what counts as completion. “Agent stopped” is not enough. Completion might mean a focused patch, a named test result and an inspected diff. The proof-of-work packet keeps those artifacts together.

Loop control Purpose Boundary
Turn limit Stops repeated model-tool cycles SDK support must be confirmed for the surface
Budget limit Stops a run at a configured spend condition Pricing and enforcement need verification
Tool timeout Bounds a command that may hang Timeout alone does not prove useful output
Search scope Restricts repository discovery Can miss code outside the scope
Completion check Defines accepted work Human review may still be required

A hard stop protects the experiment from runaway cost. It does not make the work correct. Pair the stop with a checkpoint so an interrupted run leaves usable state.

Build a benchmark protocol

Start with a small, versioned fixture. It should contain a known issue, a focused test and enough surrounding code to create a meaningful prompt. Use synthetic or non-sensitive material so repeated runs do not expose real project data.

Fix the model, client version, instructions and tool set. Then vary one input condition at a time: a focused file set, a broader package, or a larger tool result. Hold the expected change and acceptance check identical.

Warm-up runs can reveal setup problems, but they also alter cache state. Capture them separately. A measured trial should state whether it began with a warm prefix, a fresh session or an unknown cache condition.

Benchmark input Keep fixed Vary deliberately
Task fixture Issue and acceptance test None
Client environment Version, tools and permissions None
Model and settings Model identity and relevant options None
Context scope Retrieval method Focused versus broader selection
Tool output Fixture behavior Compact versus verbose result
Cache condition Logging method Warm, expired or changed prefix

The idle-session cache experiment supplies a way to control one of those conditions. Without that control, a longer input or a changed prefix can look like a pure latency difference.

Run more than one trial where practical. Save raw observations and the conditions. The supplied evidence does not justify a universal average, so avoid publishing a tidy performance number from an underspecified fixture.

Measure the stages the client exposes

At request start, capture a monotonic timestamp if the harness allows it. At first visible token, capture another. On completion, capture the final timestamp and stop reason. Around each tool call, capture its own start and end.

A monotonic clock measures elapsed time without jumps caused by wall-clock adjustments. If the client does not expose event timestamps, use the coarsest honest interval available and mark the missing stages.

Input and output token counts belong beside timing. A faster response with much less output is not directly comparable to a slower, more complete answer. A longer tool execution may reflect a broader test rather than slower model decoding.

Record field Use in analysis
Request start Defines the visible wait interval
First-token time Separates initial delay from streaming
Completion time Captures full response duration
Input tokens Connects prompt size to quota use
Cache-read tokens Shows reused input when exposed
Output tokens Normalizes decode comparisons
Tool intervals Identifies time outside generation
Stop reason Shows whether the run ended naturally

Official: max_tokens means the output limit was reached, model_context_window_exceeded means context filled, tool_use requires a tool result, and pause_turn requires continuing the assistant turn. refusal, end_turn and stop_sequence have their own documented meanings.

Treat a stop reason as part of the result. A run that ends at the output limit is not equivalent to a natural completion, even if both produce text. The stop reason reference provides the classification.

If retries occur, record them as separate attempts. Combining a failed request, a wait and a successful retry into one latency number hides the access event. The 429 diagnosis guide helps identify which failures need a different response.

Use arithmetic, not invented speed claims

Suppose a measured request has 30,000 input tokens and produces 1,000 output tokens. Derived: total token volume is 30,000 + 1,000 = 31,000. The sum is not a latency prediction. It simply states the request’s token volume under the recorded conditions.

Now compare a second request with 12,000 input tokens and the same 1,000 output tokens. Its total is 13,000 tokens. The input difference is 18,000 tokens, but the time difference must come from measurement. No supplied source authorizes a conversion from those token counts to seconds.

Illustrative request Input tokens Output tokens Total token volume
Broad context 30,000 1,000 31,000
Focused context 12,000 1,000 13,000
Difference 18,000 0 18,000

The numbers are assumptions for a worksheet, not benchmark results. Their purpose is to show what can be calculated safely. Token volume supports quota and cost analysis; elapsed stages support latency analysis.

For cost, use the selected model’s official prices and actual cache treatment. Let P be base input price per token. A fully fresh 30,000-token input has an input component of 30,000 × P before output and other charges. The formula excludes any cache-write premium or model exception.

A subscription allowance is not an API price. Do not divide a plan fee by a guessed token count and present the result as an official rate. The usage and billing guide for the console is useful for separating account controls from model pricing.

Quota burn starts before a visible change

A broad prompt can consume input allowance even when the agent later asks for a smaller scope. The input is not waste by definition. Discovery may be necessary. The avoidable waste is repeated discovery that does not change the next decision.

Track accepted work alongside token volume. If a large search finds the relevant symbol and produces a verified patch, its cost may be justified. If several broad searches return the same candidates and the run ends without a change, the loop needs a tighter stop.

The cost per verified change worksheet provides a practical denominator. Include review time, failed attempts and rework rather than counting only the final successful request.

Rate limits add another constraint. Official: standard limits use a token bucket that replenishes continuously, and standard or ramp limits can return retry-after. A monthly spend-cap 429 has no retry-after and pauses usage until the next month at 00:00 UTC. These API mechanics should not be collapsed into one generic “wait five minutes” rule.

Quota question Evidence needed
How much input was processed? Request token counts and cache split
How much output was generated? Output token count and stop reason
Did a retry add usage? Separate request attempts
Which limit applied? Error type, headers and account state
Was the work accepted? Diff, tests and review result

The usage tracking and cost API guide explains that the historical Usage and Cost API typically has data within five minutes and provides daily cost buckets. It is not a real-time benchmark clock.

Reduce context without hiding relevant code

Retrieval should begin at a package or module boundary. Identify the entry point, follow its direct dependencies and inspect the test that defines expected behavior. Expand only when the evidence points outside that scope.

A root instruction file can provide broad pointers, while subdirectory files can hold local conventions. Official: that layered approach is part of Anthropic’s large-codebase guidance. It helps the agent know where to look before it starts reading.

Read-only subagents can scout separate areas without modifying shared files. Their reports should name candidate files, relevant symbols and unresolved questions. The subagent context and duplicate-work analysis explains how a shared brief reduces repeated discovery.

Retrieval strategy Useful when Loss to watch
Exact symbol search Name is known Naming may be indirect
Package-scoped grep Feature has a clear boundary Cross-package callers can be missed
Read-only subagent scout Several areas need comparison Reports can repeat the same facts
Codebase map Repository is large and structured Map can become stale
Focused file reads Candidates are already ranked Early ranking can exclude the right file

No strategy guarantees a fixed token reduction. The fact pack explicitly lacks a controlled percentage. Report the before-and-after token counts, retrieval steps and accepted result for your repository.

The context-portable migration guide helps preserve task state across clients. A portable brief should name scope, constraints and acceptance checks rather than depend on one session’s large transcript.

Structure tool output around the decisive signal

Verbose output can inflate the next request and bury the failure. A test log may contain hundreds of passing lines before the one assertion that matters. A search tool may return many matches when only a few are relevant.

Return a compact structured result: status, changed scope, failed checks, decisive error and artifact location. Leave the full log outside the model context when possible, then let the agent request a focused excerpt.

The MCP output truncation guide covers the evidence boundary. A community issue reports a silent failure before tool-call emission, while another issue is a feature request about verbose MCP output. Neither establishes a universal 10 KiB limit.

Official: stop reasons help distinguish natural completion from output or context limits. They do not tell you whether a tool summary omitted the decisive error. Verification still needs the underlying artifact.

A practical verification checklist asks whether the command ran, whether it exited successfully, which check failed, where the full output lives and what changed afterward. A summary that says only “tests failed” is not enough to guide the next action.

Tradeoff diagram comparing broad prompt input, shorter prefill wait and focused retrieval with possible missed context
Editorial tradeoff map from Anthropic’s large-codebase guidance. Focused retrieval can reduce request weight, but aggressive scoping can omit relevant code; no fixed savings are claimed.
Latency control checklist covering fixed fixtures, stage timestamps, token counts, tool intervals and stop reasons
Editorial measurement checklist based on documented stop reasons and troubleshooting boundaries. It does not prescribe a universal latency threshold.

Keep concurrency out of the latency conclusion

Parallel agents can reduce wall-clock time for independent work, but they complicate measurement. Shared resources, duplicate discovery and integration review can add cost that does not appear in one request trace.

Official: custom subagents start with isolated context, and the default concurrent subagent limit is 20, adjustable through CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS. The limit is not a recommendation to run twenty agents on one task.

The parallel-agent worktree pattern separates working state and branch ownership. It reduces shared-file collisions, but it does not eliminate merge conflicts or duplicated discovery.

For a latency benchmark, begin with one agent. Add concurrency only after the single-agent baseline is understood. Note whether read-only tools overlap and whether state-modifying tools remain sequential in the documented SDK loop.

Concurrency choice Potential benefit Measurement hazard
One agent Clear request attribution Slower total exploration
Read-only scouts Parallel candidate discovery Duplicate searches and reports
Separate worktrees Fewer shared-file collisions Merge and integration time
Many background agents More independent work in flight UI state and resource contention

The background subagent running-count diagnosis warns that a display can lag completion. Do not use a footer count as proof that model work is still running or consuming tokens.

Interpret a slow result in the right order

When a trial is slow, inspect the record before changing the model. First, confirm that the task and acceptance check stayed equivalent. Second, compare input volume and cache treatment. Third, separate first-token wait, output time and tool intervals.

If the first-token interval grew with a larger fresh prefix, prompt processing is a plausible contributor. Network, queueing and client overhead remain alternatives unless the instrumentation separates them. State that uncertainty in the report.

If output time grew, compare output length and stop reason. A longer explanation is not directly comparable to a short patch. If tool time grew, inspect the command and fixture rather than assuming model decode slowed.

If the run stopped without a useful result, classify the stop. Context exhaustion calls for a different response from a natural completion. A rate-limit error calls for access diagnosis, not a smaller context setting.

The 429 decision tree and usage tracking guide keep those events separate. A benchmark that mixes access failures with successful runs needs separate reporting.

The honest loss

A focused prompt can reduce input volume and make the next decision easier to inspect. Stable prefixes can also receive cache-read pricing when conditions match. Both are concrete wins when the retrieval remains correct.

The loss is that less context can miss the code that matters. A narrow package scope may exclude a cross-package caller, and a compact tool summary may omit the decisive exception. More context can improve coverage while increasing cost and latency. The useful choice depends on the task.

The public evidence does not provide universal prefill speed, decode speed, an ideal prompt size or a guaranteed token-saving percentage. It also does not prove that every long session feels slow. Future updates should revisit official performance guidance and publish repeatable traces with model, client version, cache state and raw stage timings.

Treat the benchmark as a local measurement, not a leaderboard. A result from one fixture cannot rank every model or predict every repository.

Verdict that long-context capacity is not speed and latency must be split into measured stages
Editorial verdict from the supplied official guidance. Context size, cache state and loop shape must be measured separately; no universal tok/s claim is supported.

Practical response: compare with an OpenAI-format agent

If you want to test the same fixture in another agent, preserve the task, tool set and acceptance checks. One AI API Key offers 46 live free model IDs through OpenAI-format agents such as OpenCode, Cline or Cursor. The quickstart uses https://api.oneaiapikey.com/v1, and the pricing page describes prepaid billing.

Free IDs do not work in Claude Code. The documented Claude Code route uses the Anthropic Messages format, but all four Claude IDs were unavailable on 2026-11-27. Use an OpenAI-format client for the active free lane. The API format guide explains the boundary.

The free lane shares 100 requests and 5,000,000 tokens per day per account, resets at 05:30 IST or 00:00 UTC, and permits one request in flight per key. Check the model catalogue for current availability. The cost calculator can estimate spend, but it cannot supply a missing latency measurement.

Use a disposable key with expiry and a narrow allowlist from the API reference. Read the privacy and retention policy, then create the evaluation account through sign-up. Save raw stage timings and token counts from both stacks. Different request construction means the comparison measures each agent and model together, not a universal model speed.

FAQ

Does a larger context window mean faster Claude Code responses?

No. Capacity and speed are different. Measure prompt processing, first-token wait, decode, tools and retries separately.

What is prefill versus time to first token?

Prefill is input processing before generation. Time to first token is the caller’s visible wait and can also include queueing, network and client overhead.

How many tokens per second should Claude Code produce?

The supplied sources publish no universal figure. Report measured output tokens and elapsed decode intervals under stated conditions instead.

Can caching remove long-context latency?

Caching can change input cost and processing treatment when a prefix is eligible and identical. It does not guarantee instant output or remove tool time.

How should a long-context benchmark stop?

Define completion and use appropriate loop controls. The Agent SDK documents turn and budget stops, while task budgets remain advisory hints.

More Claude Code troubleshooting

Sources

More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
  • 100requests
    per day
  • 3Mtokens
    per day
  • 47free
    models
  • $0per
    token
  • No card
  • No end date
Claim $10 credit →