AI Coding Tools: Troubleshooting Unexpected Token Usage
Unexpected spikes in token usage can stem from repeated context compaction, cache misses, duplicated multi-agent context, or platform-side changes. This guide explains how to measure cost per task, identify likely causes, and reduce unnecessary consumption through context management, stable request prefixes, and monitoring.
1. Symptoms: Token Usage Spikes While Workload Stays the Same
Recent user reports describe a consistent pattern: token consumption increases severalfold over a given period despite little or no change in usage habits. Three symptoms stand out:
- A sudden shift in usage share: High-context workloads rise from roughly 20% of normal usage to around 50%.
- Rapid quota depletion: A quota that previously supported several hours of work is exhausted in about 20 minutes.
- Frequent compaction: Automatic context compaction occurs dozens of times a day. The main agent and multiple subagents trigger it independently, pushing the combined count far above normal levels.
The combination of unchanged workload and doubled consumption is an important diagnostic signal. If consumption rises alongside task complexity, the increase may be expected. If the two diverge, context management or the billing path is a likely source of the problem.
2. Four Main Causes
2.1 Compaction Thresholds and Insufficient Space Recovery
Many AI coding tools use a sliding context window with automatic compaction. As the context approaches the model’s limit—for example, around 240,000 tokens—the tool summarizes older content while retaining important recent material.
The problem is how much space compaction actually recovers. User reports describe contexts of approximately 240K–250K tokens before compaction that still contain 140K–160K tokens afterward. This leaves a large residual context and can provide insufficient headroom:
- Compaction requires an additional model call, using the full context as input and producing a summary.
- If the remaining context is still large relative to the threshold, subsequent requests can quickly trigger another compaction cycle.
- Repeated full-context inputs can multiply costs.
The following illustrative logic shows how this can happen:
def maybe_compact(ctx, limit=244_800, keep_ratio=0.6):if ctx.tokens < limit:return ctx, False# Compaction: an additional model call with the full context as inputsummary = call_model(prompt=SUMMARIZE_TPL, context=ctx)kept = ctx.tail(int(limit * keep_ratio))new_ctx = merge(summary, kept)return new_ctx, True # Note: new_ctx.tokens may still be close to limit
If keep_ratio is too high, or the summary has no length constraint, compaction may fail to reduce context usage enough to prevent repeated triggers.
2.2 Cache Misses and Repeated Input Charges
Many model services offer discounted pricing for cached request prefixes, so cache utilization directly affects cost. In a normal multi-turn conversation, compaction changes the prefix and naturally invalidates its existing cache. Some loss of cache reuse is therefore expected.
However, the impact can become much larger when:
- The compacted context remains very long and its prefix changes repeatedly, preventing a stable cache from forming.
- Requests include timestamps, random IDs, dynamic file lists, or other frequently changing fields that disrupt prefix stability.
- Parallel agents maintain separate contexts whose prefixes are not reused across agents.
When the cache misses, the full input is charged at the uncached rate. Combined with the extra calls required for compaction, this creates two sources of cost amplification.
2.3 Duplicated Context Across Multiple Agents
When a main agent delegates work to subagents, inheriting the entire context rather than passing only the minimum necessary information can duplicate the same codebase context several times.
One reported example involved 17 compactions by the main agent and 21, 17, and 17 compactions by three subagents. This pattern is consistent with independently expanding contexts: the overall compaction count accumulates across agents rather than being managed through a shared context.
2.4 Platform-Side Changes to Behavior or Usage Accounting
Platform-side factors should also remain under consideration. Model updates may change default context policies, usage accounting may be revised, or a staged rollout may introduce a regression.
Client-side observations alone cannot establish these causes. Verification requires official status notices and support-ticket responses.
3. Verification: Turn “It Feels More Expensive” into Evidence
The key to determining whether there is a defect is to establish a baseline for cost per task. Collect the following metrics:
| Metric | What it measures | Warning sign |
|---|---|---|
| Input tokens per request | Input volume used for billing | Requests consistently approach the limit |
| Compactions per hour | Pressure on context management | An order-of-magnitude increase |
| Post-compaction retained ratio | Space recovery efficiency | Consistently above 50% |
| Cache hit rate | Effectiveness of prefix reuse | A significant decline from the historical baseline |
| Total cost per task | Consumption required to complete the same requirement | A twofold increase unrelated to complexity |
The following illustrative script summarizes token usage and compaction activity:
import json, statistics as stdef analyze(log_path):rows = [json.loads(l) for l in open(log_path)]inp = [r["input_tokens"] for r in rows]hit = [r.get("cached_tokens", 0) / max(r["input_tokens"], 1) for r in rows]comp = sum(1 for r in rows if r.get("event") == "compaction")print(f"Requests={len(rows)} Compactions={comp}")print(f"Median input tokens={st.median(inp):.0f} Peak={max(inp)}")print(f"Mean cache hit rate={st.mean(hit):.2%}")# Per-task usage proxy: total input tokens / task counttasks = len({r["task_id"] for r in rows if r.get("task_id")})print(f"Average input tokens per task={sum(inp)/max(tasks,1):.0f}")
If compaction frequency increases, cache utilization declines, and cost per task doubles, context management and caching are the primary areas to investigate.
If these metrics remain stable while the bill rises, prioritize checking usage-accounting changes or other platform-side updates. Contact the provider and preserve the relevant logs.
4. Mitigation and Optimization Practices
Reduce the compaction retention ratio. Aim to keep the post-compaction context within 40% of the trigger threshold. This gives compaction enough room to work and helps prevent repeated triggers.
Stabilize request prefixes. Place static content—such as system instructions, project conventions, and directory structure—at the beginning of requests and keep it consistent. Remove volatile fields such as timestamps and random identifiers from the reusable prefix.
Pass only the minimum necessary context. Give subagents only the files and excerpts directly relevant to their tasks. Avoid full-context inheritance to limit duplicated context growth.
Split work into independent stages. Break large requirements into smaller tasks with independently verifiable results. Reset context deliberately at stage boundaries instead of relying entirely on automatic compaction.
Make observability routine. Send the metrics above to logging and monitoring systems. Configure cost-per-task alerts, and pause execution with a notification when abnormal consumption is detected.
Preserve supporting evidence. Record timestamps, request volumes, compaction counts, and billing changes. Submit this evidence through official support channels to help the provider identify possible staged-rollout regressions.
5. Conclusion
Unexpected token consumption does not automatically indicate a defect. However, when an unchanged workload, doubled consumption, ineffective compaction, and cache failures occur together, the interaction between context management and billing is the leading area to investigate.
The most effective response is measurement rather than speculation. Establish a cost-per-task baseline, use the data to distinguish configuration issues from mechanism side effects and platform regressions, and adjust compaction policies, context handoffs, and observability accordingly.
