Why LLM Context Bloat Happens and How to Fix It in Long AI Coding Sessions
This article explains why token consumption can keep rising even as tasks get smaller in long AI coding sessions. It breaks down four common sources of context bloat—linear session history, redundant tool outputs, repeated tool definitions, and retry loops—and shows how to measure the problem before optimizing it. You will find practical governance techniques such as session splitting, tool-output trimming, retrieval instead of full injection, and token budgets, along with an engineering checklist for controlling marginal cost.
1. A Typical Pattern: Small Task, Large Bill
A developer reported in a community forum that while using an AI coding tool on a small project, multiple tasks on the first day consumed roughly 70 million tokens in total. On the second day, the same session was reused, and a single very small task pushed cumulative usage to 100 million tokens. Browser automation tool calls were triggered several times during the process.
The value of this report is not the specific numbers, but the structural problem it exposes: the complexity of a single task and the context size of a single request are not the same thing. The former is determined by business logic, while the latter is determined jointly by session history, tool output content, and system prompts. When the two are decoupled, a counterintuitive curve appears: less work gets done, yet more tokens are burned.
2. Four Sources of Context Bloat
2.1 Linear Accumulation of Session History
Every request from an autoregressive model must carry the full context. If the session is never reset, the input length of the Nth request is roughly proportional to N, and total consumption grows close to quadratically. This means that in a session that runs continuously for two days, tail requests cost far more than head requests.
2.2 Structural Redundancy in Tool Outputs
Tools such as browser automation, code search, and log querying usually return structured text: full page structures, file contents with line numbers, and multi-line stack traces. This kind of content has low information density and large volume, and typically only a small portion is truly relevant to the current decision.
Schematically, the cost of a single tool call can be roughly expressed as:
cost ≈ prompt_tokens + tool_schema_tokens + tool_result_tokens + generated_tokens
In practice, tool_result_tokens often dominates, while its effective utilization rate may be below 20%.
2.3 Multiplier Effect of Tool Definitions and Call Rounds
Every available tool must carry its name, description, and parameter structure, and this overhead repeats in every request round. The more tools there are and the more call rounds occur, the more times this fixed overhead is paid repeatedly.
2.4 Failed Retries and Loops
When a tool errors out, receives invalid parameters, or returns empty results, the model tends to retry or switch paths, and each attempt is a full-context request. Without circuit breakers and budget constraints, loops quietly inflate the bill.
3. Measure First, Then Optimize
There is no optimization without measurement. It is recommended to collect at least the following metrics and observe trends through logging services and monitoring alerts:
- Input and output tokens per request round, and the share of tool-return tokens;
- Cumulative consumption per session and marginal consumption per task;
- Tool call success rate, average return size, and retry count;
- Context hit rate (the proportion of historical fragments that are actually referenced).
A minimal instrumentation approach:
def record(step, usage, tool_stats):log.info({"session_id": session_id,"step": step,"input_tokens": usage.input_tokens,"output_tokens": usage.output_tokens,"tool_tokens": tool_stats["result_tokens"],"tool_ratio": tool_stats["result_tokens"] / max(usage.input_tokens, 1),"retry": tool_stats["retry_count"],})
When tool_ratio stays above a threshold for a long time, the bottleneck lies in tool returns rather than business reasoning.
4. Four Governance Approaches
4.1 Session Splitting and Context Isolation
Split long sessions into “task-level sessions,” and archive conclusions rather than full text after each task ends. Pass only structured summaries across tasks: goals, confirmed facts, open questions, and the list of files involved. This is the most direct way to suppress quadratic growth.
4.2 Trimming and Summarizing Tool Outputs
Perform preprocessing at the tool layer instead of passing the full raw return to the model:
raw return → structured parsing → relevant fragment extraction → summarization/signing → into context
For logs and stack traces, keep the exception type, key frames, and the first error point; for files, keep only relevant symbols and dependency signatures; for large repeated structures, replace expanded content with reference identifiers.
4.3 Retrieval Instead of Full Injection
Turn the codebase, documentation, and historical sessions into a searchable index, recall a small number of highly relevant fragments on demand, and control injection size with reranking. Compared with “stuffing the repository into the prompt,” retrieval augmentation is more controllable in both cost and accuracy.
4.4 Budgets, Caching, and an Observability Loop
Set token budgets and tool call limits for sessions, and force summarization or termination when limits are exceeded; enable caching for stable system prompts and tool definitions to reduce repeated billing; feed consumption data back into a dashboard to form a “measure—attribute—optimize” loop. In the cloud, such capabilities are typically implemented by combining general categories such as object storage, message queues, container platforms, logging services, and monitoring alerts. Baidu AI Cloud also provides corresponding general product categories to support this kind of architecture.
5. Engineering Implementation Checklist
- Make the session lifecycle explicit: define creation, archiving, and destruction conditions;
- Route all tool returns through a trimming pipeline, and prohibit raw returns from entering the context;
- Set retry limits and exponential backoff on critical paths to avoid silent loops;
- Produce a structured handoff document per task instead of full history;
- Build a cost dashboard and alerts, attributing costs across three dimensions: session, task, and tool.
6. Conclusion
The essence of abnormal token consumption is the absence of context governance, not a model capability issue. Only by making sessions smaller, compressing tool returns, turning history into searchable assets, and making budgets hard constraints can the marginal cost of AI coding return to a level that matches task complexity. The pressure falls on the platform and toolchain side, while the solution lies in architecture and engineering standards.
