How to Cut Token Usage by 90% in the Age of AI Coding
A practical guide to reducing token consumption in AI coding sessions. It breaks down the four token types in modern LLM API billing, explains why cache reads dominate usage while cache writes signal waste, identifies common context bloat sources, and offers ten actionable strategies plus a reusable context budget table to lower costs without sacrificing output quality.
How to Cut Token Usage by 90% in the Age of AI Coding
1. A Bill That Made Me Sit Up
One weekday evening, I was using an AI coding tool to iterate on a project, from splitting modules all the way to final integration testing. After closing the terminal, I glanced at the usage breakdown, and the number on the screen made me sit straight up: a single session had consumed roughly 9.7 million tokens, with the exact figure being 9,721,744.
My first reaction was to suspect a problem with how usage was being counted. But when I expanded the breakdown by type, the opposite turned out to be true: the number was staggering, yet the real cost was far lower than it appeared. What deserved attention was the context management problem it exposed.
The breakdown looked roughly 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. In other words, the vast majority of this session’s consumption came from repeatedly reusing the same context at a very low unit price. On the surface it “burned nine million,” but the actual bill was just a fraction of that.
2. Four Identities of a Token, Wildly Different Costs
To read the bill, you first need to understand that tokens are not a homogeneous commodity in the billing system. Mainstream large model APIs generally use four measurement categories:
- Direct input tokens: The context actually sent to the model on each request, billed at the standard unit price. This is the most expensive part.
- Cache write tokens: Once the context length reaches the platform’s minimum threshold (commonly on the order of a thousand tokens), the model service stores it as a reusable cache. The write itself costs extra, usually 1.1 to 1.25 times the standard input price, because it includes storage cost.
- Cache read tokens: When subsequent requests hit the cache, this portion is billed at about one-tenth of the standard input price. This is the underlying reason “longer sessions are more cost-effective.”
- Output tokens: Content generated by the model, usually several times the input unit price, but a very small share in coding tasks—only 0.15% in this case.
From this comes the first core rule: the higher the share of cache reads, the cheaper the output per unit; repeated cache writes are the real waste.
3. What Is Inflating the Context: Locating the Bloat Sources
Plot the peaks of each cache write along a timeline, and the bloat sources immediately reveal themselves. There are four common culprits:
- Overly long system prompts and tool descriptions: Tool definitions and behavioral constraints can run to thousands of tokens, and they are sent with every request.
- Feeding entire files: To “let the model understand the project,” people paste in multiple large files at once, 90% of which is irrelevant to the current task.
- Untrimmed command output: Raw logs from builds, tests, and dependency installs can run to tens of thousands of lines, with far more noise than signal.
- Repeated retries and rollbacks: After a wrong turn, starting over breaks the prefix, invalidating the entire cache and forcing a rewrite.
The third is the most insidious. A single unfiltered full test log can trigger a cache rewrite of hundreds of thousands of tokens.
4. Ten Actionable Token Optimization Strategies
Strategy 1: Compress the initial context to the “minimum runnable set”
Provide only the information the task requires: the goal, constraints, acceptance criteria, and relevant file paths. Project background, historical decisions, and descriptions of unrelated modules should all be deferred and added on demand.
Strategy 2: Keep the prefix stable so the cache keeps hitting
Cache matching depends on the prefix being exactly identical. Remove volatile content (timestamps, random IDs, temporary paths, current-time notices) from the top of the prompt and move it to the end or into placeholders. A single inserted timestamp is enough to invalidate an entire cache segment.
Strategy 3: Break tasks into segments and commit in small steps
Split “implement the whole module” into “read the interface—define the structure—write the implementation—add tests.” Each segment has short context and a single goal, which both improves the first-pass success rate and avoids repeated billing in long sessions.
Strategy 4: Use retrieval instead of feeding everything
First let the tool do keyword or semantic retrieval and pull back only the relevant snippets; expand the scope only after confirming a hit. Replace “give everything first, then let the model pick” with “locate first, then fetch.”
Strategy 5: Compress command output
Control output volume at the command level, keeping only errors, summaries, and key metrics. For example:
# Keep only failing cases and the summary linerun-tests --reporter=dot 2>&1 | grep -E "FAIL|passed|failed" | tail -n 20# For builds, extract only the error sectionbuild 2>&1 | grep -A5 -iE "error" | head -n 40
Strategy 6: Build cache lifecycle awareness for long sessions
Caches have a time-to-live (commonly a window on the order of minutes). If you pause an analysis for too long and then come back to continue, the cache may have expired, and the next request will trigger a rewrite. Completing steps that require continuous reasoning within the validity window is the most easily overlooked part of the cost difference—the anomaly reviewed in the original account was exactly a concentrated rewrite after a long interval, which drained about 20% of the quota in a short time.
Strategy 7: Constrain the output side too
Ask the model for conclusions, diffs, and minimal changes rather than pasting back entire files. Use a unified diff format or a structured list instead of lengthy restatement.
Strategy 8: Layer the context, keeping only an index in the main session
Write design documents, interface contracts, and historical conclusions to external files or object storage, and keep only a lightweight index in the main session. Read the corresponding snippet when needed.
Strategy 9: Start a new session periodically and hand off
When the session length enters the tens-of-thousands-of-tokens range, returns begin to diminish. Opening a new session with a structured handoff summary (goal, what’s done, what’s pending, constraints, lessons from failures) is usually cheaper than continuing to extend the old session.
Strategy 10: Establish usage observability
Track input, cache write, cache read, and output separately by type, and focus on two ratios: the cache read share and the number of cache writes. The former should keep rising, and the latter should stay flat. You can use the monitoring, alerting, and log service capabilities of cloud platforms to set threshold alerts.
5. A Reusable Context Budget Table
| Component | Suggested Cap | Notes |
|---|---|---|
| Role and constraints | 500–1500 | Stable and unchanged, placed at the very front |
| Tool and specification descriptions | 1000–3000 | Keep only enabled capabilities |
| Task description | 300–800 | Single goal, verifiable |
| Retrieval snippets | 2000–6000 | Fetched on demand, discarded after use |
| Command output | Under 500 | Filtered summary |
When you exceed the budget, delete retrieval snippets and command output first, and touch the constraints last—constraints are the bottom line for quality and safety.
6. Conclusion
The essence of token optimization is not pinching unit prices but managing context: let the stable parts be reused repeatedly, keep the volatile parts as short as possible, and filter out noise before it leaves the terminal. Do these three things, and the same budget can support several times the workload. The strategies above are tool-agnostic and apply to any AI coding solution that uses an “input + cache + output” billing model; if you use Baidu AI Cloud’s related capabilities, you can likewise combine its log service and monitoring alerts to make usage observability a routine practice.
