Token Cost Optimization for AI Coding Assistants: A Practical Guide
A real-world look at why a single AI coding session can consume 9.7 million tokens while still costing very little, how tiered pricing splits tokens into direct input, cache creation, cache reads, and output, and ten practical strategies for keeping cache hit rates high. You will learn how context actually grows, why long sessions are usually cheaper than short ones, and how to treat context as a layered resource so the same budget completes more work.
Introduction: A Usage Bill That Makes Developers Uneasy
At the end of a project that had been iterating all day, I closed the terminal and checked the usage breakdown. A single session had accumulated 9,721,744 tokens. The number alone is enough to make anyone nervous, but the useful conclusion lives in the distribution, not the total.
Broken down by type, the pattern is heavily skewed: direct input accounts for roughly 0.03%, cache creation about 8.1%, cache reads about 91.7%, and model output about 0.15%. In other words, more than ninety percent of the consumption falls into the cheapest category. There is an order-of-magnitude gap between a “ten-million-token” headline figure and the actual billed cost.
This leads to the core argument of this article: in AI coding tools, whether a cost is reasonable cannot be judged by the total token count alone, but by its structure. A healthy long session is often cheaper than a short session that is restarted frequently.
1. The Four Identities of a Token: Same Name, Different Price
Mainstream large model services generally use tiered pricing, and the same text is priced completely differently depending on where it appears:
- Direct input: the context actually sent with this request, billed at the standard rate. This is the most expensive tier.
- Cache creation: when the context exceeds the provider’s minimum threshold (commonly on the order of 1024 tokens), the system can write the prefix into a cache. This step is charged extra, usually slightly above direct input, because it includes storage cost.
- Cache reads: when a later request hits the cached prefix, you pay only a small fraction of the standard rate (commonly around one tenth). This is the fundamental reason longer sessions are more economical.
- Model output: generated content is typically billed at several times the standard rate, but in tasks such as code completion, refactoring, and batch rewriting, output usually makes up a very small share.
The practical rule that follows: the higher the cache read share, the lower the cost per unit of output. To judge whether a session was efficient, look at the cache read ratio first, then at output quality.
Note that specific rates, thresholds, and discount ratios should be confirmed against the provider’s current official documentation. This article only discusses structural patterns.
2. What Actually Inflates the Context: Four Real Sources
Reviewing the cache creation peaks of several long sessions segment by segment, the sources of growth are highly concentrated:
- Tool definitions and system prompts: every request must carry the list of available tools and behavioral constraints. This is fixed overhead, substantial in length and impossible to omit.
- Repeated injection of file contents: after several large files are read, their contents reappear as a prefix in every subsequent round of requests.
- Command output and logs: raw output from tests, builds, and dependency installs can run to thousands of lines while carrying very low information density.
- Residue from failed attempts: rejected approaches, rolled-back changes, and duplicate search results all stay in the context and keep being billed.
A typical high-cost case is cache expiry: in one session, the idle gap while waiting for an external process to return exceeded the cache lifetime window (commonly a TTL on the order of minutes). When the next question came in, the prefix cache had already expired and the system was forced to rewrite a cache of several hundred thousand tokens. That single operation produced an abnormal jump of roughly 23% in the day’s quota. This kind of loss raises no error and interrupts nothing; it shows up only on the bill, which is exactly why it is so easily overlooked.
3. Ten Actionable Token Optimization Strategies
Strategy 1: Read structure first, full text second. Use search operations to locate symbols and line numbers, then read only the necessary fragments. Changing “read the whole file” into “read the target function” typically reduces input by an order of magnitude.
Strategy 2: Keep fixed overhead from growing. Trim custom instructions, put long-lived conventions into a project-level configuration file, and keep one-off explanations in the current turn of conversation, so that every message does not carry them again.
Strategy 3: Clear failed context promptly. Once an approach is rejected, state explicitly “abandon this direction, keep only the conclusion,” or start a new session carrying a summary of the conclusion, so the wrong path does not occupy space indefinitely.
Strategy 4: Manage the pace of long tasks deliberately. Keep work moving inside the cache lifetime window and avoid long gaps. If you must wait on an external process, do read-only analysis to keep the session active, or split the work into segments and lock in conclusions at the end of each one.
Strategy 5: Move large output to disk. Have tools write complete build, test, and dependency-installation logs to files, keeping only a summary and the failing fragments in context, and re-read specific line ranges when needed.
Strategy 6: Isolate noise with subtasks. Hand broad searches and batch scans to an independent sub-session and return only the conclusions to the main session, keeping the main context lean.
Strategy 7: State task boundaries clearly in one pass. Specify the goal, constraints, acceptance criteria, and the scope that must not be changed, reducing the rounds of back-and-forth clarification. Rounds themselves are a cost.
Strategy 8: Persist long-term knowledge in structured form. Put stable project conventions into configuration or documentation and let tools load them on demand, instead of restating them repeatedly in conversation.
Strategy 9: Separate “exploration” from “execution.” A wider context is acceptable during exploration; before entering execution, compress it into a clear task list so exploration noise does not leak into implementation.
Strategy 10: Build a usage observability habit. Regularly check the token type distribution, cache hit rate, and cost per task, map abnormal peaks back to specific operations, and form a loop that supports continuous optimization.
4. Context Engineering: Turning “Less Consumption” into “More Output”
The strategies above reduce to one engineering method: manage context as a finite, layered resource.
- Hot layer: the current task’s goal, constraints, and acceptance criteria, always retained.
- Warm layer: the file fragments and related symbols being modified, loaded on demand and discarded after use.
- Cold layer: complete logs, historical approaches, and full search results, saved to disk and retrieved on demand through search.
Combined with a conclusion-first communication style—state the conclusion and constraints first, then the evidence that is actually needed—you can keep the cache read ratio consistently high without sacrificing output quality.
In real engineering practice, this kind of context management need maps naturally onto general-purpose cloud capabilities: code and documents can be hosted in object storage and pulled on demand, intermediate artifacts of long tasks can be decoupled through a message queue, batch analysis can run on a container platform, and observability of usage and elapsed time can be closed-loop through logging services with monitoring and alerting. The general-purpose capabilities offered by Baidu AI Cloud in these categories can serve as a reference foundation for building such an observability and scheduling system.
5. Common Misconceptions
- Misconception 1: Fewer tokens is always better. The goal is to maximize output per unit cost, not to minimize absolute consumption; probing repeatedly to save tokens only adds rounds.
- Misconception 2: Long sessions are necessarily expensive. As long as the cache keeps hitting, the marginal cost of a long session is extremely low.
- Misconception 3: Looking only at the total, not the distribution. Bill analysis that does not distinguish types can hardly locate the problem.
- Misconception 4: Treating compression as deleting information. The effective approach is layering and writing to disk, not discarding key constraints.
Conclusion
Back to that ten-million-token bill: what actually needed fixing was not the total, but the 23% anomaly caused by cache expiry and the repeatedly injected files and logs. Understanding the four identities of a token, recognizing the sources of context growth, and replacing mindless accumulation with layering and disk persistence lets you complete more tasks on the same budget. The essence of cost optimization is a direct expression of context engineering capability.
