AI Coding: How to Solve More Problems with Fewer Tokens

    A practical guide to controlling token consumption when using AI coding assistants. It explains why token usage spirals out of control, the four categories of tokens (input, cache write, cache read, output), and why context keeps growing. It then walks through measuring your usage distribution, precise context feeding, a search-then-edit workflow, constraining tool output, reusing project instructions and caching, and breaking complex tasks into independently verifiable steps. The goal is to trade fewer invalid inputs for higher effective output rather than mechanically compressing text.

    When AI coding becomes part of everyday development, AI coding assistants can significantly boost coding efficiency — but they also make token costs easy to lose control of. Many developers find that even for a small fix, the session length, number of tool calls, and repeated context inputs keep piling up, and the final bill is far from ideal. To achieve “fewer tokens, more problems solved,” the first step is not to blindly compress content, but to first see the consumption distribution clearly, then decide how to optimize.

    Why Does Token Consumption Often Spiral Out of Control?

    Token overruns are usually not caused by a single factor, but by multiple stages stacking up. In scenarios with long sessions, repeatedly reading large files, frequently searching logs, or many rounds of tool calls, token consumption can quickly accumulate to high volumes. Exactly how high depends on task type, project scale, model choice, and how tools are called — base it on your own session logs and usage statistics, and don’t generalize with fixed numbers.

    Common overrun scenarios include:

    • Feeding the same files into every conversation turn;
    • Retrieval tools returning the full directory tree, large blocks of logs, or duplicated code;
    • Vague requirements that force the model into multiple rounds of probing;
    • Re-entering project background, architecture conventions, and coding standards every time;
    • A wrong direction early on causing large-scale rework later.

    On the surface these look like “the context getting longer,” but in essence they are invalid input and repeated input that haven’t been identified.

    Where Do Tokens Actually Go — Four Categories?

    When interacting with a large language model, tokens fall roughly into four categories. Different cost forms carry different billing weights, and the optimization focus differs too.

    • Input tokens: the context actually sent to the model on each request, including system prompts, conversation history, code snippets, requirement descriptions, and so on. This is the most easily underestimated part in daily interaction.
    • Cache write tokens: when the context reaches a certain length and is reused repeatedly, some inference services cache the stable prefix on the server side. The first write may incur extra storage or compute overhead; its markup and exact price vary by provider and model version, so refer to the official documentation.
    • Cache read tokens: when a later request hits the cache, the read cost is usually lower than re-inputting. But caching only applies to the stable prefix, may expire after a few idle minutes, and usually has a minimum cacheable length. Different providers have different caching strategies.
    • Output tokens: the content the model actually generates, usually priced higher than input. But in coding-assistant scenarios, output is often not the main cost driver — what really spirals out of control is repeated input and tool output echoes.

    So the key to optimizing tokens is not simply reducing character count, but increasing the share of cache reads, reducing repeated input, and lowering invalid output. When cache reuse works, the cost per unit of effective work usually drops; but when the cache expires, the prefix changes frequently, or the service doesn’t support it, this benefit diminishes noticeably.

    Why Does the Context Keep Growing?

    Context bloat usually doesn’t happen suddenly; it accumulates gradually across multiple turns. Start with a “source of bloat — corresponding strategy” reference table:

    Source of bloat Typical behavior Corresponding strategy
    Repeatedly re-reading the same batch of files Putting large chunks of code back into context every turn Precise feeding, stable project instructions
    Unrestrained tool output Full echo of logs, directory trees, retrieval results Constrain tool output, paginate and summarize
    Vague requirements Model probes over multiple rounds and re-confirms repeatedly Provide clear acceptance criteria
    Lack of a reuse mechanism Re-entering project structure and tech stack every time Fix project instructions and reuse the stable prefix
    Too-high rework cost Large-scale rewriting after errors accumulate Small-step edits, decomposition by priority

    From this table you can see that token optimization is not a single-point trick, but revolves around “reducing repetition, reducing invalid echoes, reducing rework.”

    Measure the Consumption Distribution Before Optimizing

    Optimizing without measurement easily turns into adjusting by feel. Before you start optimizing, set up at least the most basic usage metrics.

    You need to collect at least these fields:

    • input tokens;
    • cache write tokens;
    • cache read tokens;
    • output tokens;
    • number of conversation turns;
    • number of tool calls;
    • characters or files returned per single tool call;
    • task type;
    • whether the cache was hit;
    • model or inference service version.

    You can group the metrics three ways: by task type, by session, and by tool call. For example:

    • By task type: which kind of requirement most easily produces high consumption;
    • By session: whether the cache-read share rises in long sessions;
    • By tool call: which retrieval or command tool echoes the most;
    • By context re-read: which files get brought in repeatedly.

    Note that logs, dashboards, project instructions, and the code snippets fed to the model should all be desensitized — they must not contain keys, tokens, user private data, or sensitive production information — and access should be restricted. Measurement is for finding problems, not for spreading risk.

    Precise Feeding: Give Only Necessary Context

    Model performance depends on context quality, not context quantity. Instead of throwing the whole repository at the model, provide the snippets directly relevant to the current task and add explicit acceptance criteria.

    A vague requirement that’s easy to run up high consumption:

    1. Help me look at what's wrong with the login feature in this project.

    This kind of requirement pushes the model into exploration mode: it has to read multiple files, guess at the problem, and verify repeatedly. A more precise requirement can be written as:

    1. In auth/login.py, the password check near line 42 should not compare plaintext.
    2. Please switch to a slow hash; bcrypt, scrypt, or Argon2 are recommended.
    3. Acceptance criteria: wrong password returns 401; correct password logs in normally; plaintext passwords are not stored in the database.

    Here I’m giving a localization clue and a security goal; the line number is only auxiliary. A longer precise description itself also consumes input tokens, so there’s a trade-off. Prioritize keeping the information needed for decisions: target file, relevant functions, constraints, acceptance criteria, known error messages. Don’t stuff in unrelated modules, full logs, and repeated comments.

    Search First, Then Edit in Small Steps

    The correct order is usually “locate first, then modify,” rather than rewriting whole sections from the start. You can first use search capabilities to find the target file, then narrow down further to the function, class, interface, or specific method.

    When locating:

    • Prefer locating by symbol, such as a function name, class name, config item, or interface name;
    • Use line numbers only as an aid, since line numbers drift after code changes or merges;
    • If you can’t find the symbol, fall back to keyword search;
    • Once you’ve found the location, read the minimal necessary context first, then make a local edit.

    The benefit of small-step editing is a small context increment, easier cache hits, and lower rollback cost when errors occur. But note that small-step editing does not equal local correctness. After finishing the change, run the build, unit tests, static checks, or a minimal verification script. Otherwise a local change that looks reasonable may break global consistency.

    Constrain Tool Output

    Tool calls are a hidden token hog. Many developers only watch the conversation text and ignore the full logs, directory trees, and search results returned by tools. Retrieval tools should use precise keywords, restrict paths, and limit the number of returned lines or characters.

    You can constrain output in a parameterized way, for example:

    1. {
    2. "path": "auth/",
    3. "keyword": "login",
    4. "max_matches": 50,
    5. "context_lines": 3,
    6. "max_chars": 2000
    7. }

    Or use a command-line approach, for example outputting only the first 50 matches and the first 200 lines of content:

    1. grep -n -m 50 -C 3 "login" auth/*.py | head -n 200

    The principle: use a summary rather than the full text when you can; paginate rather than pulling everything at once; match precisely rather than scanning loosely. Note that too narrow a range may miss key context. If you can’t find anything, try a small scope first, then gradually widen the path or keywords.

    Reuse Project Instructions and Caching

    Project instructions suit fixing stable information, for example:

    • directory structure;
    • tech stack;
    • coding standards;
    • common test commands;
    • module responsibility boundaries;
    • common entry files.

    If this information has to be re-entered every time, it not only wastes tokens but is easy to overlook. Putting stable content in a project-instructions file lets the model reuse it based on a fixed prefix. But note two points.

    First, project instructions must be desensitized. They must not contain keys, access tokens, database connection strings, user data, real production addresses, or other sensitive information, and file access should be restricted.

    Second, caching only works for a stable prefix. If the project instructions change often, or the cache has expired after an idle period, or the service’s minimum cacheable length isn’t met, the cache-read benefit drops. Caching strategies differ across providers and model versions; base the actual effect on the official documentation and your own measurements.

    How to Break Complex Requirements Down to a Verifiable Level

    For complex tasks, don’t expect one prompt to solve everything. Break them into small tasks that can be independently verified, in priority order, completing and confirming each one.

    Taking “fix the plaintext password comparison in login” as an example, you can break it down into:

    1. Locate the login logic
      Find the login entry, the password-check function, and related tests.
      Verification: you can accurately state the target file, function names, and dependent modules.

    2. Implement slow-hash checking
      Introduce bcrypt, scrypt, or Argon2, and ensure plaintext is not stored in the database.
      Verification: unit tests cover the correct password, wrong password, and empty password.

    3. Replace the login-check flow
      Replace the original plaintext-comparison logic with hash checking, keeping necessary compatibility notes.
      Verification: wrong password returns 401, correct password logs in normally.

    4. Run build and tests
      Run the project’s existing tests, static checks, and build commands.
      Verification: no new failing cases, no sensitive log output.

    Confirming immediately after each small task avoids letting errors accumulate later. Rework is often the most expensive consumption, because you not only regenerate the answer but also reload the context, re-search, and re-verify.

    FAQ

    Why Are Tokens So Expensive?

    Common reasons include: output tokens are relatively pricey, repeated context input, tools returning full text, multiple rounds of trial and error from vague requirements, and rework from a wrong direction. When the cache hit rate is low, repeated-input costs are further amplified.

    When Does the Cache Hit?

    Caching usually only works for a stable prefix. If the prefix stays unchanged, the session hasn’t expired, the context length meets the service’s requirement, and the provider supports caching, a cache read is more likely to hit. The cache may expire after an idle period, so different session strategies, model versions, and providers lead to different results.

    What Are Common Mistakes?

    Common mistakes include: looking only at total token count and not the distribution; stuffing in full files every time; searching without path and line limits; requirements without acceptance criteria; not running tests after making changes; feeding sensitive logs directly to the model.

    What Else Should You Watch When Optimizing Tokens?

    First, desensitize — keys, tokens, and user data must not appear in logs, code snippets, or project instructions. Second, restrict access permissions. Third, watch for line-number drift and global consistency — after small-step changes you still need to build and test. Finally, different providers, model versions, and project scales affect actual results, so the optimization strategy should be continuously adjusted based on your own measurements.

    The essence of token optimization is not mechanically compressing text, but trading fewer invalid inputs for higher effective output. Once measurement, feeding, search, tool constraints, cache reuse, and requirement decomposition become development habits, the waste from repeated input and rework can be clearly compressed. Efficient developers aren’t competing over who consumes more tokens, but who can deliver more reliable, more valuable results within a limited budget.