Why LLM Bills Explode: A Practical Guide to Tokens, Caching, and Intelligent Routing

    Large language model costs can rise sharply after an application moves from a small demo to production. This guide explains how input and output tokens, long context, cache hit rates, tool calls, retries, and Agent workflows affect spending. It also presents practical strategies for model routing, budget controls, observability, and reducing the cost of each successful result without sacrificing quality.

    1. Why a Demo Is Cheap but Production Costs Can Get Out of Control

    Large language model applications are usually inexpensive during the validation stage. Request volumes are limited, contexts are short, and only a small number of users are involved. Developers often focus on whether the model can answer questions and whether the results are good enough.

    Once the application enters production, however, request volume, context length, output size, and task complexity can all increase at the same time. The cost structure changes accordingly.

    For example, an internal Q&A demo may receive only a few hundred requests per day. Each request might contain approximately 2,000 input tokens and generate 500 output tokens, making the bill almost negligible. After launch, the same system may be integrated with customer support, moderation, search, reporting, and AI assistant workflows. Request volume can grow to hundreds of thousands per day, while each request may include system instructions, conversation history, retrieved knowledge, and tool results. The actual token usage per request may then be several or even dozens of times higher than during the demo stage.

    More complex Agent workflows can create additional costs:

    • A single user request triggers multiple model calls.
    • Each call repeats part of the context.
    • The model plans an action before calling search, database, or business APIs.
    • After a tool returns data, the model summarizes or makes another decision.
    • Failed requests are automatically retried.
    • Simple tasks are incorrectly routed to expensive models.
    • Unnecessarily long outputs increase output-token charges.

    The core production challenge is therefore not simply choosing the cheapest model. It is building a cost-routing system that is observable, controllable, and capable of making routing decisions automatically.

    2. What Makes Up the Cost of an LLM Request?

    The cost of a single request can be abstracted as follows:

    1. Single-request cost =
    2. Input token cost
    3. + Output token cost
    4. + Cost of uncached content
    5. + Cost of cached content
    6. + Long-context or inference surcharges
    7. + Tool and external-service costs
    8. + Additional retry costs

    At the billing level, request volume, concurrency, and task distribution must also be considered:

    1. Total cost =
    2. Σ (Number of requests in each category × Average cost per request in that category)

    2.1 Input Token Costs

    Input tokens include much more than the user’s message. They may also include:

    • System prompts;
    • Role definitions and safety rules;
    • Conversation history;
    • Retrieved knowledge snippets;
    • Tables, code, or structured data;
    • Tool results;
    • Intermediate state from multi-step Agents.

    Many teams measure only the length of the user’s question and overlook the content that actually consumes most of the tokens: fixed instructions, historical context, and retrieved material. If a long system prompt is sent with every request, its cost accumulates continuously.

    2.2 Output Token Costs

    Output tokens are often more expensive than input tokens, so controlling output is usually one of the most direct ways to reduce spending.

    Common problems include:

    • No limit on response length;
    • Requests for unnecessarily detailed explanations;
    • Large numbers of repeated fields in structured results;
    • Intermediate reasoning text in Agent outputs;
    • Regenerating a complete answer after a failure;
    • Asking for a long explanation when the task requires only a classification label.

    For classification, intent detection, and field extraction, ask the model to return a limited and clearly defined structure instead of open-ended text. Returning only a category and confidence score, for example, is usually more economical than generating a lengthy natural-language explanation.

    2.3 Cache Hits and Cache Misses

    Caching means that repeated or highly stable input content does not need to be processed from scratch every time. Previously computed context can be reused, reducing processing and billing for repeated content.

    Content that is generally suitable for caching includes:

    • Stable system instructions;
    • Long role definitions;
    • Fixed business rules;
    • Knowledge descriptions that rarely change;
    • Repeated template-based context.

    Content that is usually unsuitable for caching includes:

    • User questions that change on every request;
    • Real-time inventory, pricing, or status data;
    • Time-sensitive retrieval results;
    • Context containing many randomly changing fields.

    The goal is not to cache everything. The important design objective is to maximize the proportion of stable prefixes and avoid unnecessary changes to those prefixes. For example, do not place the current time, request ID, or random identifier at the beginning of a long prompt. Dynamic fields in the prefix can reduce the overall cache hit rate.

    3. Why Long Context Is a Hidden Cost Multiplier

    Long context creates more than additional input-token charges. It introduces three major problems.

    First, input costs grow linearly. As conversation history, knowledge-base excerpts, and tool results accumulate, a single request can grow from a few thousand tokens to tens of thousands.

    Second, processing efficiency declines. The longer the context, the more information the model must consider. Response latency and the probability of failure may increase as a result.

    Third, routing strategies can become ineffective. Some teams see a long context and immediately choose the most capable and expensive model. However, a long context does not necessarily indicate a difficult task. Many such requests simply require finding an answer in a document and do not need complex reasoning.

    Context management should therefore be treated as part of cost governance:

    • Summarize conversation history instead of appending it indefinitely.
    • Remove intermediate messages after their tasks are complete.
    • Deduplicate and compress retrieved results.
    • Filter documents first, then send only the most relevant content to the model.
    • Set context limits for different task types.
    • Separate stable rules from dynamic data.
    • Split overlong inputs into multiple segments.

    A two-stage workflow can be useful. In the first stage, a low-cost model or rule-based system filters relevant content. In the second stage, a stronger model receives only the reduced context. This lowers input-token usage while also reducing interference from irrelevant information.

    4. Model Routing: Do Not Send Every Request to the Same Model

    Mature LLM systems generally use a tiered model strategy rather than relying on one model for every task.

    4.1 Low-Complexity Tasks

    Lower-cost, high-throughput models are often suitable for:

    • Text classification;
    • Sentiment analysis;
    • Simple rewriting;
    • Keyword extraction;
    • Fixed-format summaries;
    • Routine Q&A;
    • Intent detection;
    • Structured field extraction.

    These tasks typically have clear objectives, short outputs, and controllable consequences when errors occur. Using an expensive model usually does not produce a proportional business benefit.

    4.2 Medium-Complexity Tasks

    Medium-capability models can handle tasks such as:

    • Summarizing multiple pieces of material;
    • Drafting customer-support replies;
    • Answering questions about business documents;
    • Explaining ordinary code;
    • Organizing information with multiple conditions;
    • Producing general analysis reports.

    For these requests, choose a model that balances quality and price, and use an evaluation set to confirm that the results meet business requirements.

    4.3 High-Complexity Tasks

    Use high-capability models only when they are genuinely necessary, for example:

    • Complex code generation and refactoring;
    • Multi-step business planning;
    • Critical decision support;
    • Difficult reasoning;
    • Coordination across multiple tools;
    • Scenarios with very high accuracy requirements;
    • Requests that fail repeatedly with lower-cost models.

    The basic routing principle is simple: first use the least expensive model that can reasonably solve the task. Upgrade only when the task difficulty, business risk, or failure conditions exceed a defined threshold.

    5. How to Design an Executable Cost-Routing System

    A practical router should include at least the following steps.

    Step 1: Classify the Request

    Before calling an LLM, classify the task according to its characteristics:

    1. Task type = Classification / Summarization / Q&A / Code / Agent / High-risk operation
    2. Input length = Short / Medium / Long
    3. Output requirement = Short text / Structured output / Long text
    4. Business risk = Low / Medium / High
    5. Tool required = Yes / No

    Classification can be performed with rules or by using a low-cost model.

    Step 2: Define Candidate Models

    Create a candidate model set for each task category and record:

    • Input price;
    • Output price;
    • Cache price;
    • Context limit;
    • Average latency;
    • Historical success rate;
    • Structured-output reliability;
    • Business evaluation score.

    Model selection should not be based on price alone. Quality and failure rates must also be included in the calculation.

    Step 3: Calculate the Combined Cost

    A simplified scoring function might look like this:

    1. Overall score =
    2. Quality benefit
    3. - Cost weight × Estimated cost
    4. - Latency weight × Estimated latency
    5. - Risk weight × Estimated failure loss

    Quality benefit can be derived from offline evaluations, manual reviews, or online user feedback. Estimated cost can be calculated from input tokens, output limits, cache hit rates, and historical averages.

    Step 4: Define Upgrade and Downgrade Rules

    Possible rules include:

    • For short classification requests, prioritize a low-cost model.
    • For complex code tasks, send the request directly to the high-capability candidate set.
    • Upgrade when the low-cost model has insufficient confidence.
    • If output validation fails, retry without necessarily switching models.
    • Upgrade only after two consecutive failures to avoid unlimited retries.
    • During peak periods, delay or downgrade low-priority tasks.

    Step 5: Add Budget Protection

    Hard limits are essential:

    • Daily token limits per user;
    • Hourly spending limits per application;
    • Maximum input length per request;
    • Maximum output length per request;
    • Maximum Agent loop count;
    • Maximum number of tool calls;
    • Maximum number of automatic retries;
    • A downgrade strategy for budget overruns.

    Without budget protection, even a system with low average costs can generate a large bill because of abnormal loops, prompt injection, or sudden traffic spikes.

    6. Why Agent Workflows Are Especially Prone to Overspending

    A traditional Q&A flow is often one question followed by one answer. An Agent may execute a sequence such as:

    1. User request
    2. → Analyze the task
    3. → Query a knowledge source
    4. → Call a business API
    5. → Evaluate the result
    6. → Query again
    7. → Generate the final answer

    If every step calls a model and every round includes the complete history and tool results, one user request can generate multiple rounds of input and output charges.

    When managing Agent costs, focus on the following:

    1. Loop count: Set a maximum number of steps for each task.
    2. Tool scope: Expose only the tools required to complete the task.
    3. Context transfer: Do not pass every intermediate result to the next round in its original form.
    4. Result reuse: Cache identical query results within the workflow.
    5. Failure handling: Distinguish temporary failures, parameter errors, and model decision errors instead of retrying everything in the same way.
    6. Task decomposition: Steps that can be completed by rules or conventional code should not be delegated to a model.

    For fixed workflows, deterministic programmatic orchestration should be preferred. Introduce an Agent only when dynamic decision-making is actually required. A model is not the best executor for every step.

    7. Cost Monitoring Should Go Beyond the Total Bill

    A monthly total is not enough to identify the source of a problem. At minimum, track the following metrics.

    Usage Metrics

    • Total request count;
    • Input tokens;
    • Output tokens;
    • Cache hit rate;
    • Average context length;
    • Average output length;
    • Usage by user and application.

    Quality Metrics

    • Task success rate;
    • Human adoption rate;
    • User follow-up rate;
    • Output validation pass rate;
    • Model upgrade rate;
    • Retry rate;
    • Tool-call success rate.

    Cost Metrics

    • Average cost per request;
    • Cost per successful result;
    • Cost by business unit;
    • Cost by model;
    • Cost during peak periods;
    • Cost of failed requests;
    • Cost per Agent task.

    Pay particular attention to the cost per successful result. If a low-priced model requires multiple retries to complete a task, its real cost may not be low. Conversely, a more expensive model that succeeds on the first attempt may offer better overall economics.

    8. A Practical Cost-Reduction Checklist

    Implement cost controls in the following order:

    1. Measure actual token usage instead of estimating from request counts.
    2. Analyze input and output costs separately.
    3. Identify the longest system prompts, conversation histories, and retrieved results.
    4. Design caching for stable prefixes.
    5. Summarize and trim historical messages.
    6. Set reasonable output limits.
    7. Move simple tasks to lower-cost models.
    8. Preserve an upgrade mechanism for high-risk tasks.
    9. Limit Agent loops and tool-call counts.
    10. Set retry-count and budget limits.
    11. Attribute costs by application, team, and user.
    12. Use offline evaluations to verify that cost reductions do not harm quality.
    13. Set up real-time alerts and circuit breakers for abnormal traffic.
    14. Regularly review model pricing, quality, and routing performance.

    9. Conclusion: Cost Governance Is System Governance

    LLM cost optimization is not about finding the single cheapest model. It requires the coordinated design of requests, context, caching, models, tools, and retry behavior.

    An effective cost-governance system should have four characteristics:

    • Observable: You can identify which requests generated each portion of the cost.
    • Routable: Tasks with different levels of difficulty use different models.
    • Controllable: Context, output, loops, and retries are subject to limits.
    • Evaluable: Price, quality, latency, and success rate are measured together.

    When a system can assess task difficulty, reuse stable context whenever possible, upgrade models only when necessary, and continuously monitor the cost per successful result, LLM spending is no longer an unpredictable black box. It becomes an engineering metric that can be measured, analyzed, and continuously optimized.