Token Cost Optimization for AI Coding Sessions: A Practical Guide
An analysis of token usage in long AI coding sessions reveals why a high token count does not translate into a proportional bill, how prompt caching changes the cost structure, and which practical levers reduce spending. Learn how cache reads, cache creation, input, and output tokens are priced, what actually inflates context, and how to stabilize prefixes, replace full-file feeds with retrieval, split tasks, constrain output, and add observability to control AI coding costs.
1. A Counterintuitive Starting Point: 9 Million Tokens Is Not a 9 Million-Unit Bill
A usage report from a long session showed a cumulative total close to 9.72 million tokens. The first reaction is usually panic, but expanding the breakdown reveals a highly uneven distribution:
| Type | Count | Share |
|---|---|---|
| Input (context sent directly) | 29,710 | 0.03% |
| Cache creation (writing to the prompt cache) | 790,452 | 8.1% |
| Cache read (reusing the prompt cache) | 8,913,330 | 91.7% |
| Output (model-generated) | 14,991 | 0.15% |
More than ninety percent is cache reads. Mainstream large model services generally use tiered pricing: cache reads typically cost about one-tenth of standard input, cache writes cost slightly more than standard input (because they carry additional storage overhead), and output typically costs several times the input rate. As a result, there is an order-of-magnitude gap between the “surface number” and the “actual bill.”
But that is only half the story. The truly worrying half is this: a high cache-read share means the context was replayed nearly three hundred times; nearly eight hundred thousand cache-creation tokens mean the context was “rewritten” multiple times during the session. Together these two point to one problem — out-of-control context management. Cost is only the symptom; the real loss is in efficiency and correctness.
2. The Cost Structure of Four Token Types: Why “Longer Sessions Are Cheaper” Has Preconditions
Understanding cost requires understanding the four identities of a token.
- Input tokens: the context actually sent to the model on each request, at standard pricing, the most expensive tier relative to cached reads.
- Cache creation tokens: when the context exceeds the platform’s minimum cache threshold (commonly on the order of a thousand tokens), the system writes it to a server-side cache. This write is billed at a higher rate.
- Cache read tokens: subsequent requests that hit the cache are billed at roughly one-tenth of the input price.
- Output tokens: model-generated content, with a high unit price but typically a very small share in coding tasks (only 0.15% in this example).
Three engineering conclusions follow.
First, a repeated prefix is an asset, not waste. Stable content such as system prompts, coding standards, and directory structure notes placed at the very front of the context can be reused over the long term at very low marginal cost.
Second, caching gains come from “stability,” not “length.” Caches match on the content prefix, so any single character change in the prefix (a timestamp, a random ID, a dynamically assembled prompt) prevents all subsequent content from hitting the cache and degrades it to standard pricing.
Third, cache writes must be restrained. Frequently triggering writes means repeatedly paying that “25% more expensive” fee. If context is repeatedly compressed and expanded during a session, the number of writes accumulates quickly.
A schematic structure should look like this (pseudocode):
[Stable zone] System instructions + coding standards + project structure notes # long-term cache hits[Semi-stable zone] Current task goal + relevant file list # stage-level caching[Volatile zone] Latest tool result + additional user requests # changes every time, keep at the end
3. What the Real Data Reveals: What Actually Inflates the Context
Reviewing the cache-creation peaks line by line, what inflates the context is usually not the code itself but the following kinds of “noise”:
- Full-file re-ingestion: reading an entire repository or a huge generated file at once, easily tens of thousands of tokens.
- Untrimmed tool output: build logs, test reports, and dependency trees pasted back verbatim, containing many repeated lines.
- Long trial-and-error residue: failed approaches and rejected patches left in history, participating in billing on every round.
- Repeated explanation: the same constraint restated repeatedly in the session, and repeated back by the model.
- Binary and asset files: images, lock files, and archives mistakenly read in as text.
The corresponding remediation actions are equally clear: locate before reading a file, then read a range; aggregate and truncate tool output first; explicitly archive or delete rejected approaches; write constraints into a spec file instead of repeating them verbally.
4. Five Actionable Optimization Levers
Lever 1: Context partitioning and a stable prefix. Putting unchanging content first and volatile content last is the single most effective way to improve cache hit rates.
Lever 2: Retrieval instead of full-context feeding. Locate with keyword or symbol search first, then read fragments on demand, turning “read the whole repository” into “read the necessary range.”
Lever 3: Task splitting and session closure. One session should carry only one verifiable goal; end when it is done, avoiding long-tail conversation that keeps amplifying replay cost.
Lever 4: Output constraints. Ask the model to answer with patches, checklists, or minimal runnable snippets, reducing low-information restatement. Output has a high unit price, so compression gains are direct.
Lever 5: Observability. Record the absolute values and shares of the four token types per session, focusing on two signals: whether the cache-read share stays stable and whether the number of cache creations grows abnormally.
The following schematic logic can serve as a budget guardrail:
def should_continue(session):# A low cache-read share means an unstable prefix; fix the context before continuingif session.cache_read_ratio < 0.5:return "stabilize_prefix"# An oversized single write; split the task firstif session.last_cache_creation > 50_000:return "split_task"return "continue"
5. Upgrading from “Saving Tokens” to “Saving Budget and Increasing Throughput”
The point must be emphasized: the optimization goal is not to minimize the token number, but to make every unit of cost produce more effective changes. Reading fewer useless files, keeping less failed history, and repeating explanations less are all essentially about raising the effective output per unit of cost.
If a team needs scaled governance on top of this, it can build a closed loop with general cloud capabilities: use object storage to archive sessions and artifacts, use logging services and monitoring alerts to track usage trends, use container platforms to run parallel automated tasks, and use message queues to decouple long-running jobs. Baidu AI Cloud offers corresponding product forms in these general categories, which can be combined according to your own budget model.
The final criterion is simple: when the cache-read share stays at a high level, the number of cache creations is under control, and the output share, though low, is directly adopted every time, you are solving more problems with less money.
