AI Coding Assistant Token Usage Spikes: Diagnosing Context Compaction and Caching
Unexpected token usage in AI coding assistants can reflect changes in metering, context compaction, cache reuse, or multi-agent execution. This article explains how to build a request-level token ledger, trace compaction and cache misses, identify hidden amplification from agents and tools, and distinguish product regressions from workload-driven costs. It also outlines practical controls for budgets, context size, retries, and stable cache prefixes.
AI Coding Assistant Token Usage Spikes: Diagnosing Context Compaction and Caching
Developers have recently reported unexpected token consumption in an AI coding tool after a particular time window. Reported quota usage rose from roughly 20% to 50% in a short period, while some users with larger allowances felt that an hourly quota was exhausted within 20 minutes—even though their usage intensity had not noticeably changed.
Reports also described frequent automatic context compaction in multi-agent workflows. One account recorded approximately 72 compaction events in a day: 17 for the main agent and 21, 17, and 17 for three subagents. Context size was around 240,000–250,000 tokens before compaction and still 140,000–160,000 tokens afterward, with a reported trigger threshold of approximately 244,800 tokens. Cache hits also became inconsistent after compaction, preventing reliable reuse of previously cached prefixes.
These symptoms should not automatically be attributed to either a product defect or increased user activity. A systematic investigation needs to cover five layers: metering, compaction, caching, agent orchestration, and tool calls.
1. Separate Actual Usage Increases from Perceived Increases
Unexpected token consumption generally falls into two categories: changes in billing or metering, and longer execution paths.
Metering changes may affect the billing units applied to otherwise identical requests, how cache reads and writes are counted, or whether compaction calls are charged separately. Longer execution paths involve increases in request counts, input lengths, retries, subagent calls, or tool output fed back into the model.
A quota that appears to drain faster may therefore reflect genuinely higher usage, or a change in quota pools, cache discounts, or the accounting treatment of compaction calls.
The first step is to build a token ledger, rather than assume a defect. For each request, record:
- Input and output tokens
- Cache-hit and cache-write tokens
- Tokens used by compaction calls
- Subagent tokens
- Tool-result tokens
- Request ID, session ID, and agent role
- Associated compaction events and cache-prefix hashes
Breaking consumption down into the smallest explainable units makes it possible to identify the layer responsible for the increase.
2. How Automatic Context Compaction Can Amplify Usage
Automatic context compaction frees space as a conversation approaches the context-window limit. It may summarize, trim, or reorganize earlier messages.
Compaction is not free, however. It requires one or more model calls, and the resulting summary changes the prefix of subsequent requests. If the strategy retains too much content, it frees only limited space before the next compaction becomes necessary.
The reported reduction from approximately 240,000–250,000 tokens to 140,000–160,000 tokens leaves the session at a relatively high context level. Continued growth can bring it back to the trigger threshold quickly.
More importantly, compaction changes cached prefixes. Most prefix-caching mechanisms depend on stable prefix matches. Rewriting conversation history can invalidate existing cache keys, requiring subsequent inputs to be processed again.
If the compacted result is not persisted consistently, or if the summary varies slightly each time it is generated, costs can accumulate through three mechanisms:
- The compaction call itself
- Cache misses after compaction
- Repeated processing of input that was previously reusable
At 72 compaction events per day, compaction calls, subsequent requests, and cache rebuilding may form a chain of amplified consumption.
3. Multi-Agent Fan-Out and Tool Loops Are Hidden Amplifiers
When a main agent coordinates several subagents, repeated context transfer is a common source of overhead. The main agent may send its full history to each subagent, receive their results, and then process those results again during synthesis. Every fan-out can duplicate substantial amounts of context.
If subagents also compact their own histories, both compaction frequency and cache invalidation can multiply. The reported subagent counts of 21, 17, and 17 compactions show that this was not a single event at the main-agent level: it was distributed across the orchestration tree.
Tool calls can add further overhead through:
- Excessively long tool outputs
- Retries after errors
- Duplicate tool results inserted into context
- Agent replanning after failures
Without retry backoff and deduplication, a single failure can trigger repeated cycles of reading results, compacting context, and submitting another request.
Investigations should therefore examine tool-output truncation, retry limits, deduplication of inter-agent messages, and subagent lifecycles.
4. Investigate Prefix Stability When Cache Hits Decline
A lower cache-hit rate does not necessarily indicate a failure in the cache system. Common causes include:
- Timestamps or random IDs dynamically inserted into system prompts
- Different wording in successive compaction summaries
- Unstable ordering of tool results
- Changes in the order used to merge multi-agent messages
- Cache keys that include session state that is not updated promptly
Compare prefix hashes before and after compaction, across successive requests from the same agent, and between the main agent and its subagents.
The following pseudocode illustrates the diagnostic approach:
for request in trace:key = hash(stable_system_prompt + stable_history_prefix)log(request.id, key, request.input_tokens,request.cache_hit_tokens, request.compress_event_id)if cache_hit_tokens / input_tokens < baseline:analyze_prefix_diff(request)
If cache-hit ratios deteriorate after compaction, check whether:
- The compacted result is written to the cache as a stable prefix
- Compaction invalidates the old cache before a replacement is established
- Metering counts uncached input more than once
These checks help distinguish prefix instability from cache infrastructure problems or accounting errors.
5. Determine Whether the Behavior Is a Product Defect
A product-defect diagnosis should rest on reproducible evidence. Under the same input, session, and agent configuration, investigate whether:
- Consumption is significantly above the established baseline
- Compaction triggers behave erratically, such as firing below the threshold or failing to reduce context size
- Cache keys change for nonsemantic reasons
- Subagents are activated unexpectedly
- Retries form loops
- Metering logs agree with request logs
If the behavior appears only in a particular version, configuration, or time window—and can be reproduced through a rollback or feature toggle—it is more consistent with a product defect or policy regression.
If it correlates strongly with long sessions, multi-agent workflows, and large tool outputs, it is more likely to result from the interaction between workload patterns and compaction strategy.
6. Controls for Reducing Consumption
Short-Term Controls
Use tiered compaction thresholds and processing stages, trimming low-value tool output before summarizing conversation history. Keep summary templates and post-compaction prefixes stable to reduce cache invalidation.
Additional controls include:
- Limiting how much context subagents inherit
- Capping tool-output length
- Adding retry backoff, deduplication, and an overall retry budget
- Setting token-budget alerts for each session
Medium-Term Observability
Trace compaction events, cache hits, agent fan-out, tool calls, and billing details together.
Establish consumption baselines and compare versions through staged rollouts. Users with larger quotas should also have access to a breakdown showing where their allowance is being consumed.
Long-Term Orchestration Improvements
The main agent should pass only the task summary a subagent needs, rather than its entire history. Subagents should return structured results.
Compacted context should be persisted and versioned, while cache keys should use stable semantic prefixes.
Conclusion
Unexpected token consumption is often better understood as an interaction among compaction strategy, cache prefixes, multi-agent fan-out, and metering rules than as a single isolated defect. A rapidly declining quota alone is not enough to establish the cause.
Use a request-level token ledger and a trace of compaction events to locate the source of the increase. Then combine budget controls, output truncation, stable prefixes, and tighter agent context boundaries to manage costs without undermining the coding assistant’s usefulness.
