Session-Level LLM Coding: How to Spend Tokens Where They Actually Matter

    This article breaks down why a high token count isn't automatically a high bill, explains the four token types (Input, Cache Creation, Cache Read, and Output) and their real cost impact, and shows how prompt caching makes continuous sessions more cost-efficient than restarting. It also covers where tokens actually go, how to classify and measure usage, and ten practical strategies for reducing token consumption—such as providing only necessary context, defining acceptance criteria upfront, controlling tool output size, and keeping a stable context prefix. A checklist and a context organization template are included to help you build better token-spending habits.

    1. When “9.7 Million Tokens” Isn’t a Disaster: Understand the Bill Structure First

    A development project that’s been running all day comes to a close. You shut down the terminal, glance at the usage dashboard, and see a number: 9,721,744 tokens. Your first reaction is probably panic—how much money did that just cost?

    But if you break down that usage by type, the conclusion flips:

    Type Count Share
    Input 29,710 0.03%
    Cache Creation 790,452 8.1%
    Cache Read 8,913,330 91.7%
    Output 14,991 0.15%

    91.7% of it is Cache Read, which costs roughly 1/10 the price of Input. In other words, “9.7 million” is the nominal token count, not the billed token count. What actually determines your bill is the weighted sum of the four token types, each multiplied by a different coefficient.

    This leads to the first counterintuitive rule:

    A high Cache Read share usually means the caching mechanism is working as intended, which lowers your per-question cost. What you should actually worry about isn’t “the total token count is high”—it’s “the share of high-cost tokens is out of control.”

    The Cost Identity of the Four Token Types

    1. Input (direct input): The actual context sent to the model on each request. Billed at the standard rate, it’s the most expensive “list price” token type. It determines how much useful information you feed the model.
    2. Cache Creation (writing to cache): Mainstream LLM APIs commonly offer prompt caching—when the context exceeds the minimum cacheable length (typically around 1,024 tokens), the system writes that text into cache for reuse on subsequent requests. Writing to the cache incurs a cost, usually slightly higher than Input (around 1.25× Input, since it includes storage overhead).
    3. Cache Read (reading from cache): Once a cache hit occurs, that context doesn’t need to be recomputed—you only pay about 1/10 of the Input price. This is the underlying reason why “the longer you chat in the same session, the cheaper it gets.”
    4. Output (model output): The code and explanations generated by the model. Typically 3–5× the Input price. But in AI coding scenarios, Output share is usually very small—the model writes code faster than humans read it, so output is the compressed end of the pipeline.

    Key takeaway: The essence of saving tokens isn’t “typing less”—it’s “keeping high-cost Input and Cache Creation to a minimum while maximizing low-cost Cache Read.” This determines the priority order of all optimization actions.


    2. The First Principle of Cost Optimization: Keep the Cache “Warm”

    Once you understand the billing model, the most cost-effective strategy becomes immediately clear—maintain session continuity and prefix stability in your context.

    2.1 Why Restarting Sessions Is the Most Expensive Option

    Cache hits require an exact prefix match. Mainstream prompt caching matches based on the context prefix: it compares token-by-token from the beginning of the conversation, and only the longest common prefix qualifies for a cache hit.

    This means:

    • Adding even one sentence at the beginning of a session shifts the cache position of everything after it, reducing the hit rate.
    • Frequently starting new sessions and re-pasting the project description means repeatedly paying for Cache Creation.
    • Making significant changes to the system prompt or project description mid-session invalidates all prior cache investment.

    A real-world example worth examining in detail: during a long session, someone adjusted the role-setting paragraph at the beginning. This invalidated the already-established cache prefix, and the system had to re-write cache across subsequent requests. 23% of the quota evaporated instantly due to cache expiration and rewrites—those tokens neither produced new useful context nor were reused. Pure waste.

    2.2 Three Rules for Keeping Cache Hits Consistent

    1. Pin the “unchanging stuff” at the front: Project descriptions, coding conventions, role settings, and long-term agreements should all go at the very top of the context and remain unmodified once set.
    2. Put the “changing stuff” at the end: Temporary requirements, task descriptions for the current request, and additional user constraints go at the tail. This keeps the prefix stable, so new content only affects the suffix.
    3. Close tasks within the same session whenever possible: When switching tasks, evaluate whether to “continue with the current session” or “start a new one.” The former reuses cache; the latter requires rebuilding it—opening a new session only makes sense when the context overlap is very low AND the new task is long-running.

    A simple heuristic: if the new task shares more than half of its context with the previous one, keep the same session; otherwise, start fresh.


    3. Where Tokens Actually Go: Classify by Task, Tool Calls, and Context Re-reads

    To optimize, you must measure first. Usage data without categorization is just “total-count anxiety”—it can’t guide action. Build your own classification table and review it after each long session:

    Dimension Classification Question Typical Waste Signal
    By task Which requirement does this token consumption correspond to? A single small requirement consumed over 30% of the entire session
    By tool call Which type of tool call causes the heaviest context reload? Repeated full-codebase searches or large file reads
    By context re-read How many times has the same content been re-read by the model? The same file appears 3+ times in a session

    3.1 Three Typical Token-Swallowing Behaviors

    Behavior 1: Mindless full-codebase re-reads. Every time a new instruction arrives, the model reads the project root, dependency list, and all source files from scratch. For a mid-sized project, this easily runs into tens of thousands of tokens. One full-codebase scan can cost more Input tokens than dozens of targeted tasks.

    Behavior 2: Repeated trial and error. The model changes something, hits an error, tries again, hits another error. Each round re-inputs the full context + error logs + diff. The pattern is “many rounds, small per-round cost, massive total consumption”—and it usually stems from vague requirements. Without clear acceptance criteria, the model has no choice but to guess.

    Behavior 3: Context pollution. Stuffing irrelevant logs, build artifacts, or dependency package contents into the context. These not only waste tokens but also interfere with the model’s judgment about which code is truly relevant, degrading output quality and triggering even more rounds—a vicious cycle.

    3.2 A Rough Estimation Formula

    Roughly estimate the context cost of a single task:

    1. Per-task cost ≈ (Base context × Rounds) × Input coefficient
    2. + (New content × Rounds) × Cache Creation coefficient
    3. + (Cached prefix × Rounds) × 0.1

    The conclusion is straightforward: rounds are the biggest multiplier. Reducing rounds is far more effective than reducing per-round token count. And the core ways to reduce rounds are “state the requirement clearly in one go” + “verify incrementally to avoid large reworks.”


    4. Ten Actionable Token Optimization Strategies

    Strategy 1: Provide Only Necessary Context

    Don’t “throw the project at the model and let it figure things out.” Instead:

    • Explicitly point out the file paths involved;
    • Paste only the relevant functions/classes/config snippets, not entire files;
    • Describe the call relationships in one sentence (“A calls B, B depends on C’s configuration”) instead of dumping all the code.

    Comparison: A full-codebase scan vs. pasting relevant snippets from 3 specific files—the former can easily be 50× the token count of the latter.

    Strategy 2: Define Acceptance Criteria Upfront

    “Help me optimize this API” is a vague request. The model can only improvise, the output often doesn’t match expectations, and you end up in multiple rounds of rework. Instead:

    “Reduce this API’s P99 latency from 800ms to under 300ms, without changing the return structure, without adding external dependencies. When done, provide the list of modified files and key diffs.”

    The clearer the acceptance criteria, the fewer rework rounds. This is the single highest ROI optimization.

    Strategy 3: Search Before Editing

    Follow the order “locate → understand → modify” rather than “open file → edit directly”:

    1. First, have the model output a plan: “I believe these files need changes, and here’s what I’d change in each.”
    2. You review the plan and eliminate unnecessary changes.
    3. Then let it execute the edits.

    The token cost of the planning phase is far lower than the cost of rolling back and retrying after an erroneous edit.

    Strategy 4: Limit Tool Output Size

    File reads, command executions, and log views can all return excessively long content. Develop the habit of:

    • Specifying line ranges or keyword filters when reading;
    • Truncating command output with pipes (e.g., showing only the first/last N lines);
    • Extracting only the failure sections from build/test logs.

    An underappreciated fact: A single “view full build log” can return thousands of lines, 95% of which are irrelevant to the current problem.

    Strategy 5: Reuse Project Descriptions and Cache

    Maintain a stable project description (architecture, directory responsibilities, coding conventions, common commands). Provide it once at the beginning of a session and never modify it. This content has near-100% cache hit rate, so every subsequent round only reads from cache.

    Strategy 6: Break Down Requirements by Priority

    Break “build a complete user center” into:

    1. Data model definitions;
    2. Registration API;
    3. Login API;
    4. Permission validation;
    5. Frontend pages.

    Each sub-task is independently closed and verified. The benefit of splitting isn’t just manageability—it’s cacheability. Each sub-task has its own independent context and won’t pollute the others.

    Strategy 7: Prevent Irrelevant Context from Mixing In

    Build artifacts, dependency directories, temporary files, and large data files should never enter the context. Use path whitelists at the tool call level when necessary.

    Strategy 8: Control Single-Session Length

    Quality degrades at the tail of long conversations (attention dilution), and every round re-transmits the entire history. When a session exceeds a certain number of rounds, proactively summarize the current state, start a new session, and carry only “conclusions + necessary context.” This is usually more economical than pushing through.

    Strategy 9: Have the Model “Talk” Before “Doing”

    For complex changes, ask the model to first output its plan and impact analysis (this is low-cost Output). You confirm, then let it act (this is high-cost multi-round Input). Trade a small amount of Output for a large reduction in Input.

    Strategy 10: Develop a Personal “Token Budget” Awareness

    Set a mental budget for each session. When consumption exceeds 2× your expectation, stop and ask three questions:

    • Was the requirement unclear, causing repeated trial and error?
    • Did irrelevant content sneak into the context?
    • Is it time to start a new session?

    5. Turn Optimization into a Habit: An Actionable Checklist

    After each long task, spend two minutes reviewing:

    • What was this session’s Cache Read share? Below 70% means the cache isn’t being fully utilized.
    • Was any single file read more than 3 times?
    • Were the acceptance criteria stated clearly in the first round?
    • Is there any build artifact / dependency directory / irrelevant log in the context?
    • Was the task broken down into independently verifiable small steps by priority?
    • Was there any waste from “starting a new session with context that highly overlaps the previous one”?

    A Sample Context Organization Template

    1. # Project Description (provided at session start, never changed)
    2. - Architecture: layered structure, api/service/dao
    3. - Conventions: TypeScript strict, no any
    4. - Common commands: build / test / lint
    5. # Current Task (updated each time, placed at the end)
    6. - Goal: add pagination parameters to /api/user
    7. - Files involved: src/api/user.ts, src/service/user.ts
    8. - Acceptance: add total field to return structure, default page size 20
    9. # Constraints
    10. - Do not modify database schema
    11. - Do not add third-party dependencies

    This structure naturally aligns with the caching mechanism: stable prefix + changing suffix.


    6. Conclusion: Saving Tokens Isn’t Being Cheap—It’s Engineering Competence

    Going back to that 9.7 million token count. The reason it isn’t alarming is that 91.7% was low-cost Cache Read—the system was doing exactly what it should: reusing, caching, and working incrementally.

    What you should actually worry about is a different kind of bill: 90% is high-cost Input and Cache Creation, with near-zero Cache Read. That’s not “heavy usage”—that’s “starting from scratch every single time.”

    So the core of solving enough problems with the fewest tokens isn’t restricting the model’s capability. It’s three things:

    1. State requirements clearly—reduce trial-and-error rounds.
    2. Narrow the context—feed only necessary information.
    3. Keep the cache warm—stable prefix, reuse above all.

    Do these three things, and you’ll find that token consumption drops while delivery speed actually increases. Because every token you saved was originally being spent on “repeated labor” and “error-driven rework.”