Token Cost Optimization in AI Coding Sessions: Why Token Structure Matters More Than Volume
A single AI coding session can consume millions of tokens, yet the actual bill may be a fraction of what the raw number suggests. This article breaks down the four token types used in mainstream LLM API pricing, traces where context bloat really comes from, and lays out practical cost-control techniques—context layering, cache-friendly ordering, retrieval instead of full-file feeding, task splitting, and observability—along with how to embed these practices into a team's development workflow.
A single session consumed 9.72 million tokens. The number looks alarming at first glance, but the breakdown tells a very different story: more than 90% of it was low-cost cache reads. That gap points to a widely overlooked fact—what determines the cost of AI coding tools is not the absolute number of tokens, but the structure of those tokens. This article starts from the pricing logic of four token types, traces the real sources of context bloat, and offers cost-governance practices you can actually apply.
1. A Counterintuitive Bill
After one long session, the usage panel showed roughly 9.72 million tokens consumed. The instinct is usually to close the tool and restart the session. But breaking the usage down by type looks like this:
| Type | Count | Share |
|---|---|---|
| Direct input | 29,710 | 0.03% |
| Cache write | 790,452 | 8.1% |
| Cache read | 8,913,330 | 91.7% |
| Model output | 14,991 | 0.15% |
More than 90% was cache reads, and cache reads typically cost only about one-tenth of direct input. In other words, the “tens of millions” on the dashboard translated into actual billing of just a fraction of that number.
The conclusion is not “don’t worry about spending money.” It is this: token count is a vanity metric; token structure is the cost metric. To optimize cost, you have to optimize structure.
2. The Cost Semantics of the Four Token Types
Mainstream LLM API pricing generally splits tokens into four categories, with price differences reaching tens of times:
- Direct input: the context actually sent to the model in this request, at standard pricing—the most expensive.
- Cache write: once the context exceeds the platform’s minimum cache threshold (commonly on the order of a thousand tokens), the system stores it as a reusable cache. This write costs about 1.25x direct input—more expensive than direct input, because it includes storage cost.
- Cache read: subsequent requests that hit the cache are billed at roughly 1/10 of direct input. This is the underlying reason “longer sessions get cheaper.”
- Model output: usually 3–5x direct input, but a very small share in coding scenarios (only 0.15% here), because generated code is always “short” relative to the input context.
This yields the first core rule: the higher the share of cache reads, the lower the cost per question. A second rule is just as important: cache write is the only “premium action”—frequently invalidating the cache means repeatedly paying the 1.25x rate.
Keep in mind that the exact multipliers, minimum cache thresholds, and cache time-to-live (TTL) differ across platforms. In engineering practice, defer to the official pricing documentation of the platform you use, and don’t treat one vendor’s numbers as universal constants.
3. What Is Inflating the Context
Reviewing the “cache write peaks,” the sources of bloat are highly concentrated:
- Full-file feeding: stuffing an entire directory into the context, where 80% of the content is irrelevant to the current task.
- Repeated tool definitions and system prompts: carried on every request, a fixed overhead.
- Long-chain history buildup: early trial-and-error logs and failed patches all retained.
- Large artifacts: build logs, dependency manifests, and generated files pasted in as-is.
A practical rule of thumb: if a piece of context hasn’t been referenced in the last three exchanges, it’s probably just cost, not information.
4. Five Practical Optimization Techniques
1. Context layering
Split information into a resident layer (system constraints, coding standards), a task layer (current target files and interface definitions), and a temporary layer (logs and intermediate artifacts). Only let the resident and task layers enter the main session.
2. Cache-friendly ordering
Caching matches by prefix. Put stable content first and volatile content last to avoid “editing one comment invalidates the whole cached block”:
[system constraints] → [project standards] → [stable interface definitions] → [current task description] → [volatile logs]
3. Retrieval instead of feeding
Let the tool search and locate the relevant snippets first, then feed only the matched snippets into the context. One extra cheap retrieval beats one expensive feed.
4. Task splitting and new sessions
One session solves one verifiable small goal. When switching tasks, start a new session decisively—the 1.25x premium of rebuilding the cache is usually far lower than the ongoing cache-read cost of a long history chain.
5. Observability
Establish minimal metrics: per-round usage of the four token types, cache hit rate, and cost per question. Without measurement, optimization is guesswork.
5. Embedding Cost Governance into the Development Workflow
In team or enterprise settings, these practices need to grow from personal habits into platform capabilities: set thresholds on abnormal usage through monitoring and alerting, retain call chains via logging services for attribution, consolidate standards into unified configuration management, and make “context layering” a default constraint rather than individual diligence. In engineering practice like this, Baidu AI Cloud typically combines general-purpose capabilities such as object storage, logging services, and monitoring and alerting; refer to the official documentation for specific pricing and quotas.
Conclusion
Cost optimization for AI coding is not fundamentally about “using less,” but about “using the right structure.” The next time you see a bill in the tens of millions of tokens, don’t panic—break it down by the four token types: cache reads at 90% mean you’re on the right track; repeated cache writes are what actually needs fixing.
