Long Contexts and LLM Cost: Why Token Usage Spikes and How to Reduce It
Long conversations and large raw inputs can make LLM usage feel unexpectedly expensive. This article explains how input, cached, and output tokens contribute to cost, why ever-growing contexts and repeated file uploads increase consumption, and how to observe usage, split sessions, summarize history, preprocess data, constrain outputs, and establish team-level token governance.
When using large language models for code generation, troubleshooting, or document analysis, many teams notice the same pattern: a single request does not look complicated, yet the usage allowance is consumed very quickly. This is especially common in AI coding tools. If the same session stays open for a long time and code, logs, and operation records keep being appended, token usage may grow at an accelerating rate.
This problem cannot simply be reduced to “the model is too expensive” or “the plan is not large enough.” More accurately, the factors that drive consumption include context length, cache hit behavior, input and output size, session duration, request frequency, and whether large amounts of raw data are sent directly to the model. Only after understanding these factors can usage be optimized in a targeted way.
1. What Token Consumption Consists Of
A large model request can usually be divided into three parts:
- Input tokens: the instructions, code, logs, documents, and problem descriptions submitted by the user in the current turn.
- Cached tokens: content that has already appeared in the context and is reused in later requests.
- Output tokens: the answer, code, analysis conclusion, or modification suggestions generated by the model.
A simplified formula for the cost of a single request is:
Cost per request≈ input tokens × input price+ cached tokens × cached price+ output tokens × output price
Different services may price these three types of tokens differently, but a common pattern is that cached content usually has a lower unit price than first-time input, while output may be priced higher than cached content.
As a result, under normal usage patterns, many large model services are not very expensive. For example, if a session has an effective context of around 100,000 tokens, each new request adds only a small amount of input, and most historical content can hit the cache, the average cost per request can remain relatively manageable. Problems often arise when users keep expanding the context without organizing and compressing it at the same time.
2. Why Not Starting a New Session Can Rapidly Increase Cost
Many users prefer to keep working in the same session: first ask the model to understand the project structure, then analyze configuration files, then troubleshoot logs, and finally modify multiple modules. This has an obvious benefit: the context remains continuous, and the model does not need to have the background explained repeatedly. But it also creates a clear cost problem.
Suppose the first few rounds of conversation create a context of about 100,000 tokens. Every later request will carry this historical content. Even if this content can be cached, and cached pricing is lower than ordinary input pricing, it does not mean caching is completely free.
When the context expands further to 300,000, 400,000 tokens, or more, the number of cached tokens involved in each request grows accordingly. Assuming input and output sizes remain roughly unchanged, simply increasing cached context from the 100,000-token level to the 400,000-token level can raise the average cost per request several times over. Under the same monthly budget, the number of requests that can be completed will drop noticeably.
This illustrates a key fact:
A long context is not free memory. It only lowers the cost of repeated input; it does not reduce the cost to zero.
If a user interacts frequently every day, the small additional cost per request will be amplified by high-frequency calls, ultimately appearing as rapid consumption of the usage allowance.
3. Three Common High-Consumption Usage Patterns
3.1 One Session Carries the Entire Project Lifecycle
Putting requirements discussions, code reading, error troubleshooting, test results, and deployment records all into one session is convenient in the short term, but over time it causes context bloat.
Large amounts of historical content often no longer have value, for example:
- errors that were already resolved earlier;
- implementation approaches that were abandoned;
- project directory listings that appear repeatedly;
- logs that have been confirmed to be irrelevant;
- code generated by the model but not adopted;
- outdated requirement constraints.
This information still exists in the context, and the model may need to process it on every request. Even if caching reduces the price of repeated content, it still increases the baseline consumption of each request.
3.2 Uploading Large Amounts of Raw Files Directly
Another common pattern is to submit an entire project, complete logs, database export results, or a large document to the model all at once, then ask the model to “analyze the problem.”
The main cost of this approach is not caching but first-time input. A large amount of content may be information the model truly needs, but it may also contain a great deal of irrelevant data, such as:
- build artifacts and dependency directories;
- repeated log lines;
- binary files or compressed text;
- comments, blank lines, and formatting content;
- modules unrelated to the current problem;
- multiple similar configuration files.
If this data is uploaded again for each analysis, even a small number of requests can quickly consume input allowance.
3.3 Asking the Model to Repeatedly Generate Overly Long Outputs
Some tasks only need a short conclusion, but the model is asked to output the full reasoning process, all modified files, or a lengthy explanation. Output tokens also count toward consumption.
This is especially important in coding scenarios. If only one function needs to be changed but the model is asked to output the entire file again, the cost rises significantly, and the risk of manual review errors and unintended modifications also increases.
4. First Confirm the Problem: Establish Minimal Usage Observability
Before changing usage patterns, it is advisable to record call data over a period of time. At minimum, track the following metrics:
- input tokens per request;
- cached tokens per request;
- output tokens per request;
- cache hit rate;
- average cost per request;
- duration of each session;
- total number of requests per task;
- share of usage by task type.
Tasks can be divided into several categories:
Code completion → Usually small input and output, but high frequencyCode refactoring → Longer context, potentially larger outputLog analysis → Large input, limited cache valueDocument Q&A → Depends on material filtering and retrievalContinuous debugging → Long sessions can inflate cached context
If input tokens account for the highest share, the main problem is insufficient data filtering. If cached tokens account for the highest share, the session may be too long. If output tokens account for the highest share, answer length should be limited and task decomposition should be improved.
5. The Most Effective Optimization Methods
5.1 Split Sessions by Task Stage
Do not let a single session continue indefinitely. Split it according to task boundaries:
- requirements understanding;
- project structure analysis;
- single-module design;
- error localization;
- test verification;
- pre-release checks.
At the end of each stage, extract a concise “stage conclusion” and continue in a new session. Keep only necessary information in the conclusion, for example:
Project goal: implement user permission checksCurrent issue: API returns insufficient permissionsConfirmed cause: role field in cache was not updatedFiles involved: permission middleware, user cache moduleNext step: check cache invalidation logic and add tests
This can compress a historical conversation that originally contained hundreds of thousands of tokens into a structured summary of a few hundred to a few thousand tokens.
5.2 Use Structured Summaries Instead of Complete History
A summary should not simply copy the original conversation. It should preserve decision information. It is recommended to include:
- current task goal;
- verified facts;
- key constraints;
- adopted approaches;
- rejected approaches and reasons;
- current blockers;
- next actions;
- relevant file or data locations.
For coding tasks, interface signatures, data structures, and test results can also be added. The value of a structured summary is that it reduces irrelevant context while preserving the key background the model needs to continue working.
5.3 Submit Only Code Relevant to the Problem
Before submitting code, filter it first:
- keep only relevant directories and files;
- remove dependency directories and generated files;
- remove duplicate logs;
- capture only key fragments before and after the error;
- provide only relevant fields for large configuration files;
- use a directory tree instead of complete file contents;
- first ask the model to locate the scope, then provide local code.
For example, troubleshooting an API timeout usually does not require submitting the entire project. A more reasonable sequence is to provide the call chain, exception information, and core configuration first, then add specific files based on the model’s localization results.
5.4 Preprocess Logs
Raw logs are usually highly repetitive. You can first:
- remove timestamp differences;
- merge duplicate errors;
- aggregate by request ID;
- filter out health checks and irrelevant access;
- capture context before and after exceptions;
- count error types and occurrence frequencies.
Compared with uploading hundreds of thousands of raw log lines directly, a summary containing error distribution, representative samples, and key time windows is usually more suitable for model analysis and also saves input cost.
5.5 Limit Output Scope
Clearly define output boundaries in the prompt, for example:
Return only the functions that need to be modifiedDo not repeat unchanged codeGive the conclusion first, then list three verification stepsIf you cannot determine the answer, point out the missing informationKeep the response under 800 words
For code modification tasks, ask the model to return a patch, diff fragment, or change list instead of the complete file. This not only reduces output tokens but also lowers copy errors and review costs.
5.6 Break Complex Tasks into Smaller Tasks
Asking the model in a single request to understand the business, locate the problem, design a solution, modify code, and write tests often produces long context and long output. A more reasonable process is:
- Ask the model to confirm the problem scope.
- Ask the model to list possible causes.
- Provide the necessary code for localization.
- Ask the model for the minimal modification plan.
- Generate tests separately.
- Finally, review the changes.
After task decomposition, the input and output of each step are more controllable, and errors are easier to trace back.
6. When to Proactively Start a New Session
The following criteria can be used:
- the current context has clearly exceeded the scope required by the task;
- the topic has moved from one module to another;
- earlier conclusions have been overturned;
- many repeated explanations appear in the same session;
- the model begins to reference historical content unrelated to the current problem;
- the cost per request continues to rise;
- response quality does not improve as context increases.
A new session does not mean losing context. As long as a high-quality summary is generated first, work can be resumed at a lower cost.
7. Do Not Misunderstand the Role of Caching
The essence of caching is to reduce the marginal cost of repeated content, not to encourage users to expand context indefinitely.
When the scale of cached content is small, reusing historical information is very cost-effective. But when cached content grows from the 100,000-token level to hundreds of thousands of tokens, each request still has to process a large amount of content, and costs continue to accumulate. At the same time, overly long contexts can also cause attention dilution, key information being buried, and reduced answer stability.
Therefore, a reasonable strategy is not “retain as much context as possible,” but rather:
Keep high-value information and eliminate low-value history; prioritize conclusions, constraints, and evidence rather than complete processes.
8. Establish Team-Level Token Governance
For multi-person or enterprise use, personal habits alone are unlikely to control costs over the long term. Standards can be established in the following areas.
Task Templates
Create unified templates for code review, log analysis, incident troubleshooting, document summarization, and other scenarios, specifying input scope and output format.
Session Lifecycle Management
Define the applicable scope of a session, for example, that it serves only one problem, one module, or one version. After the task ends, generate a summary and archive it.
Usage Alerts
Track token usage by user, project, and task type, and issue timely alerts when daily usage or a single request grows abnormally.
Data Preprocessing Workflow
Before data enters the model, use scripts to perform filtering, deduplication, desensitization, chunking, and summarization, avoiding direct submission of unorganized raw data.
Regular Review of High-Cost Tasks
Analyze which tasks contribute most of the consumption, and determine whether model calls can be reduced through retrieval, rule matching, cached results, or local preprocessing.
9. Conclusion
Rapid consumption of large model allowance is usually the result of multiple factors working together. The most typical causes include sessions that last too long, historical context that keeps accumulating, repeated submission of large raw files, logs without preprocessing, and output content without clear boundaries.
Optimization can follow four principles:
- Short sessions are better than infinitely extended long sessions.
- Structured summaries are better than complete historical records.
- Filtered, effective data is better than large raw files.
- Clear minimal output is better than generalized long answers.
If consumption mainly comes from input, focus on data trimming and preprocessing. If consumption mainly comes from cached tokens, split sessions and compress history. If consumption mainly comes from output, limit the return scope and use patch-style modifications. Only by first identifying the source of consumption and then choosing the corresponding optimization method can token usage be truly reduced, rather than simply changing plans or blindly reducing the number of calls.
