Optimizing Token Costs in AI Coding Sessions: A Practical Guide
An analysis of a 9.72 million token AI coding session shows that total token count does not equal cost, since cached reads are typically billed at about one-tenth of direct input. This article explains the four token categories, why context structure drives spending, and four reusable practices: building a stable context prefix, splitting work into minimal verifiable units, increasing input information density, and making cost observable through metrics. It also covers common misconceptions about token usage, session length, model output, and switching models.
1. Introduction: A 9 Million Token Session With a Surprising Bill
After an AI coding session ended, the statistics panel showed a cumulative consumption of roughly 9.72 million tokens. The first reaction is usually panic, but breaking the details down reverses the conclusion: about 91.7% was cache reads, cache creation was about 8.1%, and direct input plus model output combined was less than 0.2%.
This distribution reveals a key fact: total token count does not equal cost. Under the prompt caching billing model widely used across the industry, the unit price of a cache read is typically only about one-tenth of direct input, cache creation is priced slightly higher than direct input, and model output is usually several times the price of direct input. As a result, a session that “looks like an astronomical number” may actually cost only a fraction of the surface figure.
What deserves real attention is not the total volume but the structure: which content is being repeatedly written into the cache, which content could have gone unread, and which tasks were not broken down finely enough. From a general technical perspective, this article presents a reusable methodology to help developers solve enough problems with the fewest tokens in AI coding tools.
2. First, Understand the Four “Identities” of Tokens
Specific prices vary by vendor, but the billing dimensions are highly consistent and usually fall into four categories:
- Direct Input: The context actually sent to the model in the current request, charged at standard pricing, the most expensive.
- Cache Creation: When the context exceeds the platform’s minimum cache length (commonly on the order of 1024 tokens), the system writes the prefix into the cache, and this write is billed at a price higher than direct input.
- Cache Read: Subsequent requests hit the cache and are billed at only about one-tenth of the input price.
- Model Output: Content generated by the model, with a unit price usually several times that of input, but a very low share in coding tasks.
The core rule is a single sentence: the higher the share of cache reads, the lower the cost per question. So the optimization goal is not to “use fewer tokens” but to “make tokens reusable repeatedly at a low price.”
A schematic cost estimation logic can be written as:
Cost per request ≈ Input×P_in+ CacheCreation×P_in×1.25+ CacheRead×P_in×0.1+ Output×P_in×4
When the share of CacheRead exceeds 90%, the total cost is significantly lower than an estimate based on total volume.
3. What the Real Data Reveals: What Inflates the Context
Reviewing that 9.72 million token session, the peaks in cache creation clustered around a few types of actions:
- Reading large files all at once: Pasting an entire source file of thousands of lines into the context and carrying it through every subsequent turn.
- Pasting long logs and stack traces: Build failure logs can easily reach tens of thousands of tokens while carrying very low information density.
- Switching tasks repeatedly: The context prefix changes frequently, causing the cache to be invalidated and rewritten over and over.
- Full retrieval instead of precise retrieval: Pulling in the contents of an entire directory rather than only the relevant fragments.
The conclusion is clear: what inflates the context is often not model output but the human habit of taking the easy way with input.
4. Method 1: Build a Stable Context Prefix
A cache hit requires the prefix to be exactly identical. So put unchanging content at the very front and volatile content at the end:
[System constraints + coding standards + project structure notes] ← stable, hits cache long-term[Relevant file fragments + interface definitions] ← semi-stable[The specific request this time + latest error] ← changes every turn
Practical points:
- Do not paste the same standards every turn; fix them once in the upfront instructions.
- Avoid modifying earlier messages mid-session; any change invalidates subsequent caching.
- When switching tasks, prefer starting a new session instead of jumping around within the same one.
5. Method 2: Split Large Tasks Into “Minimal Verifiable Units”
Long sessions are not inherently cheaper; they only pay off when the cache keeps hitting. A more reliable approach is to control the size of each session:
- Break requirements into small, independently verifiable steps: read code → locate → change one place → run tests.
- End the session once a closed loop is complete, and build a small, precise context again for the next task.
- Provide only the necessary files and line ranges, using retrieval to locate instead of feeding everything in.
This pushes the direct input of each request to the minimum and reduces the number of cache creations accordingly.
6. Method 3: Compress the Information Density of Input
- Filter logs before feeding them: keep only the error type, key stack frames, and reproduction steps.
- Read large files by symbol: give class names, function names, and fragments rather than the whole file.
- Replace raw pasting with structured descriptions: interface signatures, data table fields, sample expected outputs.
- State clearly “what not to do” to reduce extra rounds caused by the model’s ineffective exploration.
Once information density improves, the number of rounds needed to solve a problem drops, and tokens drop naturally.
7. Method 4: Make Cost Observable
Optimization must be built on measurement. It is advisable to record at least four metrics: direct input volume, cache creation volume, cache read volume, and output volume, then calculate the cache hit rate and cost per question. In engineering practice, log services, monitoring alerts, and object storage can support archival analysis; on cloud platforms such as Baidu AI Cloud, general capabilities like log collection, metric dashboards, and alert rules can complete this observability loop without relying on any proprietary interface.
When the cache hit rate declines continuously, it usually means the context prefix is unstable or tasks are being switched too frequently, which is a clear optimization signal.
8. Common Misconceptions
- Misconception 1: Fewer tokens is always better. In fact, a bit more low-price cache reading can lower the total cost.
- Misconception 2: Longer sessions save more. This only holds when the prefix is stable; frequent changes repeatedly trigger cache creation.
- Misconception 3: Treating model output as the main cost. In coding scenarios, output usually accounts for a very low share; the bottleneck is input structure.
- Misconception 4: Solving cost by switching models. Without changing the structure, any model will repeat the same waste.
9. Conclusion
The essence of “solving enough problems with the fewest tokens” is treating context as a structure that needs design rather than a dumping ground for casual pasting. Get these four things right—stable prefixes, fine-grained tasks, high-density input, and observable metrics—and both total token volume and the bill will drop at the same time.
