A Practical Guide to Token Cost Optimization for AI Coding Tools
This article explains why AI coding sessions can consume millions of tokens and how to reduce costs without simply shortening prompts. It breaks down the four token types—direct input, cache creation, cache reads, and model output—and shows how to use session logs for attribution across tasks, tool calls, and repeated context. It also covers the main sources of context bloat, ten actionable optimization strategies, and a real case where cache invalidation wiped out cached quota. The goal is to solve more problems with fewer tokens through precise context, small-step edits, output constraints, and cache reuse.
Introduction: The Usage Bill That Makes Developers Uneasy
After using AI coding tools on a long-running, continuously iterated project, many developers run into the same scenario: they close the terminal, open the usage dashboard, and see that a single session has consumed millions—sometimes nearly ten million—tokens. The first reaction is usually panic. But the professional move is not to blindly shorten prompts. It is to do attribution analysis first.
When you break usage down by type, the distribution is extremely uneven: direct input accounts for a very small share, cache creation takes up a portion, cache reads often make up more than ninety percent, and model output is usually under one percent. Since cache reads are typically billed at around one-tenth the price of direct input, a nominal “ten million tokens” does not translate into a bill of the same magnitude. What you really need to watch for is behavior that repeatedly writes expensive context and then reads it back over and over.
This article takes a general technical perspective and lays out a reusable approach to token governance.
1. Understand the Four “Identities” of Tokens
The cost of tokens varies enormously depending on where they come from, and that is the starting point for any optimization:
- Direct input: The context actually sent to the model in the current request. Billed at the standard rate, it is the most expensive.
- Cache creation: When the context length reaches the platform’s minimum threshold, the system writes it into the prompt cache. This step usually costs slightly more than direct input because it includes storage overhead.
- Cache reads: Subsequent requests hit the cache and are billed at only a very low fraction of the rate. This is the underlying reason why long sessions are more cost-effective.
- Model output: Generated content. The unit price is usually several times that of input, but its share in coding tasks is very low.
The core rule fits in one sentence: the higher the share of cache reads, the lower the cost per question; repeatedly creating caches and re-reading the full context is what actually inflates the bill.
2. Use Session Logs for Attribution Instead of Cutting Costs by Feel
The first step in optimization is quantification. It helps to categorize session logs along three dimensions:
- By task: How much each of requirement clarification, code retrieval, edit generation, and test verification consumes.
- By tool call: How much context file reads, repository-wide search, and command execution each contribute.
- By context re-reads: How many times the same piece of content is fed to the model repeatedly.
Illustrative aggregation logic can be expressed like this:
summary = {}for ev in session_log:key = (ev.task_type, ev.tool_name)summary.setdefault(key, {"input": 0, "cache_read": 0, "output": 0})summary[key]["input"] += ev.input_tokenssummary[key]["cache_read"] += ev.cache_read_tokenssummary[key]["output"] += ev.output_tokens
When a particular “cache creation” entry shows an abnormal spike, you can almost certainly conclude that the context was heavily rewritten or fully reloaded, which invalidated the cache and forced it to be rebuilt.
3. Four Real Sources of Context Bloat
- Mindless full-repository re-reads: Having the tool traverse the entire repository from the start, stuffing large numbers of irrelevant files into the context.
- Overly long tool output: Logs, build errors, and dependency lists all returned in full at once.
- Repeated trial and error: Vague requirements lead the model to guess across multiple rounds, with each round carrying the complete history.
- Cache expiry and rebuilds: Long idle periods or frequent context changes invalidate the cache, so previously written quota is effectively lost in an instant.
4. Ten Actionable Optimization Strategies
- Provide only necessary context: Specify exact file paths and function scopes rather than “take a look at this project.”
- Search before editing: Locate code with keyword or symbol search first, then make small changes, avoiding large-scale rewrites.
- Give clear acceptance criteria: Replace “just get it done” with verifiable conditions to reduce back-and-forth rounds.
- Limit tool output: Truncate, filter, and keep only error lines for logs and test results.
- Reuse project documentation files: Capture conventions, directory structure, and coding standards in a fixed document so it hits the cache consistently.
- Keep context stable: Avoid frequently changing prefix content within the same task, which prevents repeated cache rebuilds.
- Break requirements down by priority: Solve one verifiable sub-problem at a time and confirm each one.
- Clean up history promptly: Start a new session when switching tasks so unrelated history is not continuously re-read.
- Make output structured: Ask for results as patches, checklists, or tables to compress output size.
- Build a usage dashboard: Bring token consumption into routine monitoring and alert on abnormal fluctuations.
5. A Postmortem: Cache Invalidation That Vaporized Quota
In one long session, a developer stepped away briefly after several hours of continuous work and then resumed asking questions. Within a short time, a large number of cache creation records appeared while cache reads dropped sharply. The cause was that the context prefix had been substantially modified, so the existing cache no longer matched and had to be written again. The lesson: for long tasks, keep the prefix as stable as possible, put volatile content at the end of the session, and do a lightweight confirmation after an interruption before moving on to heavy work.
6. Conclusion
The essence of token optimization is not “saying less” but “saying the right things and turning repeated things into cheap things.” Quantify first, then attribute, then govern—combined with precise context supply, small-step edits, output constraints, and cache reuse—and you can solve enough problems with fewer tokens. If you need to store session logs, usage dashboards, and archived data, you can close the loop with general cloud capabilities such as object storage, logging services, and monitoring and alerting.
