How to Cut Token Costs in the Age of AI Coding
A practical guide to reducing LLM token bills during AI-assisted development. Based on a real session that consumed 9.7 million tokens, this article breaks down the four token types (input, cache write, cache read, output), explains why cache structure matters more than total volume, and presents ten actionable strategies such as stabilizing the prompt prefix, retrieving before feeding context, setting context budgets, and monitoring cache hit rates. Learn how to treat context as an engineering asset and keep costs under control without sacrificing output quality.
Introduction: A Bill That Made Me Pause
After a full day of iterative refactoring, I closed the terminal and checked the usage breakdown. A single session had consumed roughly 9.7 million tokens—9,721,744 to be exact. My first thought was that the metering had to be wrong. But once I expanded the details by token type, the opposite turned out to be true.
| Token type | Count | Share |
|---|---|---|
| Input (context sent directly) | 29,710 | 0.03% |
| Cache write (initial context caching) | 790,452 | 8.1% |
| Cache read (reusing cached context) | 8,913,330 | 91.7% |
| Output (model-generated content) | 14,991 | 0.15% |
More than 90% was cache reads. Most mainstream LLM services price prompt caching at roughly one-tenth of the standard input rate for reads, so the actual cost of those 9.7 million tokens was far lower than the headline number suggests. The real concern is not the total volume but the structure: the 8.1% spent on cache writes, and the 23% of the budget that evaporated instantly when the cache expired.
1. First, Understand the Four “Identities” of Tokens
Cost optimization starts with accepting that tokens are not a homogeneous commodity. In a general LLM calling model, a single request typically involves four kinds of metering:
- Input tokens: the context actually sent to the model in this request, billed at the standard rate. This is the most expensive part.
- Cache write tokens: when the context exceeds the provider’s minimum cache threshold (commonly around a thousand tokens), the system writes the stable prefix into the cache. This step usually costs slightly more than standard input because it includes storage overhead.
- Cache read tokens: when a later request hits the cache, you pay only a small fraction of the input rate. This is the underlying reason longer sessions can be more cost-effective.
- Output tokens: the content the model generates, typically priced at several times the input rate, but a very small share in coding scenarios (only 0.15% in this case).
This yields the first core rule: the higher the share of cache reads, the lower the cost per unit of useful output; the more frequent and repetitive the cache writes, the worse the bill looks.
2. What the Real Data Shows: What Is Inflating the Context
Looking back at the cache write peaks segment by segment, the sources of bloat are highly concentrated:
- Dumping entire files: pasting all key repository files into the conversation at once, injecting tens of thousands of tokens in a single shot.
- Untrimmed long logs: pasting complete build and test logs, 90% of which are repeated warnings.
- Restating requirements repeatedly: re-pasting background notes with every new requirement, causing the prefix to keep changing.
- Ineffective back-and-forth: after the model’s output deviates, explaining the same constraint over and over in natural language.
3. Ten Actionable Token Governance Strategies
Strategy 1: Keep the Prefix Stable So the Cache Stays “Hot”
Cache hits depend on a byte-for-byte identical prefix. Fix the project conventions, directory structure, and coding standards into an unchanging preamble, and append requirement changes only at the end.
[Fixed prefix: project background + directory conventions + coding standards + output format requirements][This round's increment: the only changed requirement description]
Strategy 2: Retrieve First, Then Feed
Do not paste files from memory. Use keyword search to locate the function and line numbers first, then feed only the relevant snippets. This can usually compress a single injection by an order of magnitude.
Strategy 3: Give the Context a Budget
Set a token ceiling for each turn (for example, 30,000). When the limit is exceeded, force a summary before continuing, avoiding the “boiling frog” style of gradual expansion.
Strategy 4: Subtract from Logs and Errors
Keep only the first exception stack, key error codes, and the last few lines of context, and fold the rest into a statistical summary.
Strategy 5: Replace Raw Text with Structured Summaries
Compress long documents into a three-part form: interface signatures + constraints + boundary conditions. Information density goes up and token usage goes down.
Strategy 6: Control the Cache Rhythm of Concurrency
When multiple sessions run in parallel, caches can crowd each other out. Process tasks that share the same prefix serially for a more stable hit rate.
Strategy 7: Watch Out for Cache Expiration
Caches have a time-to-live limit. Long thinking or frequent task switching turns hot caches cold, requiring a rewrite. In this case, about 23% of the budget was lost this way. The countermeasures are compact scheduling, fewer interruptions, and proactively reheating the cache when necessary.
Strategy 8: Make Output More “Executable”
Ask the model to return patches, commands, and verification steps directly, reducing long explanatory prose. Both output tokens and subsequent rework go down.
Strategy 9: Commit in Small Steps and Close Promptly
End the session and record conclusions as soon as a verifiable small goal is complete, avoiding repeatedly hauling history around in an overly long session.
Strategy 10: Build a Usage Dashboard
Track the share of the four token types and the cache hit rate per session, and set thresholds with monitoring alerts for abnormal growth, turning optimization from a feeling into a metric.
4. Treat Context as an Engineering Asset
Mature teams treat context as an asset that needs versioning, layering, and lifecycle management: a stable layer (standards and architecture), an index layer (retrieval results), an incremental layer (this round’s requirements), and an archive layer (historical conclusions). Combined with object storage for large files, a log service to consolidate runtime information, and a container platform to standardize environment descriptions, you can compress the context to the minimum necessary set without sacrificing quality.
Conclusion
Saving tokens is not about being stingy; it is about being precise: making every call carry the minimum necessary information, keeping the cache hot for as long as possible, and making output as directly usable as possible. Do these three things, and the bill will naturally return to a reasonable range.
