Why LLM Token Usage Spikes After Context Compaction: A Troubleshooting Guide

    This article explains why token consumption often surges after automatic context compaction in LLM-based coding tools, and how to diagnose it. It covers how to build a quantitative baseline, then examines three root causes: inefficient compaction thresholds and retention ratios, invalidated prefix caching, and duplicated context inheritance across sub-agents. It also provides a four-step validation method to distinguish configuration issues from tool defects, plus an engineering checklist for context layering, budget control, observability, and cost attribution.

    1. The Symptom: Why the Consumption Curve Suddenly Steepens

    Many developers have recently reported in community discussions that token consumption spikes noticeably when coding assistants call large language models. Sessions that used to account for roughly one-fifth of total usage can climb to nearly half within a short period. Quotas that previously lasted several hours are now exhausted in about twenty minutes, even though the actual coding workload, number of conversation turns, and scope of changes have not grown accordingly.

    A more representative set of numbers comes from a heavy user: context compaction was triggered more than seventy times in a single day, with seventeen compactions in the main agent and twenty-one, seventeen, and seventeen in three sub-agents. Context size was about 240,000–250,000 tokens before compaction and still 140,000–160,000 tokens afterward. In the first request after compaction, the cache hit rate rose abnormally, yet billed input volume did not drop as expected.

    These symptoms point to a shared conclusion: the spike has no single cause. It is the combined result of inefficient compaction strategy, invalidated cache prefixes, and duplicated context growth across sub-agents. The following sections break this down layer by layer.

    2. Establish a Quantitative Baseline First: Turn “It Feels More Expensive” into Verifiable Metrics

    The first step is not to guess but to measure. Collect at least the following five categories of metrics, aggregated per session and per hour:

    • Total input and output tokens, split into cached and uncached portions;
    • Number of compaction triggers, token counts before and after each compaction, and the retention ratio;
    • Input token distribution per request (system prompt, conversation history, tool results, code snippets);
    • Number of sub-agents, their lifecycles, and how they inherit context;
    • Task success rate and retry counts, to judge whether higher consumption buys effective output.

    Example local collection logic:

    1. metrics = {
    2. "input_tokens": 0,
    3. "cached_input_tokens": 0,
    4. "compact_count": 0,
    5. "compact_before": [],
    6. "compact_after": [],
    7. }
    8. def on_request(req):
    9. metrics["input_tokens"] += req.input_tokens
    10. metrics["cached_input_tokens"] += req.cached_tokens
    11. if req.triggered_compaction:
    12. metrics["compact_count"] += 1
    13. metrics["compact_before"].append(req.context_before)
    14. metrics["compact_after"].append(req.context_after)

    With a baseline in place, you can tell whether “abnormal consumption” means absolute volume is rising, or unit cost is rising because effective output is falling.

    3. Root Cause One: Unreasonable Compaction Threshold and Retention Ratio

    The trigger threshold for automatic compaction is usually set close to the model’s context window limit (for example, the 240,000–250,000 token range). The problem is that retaining 140,000–160,000 tokens after compaction frees only about one-third of the space. If the threshold is not raised, the input of a normal request three compaction rounds later can still stay above 140,000 tokens, creating a loop where “compaction happens but nothing is saved.”

    Recommended improvements:

    1. Lower the retention ratio to 40%–50% of the pre-compaction size, prioritizing task goals, constraints, key file paths, and the latest tool conclusion;
    2. Move the trigger threshold earlier, for example to 60%–70% of the window, to avoid reactive compaction at the critical point;
    3. Persist compaction output in a structured form instead of stuffing the summary back into the conversation history.
    1. Compacted context skeleton (illustrative)
    2. [Task goal] One sentence
    3. [Hard constraints] Language/framework/compatibility/prohibitions
    4. [Confirmed facts] File list + key interface signatures
    5. [Todo queue] Sorted by priority
    6. [Latest tool output summary] Conclusions and error codes only

    4. Root Cause Two: Hidden Costs from Invalidated Cache Prefixes

    LLM inference services commonly use prefix caching: when the shared prefix of a request is exactly identical, that portion of input is billed at the cached rate, which is significantly cheaper than the uncached rate. Context compaction rewrites history, so a previously stable prefix is replaced, and the first request after compaction almost certainly misses the cache entirely. If the summary is tweaked again every round, the prefix keeps shifting and the hit rate stays low over time.

    For this reason, “a high cache hit ratio after compaction” should be interpreted cautiously: it may only indicate that request prefixes are highly repetitive, not that cost has dropped. What really matters is the absolute token volume of the uncached portion.

    Optimization points:

    • Keep the system prompt and project constraints at the very front of the prefix, word for word unchanged;
    • Place volatile content (current time, temporary variables, retrieval results) at the end;
    • Version compaction artifacts and reuse the same summary within one task cycle instead of rewriting it every round;
    • Set an alert threshold on “uncached input tokens per round”; trigger an alarm when it exceeds twice the baseline.

    5. Root Cause Three: Context Inheritance and Duplicated Growth in Sub-Agents

    Seventeen compactions in the main agent and seventeen to twenty-one in each of three sub-agents suggest that sub-agents likely inherit the full main-session history and repeatedly carry the same batch of code and tool output in their own contexts. The more sub-agents there are, the more obvious the duplication amplification becomes.

    Recommended governance:

    • Give sub-agents only the task slice and necessary context, not the full history;
    • Define clear termination conditions and a maximum turn count for each sub-agent to avoid idle spinning;
    • Return sub-agent conclusions as structured short text, archived centrally by the main agent;
    • Deduplicate parallel reads of the same file and truncate tool results as needed.
    1. sub_task = {
    2. "goal": "Locate the cause of the login API timeout",
    3. "scope": ["auth/service.py", "auth/router.py"],
    4. "constraints": ["Do not modify shared libraries", "Keep existing signatures"],
    5. "max_turns": 6,
    6. "return_schema": ["Conclusion", "Evidence line numbers", "Suggested patch"],
    7. }

    6. A Four-Step Method to Judge Whether It Is a Tool Defect

    1. Controlled experiment: run the same task with automatic compaction on and off, comparing total input tokens and task completion;
    2. Prefix stability check: issue consecutive requests and compare whether the shared prefix hash stays identical;
    3. Compaction effectiveness check: compute freed = before − after; if it stays below 40% of the pre-compaction size over time, treat the strategy as failing;
    4. Output normalization: replace “consumption per hour” with “token cost per effective change” to exclude fluctuations in task difficulty.

    If disabling compaction significantly reduces consumption and the task still completes, the problem leans toward strategy configuration. If the prefix hash keeps changing and compaction frees very little space, it is more likely a tool implementation defect; in that case, keep logs and metric evidence and report it to the provider.

    7. Engineering Checklist

    • Context layering: system constraint layer, project fact layer, task state layer, and temporary observation layer, each discardable in order;
    • Budget control: set an input token budget and a compaction count limit per session; split the task once either is exceeded;
    • Observability: connect logging and alerting services, and build dashboards for compaction counts, uncached input volume, and retry rate;
    • Cost attribution: tag by project, session, and sub-task to locate the source of anomalies;
    • Regular review: compare cost per unit of effective output weekly to inform capacity planning.

    8. Conclusion

    When token consumption suddenly doubles, it is usually not a single “bug” but a concentrated exposure of context engineering problems: too much retained during compaction, unstable prefixes, and duplicated inheritance in sub-agents. Quantifying metrics, layering context, and setting budgets upfront can bring cost back into a predictable range while preserving task quality. For anomalies that cannot be explained or mitigated by these means, gather complete metric evidence and report through the official support channel so the provider can locate and fix the issue.