Token Optimization for AI Coding: Solve More Problems with Fewer Tokens

    A practical guide to managing token consumption in AI coding tools. It explains why raw token totals don't map linearly to cost, breaks down the four token types—input, cache write, cache read, and output—and their pricing differences, and shows why long, cache-friendly sessions can cost less than repeatedly restarting. The article then covers how to diagnose context bloat and presents a six-step methodology for cutting waste while keeping output quality high.

    A Hypothetical 9-Million-Token Session

    Imagine a purely illustrative scenario: a developer uses an AI coding assistant to work on a project that has been iterated on all day. When they close the terminal in the evening, they see 9,721,744 tokens in the usage statistics. It’s worth stressing that this number comes from an example scenario and a hypothetical log—it is not a universal fact about every session. It reflects cumulative consumption over a single day, not the cost of a single request. Actual costs should always be read from the specific tool’s usage statistics and the official billing definitions.

    Seeing such a large number, the first instinct may be to worry about cost. But a more professional approach is not to fixate on the total and feel anxious; instead, open the session logs and usage statistics and break them down by task type, number of tool calls, cache hit behavior, and context re-reads. A careful analysis usually reveals that token distribution is highly uneven: a few sources dominate the total, while the output tokens—which carry the highest unit price—may account for a surprisingly small share.

    This case reveals a counterintuitive fact: the total token count and the actual billed cost are not simply linearly related. If more than 90% of tokens are cache reads (which should be confirmed against usage statistics), the real cost may be far lower than the headline number suggests. Conversely, if a large share of tokens are ordinary input or cache writes, even a modest total can still result in a high bill. So understanding cost control in AI coding starts with understanding the four identities of a token.

    The Four Identities of a Token: Different Unit Prices Shape the Cost Structure

    In the billing model of interacting with a large language model, tokens are not all the same thing. Based on their role in the request lifecycle, they typically fall into four categories. Pricing is not identical across vendors, models, and request types, so specific prices and multipliers should be verified against the official billing documentation.

    1. Input tokens: The context actually sent to the model in each request, including system prompts, user instructions, project descriptions, code snippets, and so on. This is the base content the model needs for reasoning, usually billed at the standard input rate, and it is often the main target for cost optimization.

    2. Cache write tokens: When the context reaches a certain length, some tools or platforms write the stable content into a server-side cache. Creating the cache itself usually incurs an additional charge, which may be slightly higher than ordinary input. Whether caching is enabled, the cache threshold, and how the write fee is calculated all depend on the specific vendor and model.

    3. Cache read tokens: If a later request hits the cache, the stable context can be reused without being re-billed as ordinary input. Some models or vendors price cache reads at roughly one-tenth of the standard input rate, some lower, some different. This pricing gives longer sessions a cost-amortization advantage and is a key reason why “a longer session is not necessarily more expensive.”

    4. Output tokens: The content the model actually generates. Pricing for output tokens varies by model; some models or vendors charge roughly 3–5 times the input price, while others use different multipliers, so refer to the official billing and request type for specifics. In AI coding scenarios, output tokens are often not as dominant as repeatedly reading project context, but they still meaningfully affect both total cost and response speed.

    From this, an important judgment follows: in the cost structure, a higher share of cache reads usually means more effective context reuse, which often points to a healthier cost structure. If most tokens in a session come from cache reads and those reads genuinely serve the same task, a long session may actually be cheaper than restarting repeatedly.

    The Economics of Caching: Why Long Sessions Can Be Cheaper

    Many people intuitively assume that a longer session means more tokens and therefore a higher bill. This may hold in scenarios without a caching mechanism, but it is not necessarily true in an AI coding tool with context-caching capability.

    On the first request, the system must fully input the stable context—project description, code structure, relevant files, and so on. Because this is the initial load, the first request is more expensive. Once this stable content is written into the cache, every subsequent conversation turn and tool call that hits the cache can reuse it at the cache-read price instead of being re-billed as standard input each time.

    As the session progresses, then, the same long context is reused repeatedly, and the marginal cost per turn drops. This is why long sessions can be structurally more economical: stable information such as project descriptions, directory structure, coding conventions, and existing design constraints can be cached and reused within a session.

    Conversely, the worst usage pattern is repeatedly restarting the session while re-reading the entire codebase each time. This continually triggers ordinary input and cache writes while making it hard to enjoy the cache-read discount. In other words, the problem is not that “the session is long,” but whether “the context is stable, reusable, and precisely fed.”

    What Real Data Reveals: What Inflates the Context

    When context starts to balloon, the common causes usually fall into a few categories:

    • Mindless full-codebase re-reads: Pushing unrelated files and whole directories into the context, so stable but bloated content keeps accumulating.
    • Unbounded tool output: A single command returning thousands of lines of logs or an oversized file, dumped straight into the context.
    • History pile-up from repeated trial and error: After many failed rounds, all the errors and repeated code snippets stack up layer by layer, forcing the model to keep processing stale information.
    • No reuse of project documentation: Having to re-explain background, conventions, dependencies, and acceptance criteria each time, causing redundant input.
    • No task-level splitting: Handling too many goals in one session, so the context keeps growing and the cache hit rate drops.

    To optimize cost, you must first classify and measure, then target precisely. A simple usage-analysis script can attribute log entries by type and task. Note that log field names may differ across tools; the input, cache_creation, cache_read, and output fields below are only illustrative, so map them to the actual tool log before use to avoid a script that fails to run when copied directly.

    1. # Illustrative: aggregate token usage by type to find the real cost driver.
    2. # Note: field names may differ across tools and must be mapped to the actual log.
    3. def analyze_usage(logs):
    4. summary = {
    5. "input": 0,
    6. "cache_write": 0,
    7. "cache_read": 0,
    8. "output": 0
    9. }
    10. for entry in logs:
    11. usage = entry.get("usage", {})
    12. # Adjust field names to match the actual tool log
    13. summary["input"] += usage.get("input", 0)
    14. summary["cache_write"] += usage.get("cache_creation", 0)
    15. summary["cache_read"] += usage.get("cache_read", 0)
    16. summary["output"] += usage.get("output", 0)
    17. total = sum(summary.values()) or 1
    18. for key, value in summary.items():
    19. print(f"{key:12s}: {value:>12,d} ({value / total:.2%})")
    20. return summary

    Beyond the four token types, you can add task-attribution fields to the log, such as:

    • task_id: the current task identifier;
    • task_type: the task type, such as understanding, retrieval, editing, testing, or refactoring;
    • tool_name: the tool name;
    • cache_hit_rate: the cache hit rate;
    • input_tokens: input tokens;
    • cache_read_tokens: cache read tokens;
    • output_tokens: output tokens.

    With these fields, a developer can answer more specific questions: Is retrieval consuming the most tokens, or is the full-codebase re-read? Is the cache missing, or is the tool output too large? Only after attribution is complete does optimization have a clear target: reduce unnecessary input and cache writes, and increase the share of effective cache reads.

    A Practical Token Optimization Methodology

    1. Feed Only Necessary Context and Define Acceptance Criteria

    Don’t make the tool guess your intent. Provide just enough context—the relevant files, key constraints, and the scope of impact—and write out the acceptance conditions explicitly. The clearer the acceptance criteria, the fewer rework rounds and trial-and-error iterations the model needs, which lowers both output tokens and repeated input.

    You can use an acceptance template like this directly:

    1. Goal:
    2. Fix login endpoint handling under a specific error code.
    3. Scope:
    4. Only src/auth/login.py and tests/test_login.py may be changed.
    5. Acceptance criteria:
    6. 1. pytest tests/test_login.py passes.
    7. 2. Existing function signatures remain unchanged.
    8. 3. No new third-party dependencies.
    9. 4. No more than 2 files changed.
    10. 5. No changes to the database schema.
    11. Out of scope:
    12. Do not rewrite the entire auth module; do not touch unrelated logging code.

    The value of this kind of template is that it turns vague requirements into checkable conditions. The model no longer has to repeatedly guess “how far is far enough to count as done,” and the developer avoids unproductive back-and-forth.

    2. Search First, Then Make Small Incremental Edits

    A common problem in AI coding is letting the model edit code too early. A safer order is to search, locate, and understand the relevant logic first, then make small, incremental edits.

    In the search phase, you can ask the tool to return only necessary information, such as file paths, matching lines, and a few lines of context. A simple search command example:

    1. rg -n --glob '*.py' "login|authenticate|token" src/ tests/

    If you need finer control, you can also use ranged reads:

    1. sed -n '120,180p' src/auth/login.py

    Locating the problem first and then having the model make small edits has several benefits:

    • It lowers the risk of context bloat;
    • It makes it easier to review the scope of changes manually;
    • It makes rollbacks easier when something goes wrong;
    • It avoids rewriting an entire module in one shot;
    • It makes it easier to judge whether a change works by combining it with test results.

    Small edits are not about being conservative; they make every step verifiable. For complex tasks especially, you need to break “modification” into multiple observable steps.

    3. Constrain the Size of Tool Output

    Much context bloat doesn’t come from the model but from tool return values. Logs, search results, and file contents without limits can easily flood the session with large amounts of low-value information.

    Common ways to constrain this include:

    • Taking only key log fragments instead of returning the full log;
    • Limiting search results to file paths, line numbers, and necessary context;
    • Avoiding whole-directory dump-style reads;
    • Reading only the relevant function or region of long files;
    • Having the tool return a summary first and expand into details on demand.

    For example, instead of having the tool read an entire log file, ask for:

    1. Return only the first 20 lines containing ERROR, Exception, or timeout,
    2. along with line numbers and the file path.

    Controlling the size of each tool call’s return value is one of the most effective ways to curb context bloat. The cleaner the context, the more stable the cache hits, and the more easily the model can focus on the current task.

    4. Reuse Project Documentation and the Cache

    Stable information such as project structure, directory layout, coding conventions, dependency installation commands, and test commands should be consolidated into reusable documentation files rather than re-explained on the fly each time. Once this content is cached and repeatedly hit, subsequent turns can benefit from the lower unit cost of reuse.

    A useful project documentation file might include:

    1. Project structure:
    2. - src/ business code
    3. - tests/ test code
    4. - docs/ design documents
    5. Tech stack:
    6. Python 3.11, FastAPI, pytest, ruff
    7. Coding conventions:
    8. - Functions must include type annotations
    9. - Public functions need docstrings
    10. - Run ruff check and pytest before committing
    11. Common commands:
    12. pytest -q
    13. ruff check .

    The goal here is not to make the documentation longer, but to raise the reuse rate of stable information. Once stable context enters the cache, all subsequent turns are more likely to enjoy the cost advantage of cache reads.

    5. Split Requirements by Priority and Verify Each One

    Don’t pile all requirements into a single session. A safer approach is to break the task into independently verifiable units by priority, completing and verifying one before moving to the next.

    For example, a “optimize the login module” requirement can be split into:

    1. Locate the login endpoint entry;
    2. Read the relevant tests;
    3. Fix the error-code handling;
    4. Add test cases;
    5. Run the tests and summarize the results.

    Each item has a clear success criterion, so the model doesn’t have to juggle too much background in a single session. This both reduces context bloat and lowers the token consumption from blind trial and error.

    6. Build a “Measure–Attribute–Optimize” Loop

    Finally, turn optimization into a continuous habit: periodically review the usage statistics, analyze which task consumes the most tokens, and whether the cause is too much input, a cache miss, or overly long output. Attribute every high-consumption behavior to a specific type, then adjust how you feed the context accordingly.

    You can fix a checklist like this:

    • Did this task re-read the same files repeatedly?
    • Could the stable context have been written into the cache?
    • Was the tool output too large?
    • Did unclear acceptance criteria cause rework?
    • Could it have been split into smaller tasks?
    • Has the cache-read share gone up?

    Optimization without measurement is just guesswork. Truly effective token management should be built on continuous observation and attribution of the cost structure.

    Common Mistakes and Things to Watch Out For

    In practice, several kinds of mistakes tend to waste tokens:

    1. Full-codebase re-reads: Repeatedly pushing the entire project into the context without a clear problem scope.
    2. Unbounded output: Having the tool return full logs, full files, or large search results directly.
    3. Repeatedly restarting sessions: Reloading the project description each time, unable to benefit from cache reuse.
    4. No acceptance criteria: The model can’t judge the completion boundary, leading to repeated edits and trial and error.
    5. Piled-up requirements: Handling multiple goals in one session, so the context grows more and more complex.
    6. Only looking at the total, not the structure: Focusing only on the total token count while ignoring the ratio of input, cache reads, and output.
    7. Ignoring official billing differences: Prices differ across models, vendors, and request types, so a fixed multiplier cannot be applied universally.

    These may look like engineering details, but over time they significantly affect cost, response speed, and the overall experience.

    Summary

    In AI coding scenarios, what measures efficiency is never the absolute number of tokens but their structure and purpose. A seemingly large token total, if most of it comes from low-cost cache reads that genuinely serve the same task, may not be costly at all. Conversely, if a large share of tokens comes from ordinary input, cache writes, and unbounded tool output, even a modest number may signal wasted resources.

    Mastering this approach starts with five core practices: feed context precisely with clear acceptance criteria, search before making small incremental edits, constrain tool output, reuse project documentation and the cache, and split requirements by priority for one-by-one verification. Combined with a “measure–attribute–optimize” loop, developers can solve enough problems with fewer effective tokens. This is not only token cost control but also a more mature way of working as an engineer.