LLM Unit Task Cost: Token Usage, Cache Hits, Latency Tiers, and Routing
Large language model selection is driven by more than price per million tokens. This article explains how input, output, and hidden token use form request cost, how cached input changes the bill, and how to compare models by cost per successful task. It also covers latency tiers, model routing, budgets, monitoring, and common cost mistakes.
1. Background: Why Cost and Efficiency Drive Model Selection
Large language model capability keeps improving, and call volume is growing with it. For developers and enterprises, the value of a model call depends not only on answer quality, but also on the tokens consumed, response time, and the final bill. A token is the basic unit used to meter text. Both input and output count toward the charge.
Model selection used to focus on price per million tokens. That comparison misses a key fact: different models may use very different token counts to finish the same task. A higher unit price with tighter reasoning can cost less per task than a lower unit price with verbose output. Cost evaluation should therefore move from unit price to cost per task.
This article takes a general technical view of what makes up token consumption, how cached input affects cost, which measurable metrics to use when comparing models, how latency tiers trade speed against spend, and how to set budgets and monitoring in production.
2. What Token Consumption Is Made Of
The first step in understanding cost is to break down where tokens in a single request come from. They usually fall into three groups.
2.1 Input tokens
Input tokens include system instructions, conversation history, retrieved document snippets, tool or function definitions, and the user’s current question. Many applications resend the full history on every turn, so input tokens grow linearly with the number of turns. In a support scenario that carries ten full turns of history each time, the tenth request may send about ten times the input of the first, and most of that content may be irrelevant to the current question.
2.2 Output tokens
Output tokens include the answer body, structured fields, code snippets, and intermediate reasoning content that may be billed. Output is usually priced higher than input, so controlling output length often has a clear effect on cost. Explicit output formats, limits on length or field count, and a sensible maximum output length are common controls.
2.3 Hidden consumption
Hidden consumption is easy to miss and can still be a large share of spend. Common sources include:
- Automatic retries after failed requests
- Extra turns caused by unclear instructions
- Tool-call round trips, where each result is sent back as new input
- Repeated runs during testing and debugging
These hidden costs should be included in the same accounting view. Otherwise the budget will be systematically too low.
2.4 A basic cost formula
The cost of one request can be expressed as:
Request cost = uncached input tokens × input price + cached input tokens × cached input price + output tokens × output price
The cached input price is usually lower than the normal input price. Use the provider’s pricing rules, read from the bill or the official documentation, rather than estimates from experience.
3. Cached Input: Making Stable Content Cheaper
Cached input works on a simple idea: when the prefix of a request closely matches an earlier request, the service can reuse intermediate results it has already processed and charge less for that part of the input. This is especially useful for repetitive applications, such as a fixed system prompt, a long product manual, or a shared coding-standards document.
Raising the cache hit rate depends on keeping the request prefix stable. Useful principles are:
- Put unchanging content at the front, such as system instructions, role settings, and fixed reference material.
- Put content that changes each time, such as the user question and live retrieval results, at the end.
- Do not insert timestamps, random IDs, or other fields that change on every call into the fixed prefix.
- Use a consistent template for the same class of task.
The following request layout shows how to separate stable and dynamic parts:
def build_messages(system_prompt: str, reference_docs: str, user_query: str) -> list[dict]:# Keep stable content first so the prefix can be reusedstable_prefix = f"{system_prompt}\n\n[Reference]\n{reference_docs}"return [{"role": "system", "content": stable_prefix},# Dynamic content goes last{"role": "user", "content": user_query},]
Whether a cache hit actually applies depends on the provider’s rules, such as a minimum prefix length and cache lifetime. Teams should verify the real hit rate from usage data rather than infer it from code structure alone.
4. Comparing Models by Cost per Task
Unit price is a quote. Cost per task is the business metric. Two models can be compared with the following steps.
4.1 Build an evaluation set
Sample a representative set of tasks from real workloads, covering common requests, edge cases, and hard scenarios. Size depends on business complexity, but each task type should have enough samples. The set needs clear pass criteria, such as whether the answer is correct, whether code passes tests, or whether a document matches a required template.
4.2 Record the key metrics
For each task, record:
| Metric | Meaning |
|---|---|
| Input tokens | Total input for this request |
| Cached tokens | Input portion that hit the cache |
| Output tokens | Amount of content the model generated |
| End-to-end latency | Time from sending the request to receiving the full response |
| Success | Whether the result meets the evaluation criteria |
4.3 Compute cost per successful task
Cost per successful task is a more robust comparison:
Cost per successful task = total spend ÷ number of successful tasks
Failed tasks still count in total spend. A model that is cheaper per call but succeeds much less often can have a higher cost per success.
The code below shows the calculation. The price parameters are only for demonstrating the logic; they are not a real quote from any service:
from dataclasses import dataclass@dataclassclass Price:input_per_m: float # price per million input tokenscached_per_m: float # price per million cached input tokensoutput_per_m: float # price per million output tokensdef request_cost(price: Price, input_tokens: int, cached_tokens: int, output_tokens: int) -> float:uncached = input_tokens - cached_tokenstotal = (uncached * price.input_per_m+ cached_tokens * price.cached_per_m+ output_tokens * price.output_per_m)return total / 1_000_000def cost_per_success(records: list[dict], price: Price) -> float:total = sum(request_cost(price, r["input"], r["cached"], r["output"])for r in records)successes = sum(1 for r in records if r["success"])return total / successes if successes else float("inf")
With this method, a team can compare models or configurations on the same evaluation set instead of relying on a single figure from marketing material.
5. Latency Tiers: Trading Speed Against Cost
Many services offer low-latency or high-priority calling modes, usually at a higher price or under a tighter quota. That reflects a general rule: more capacity and a shorter queue mean a faster response and a higher cost.
In system design, requests can be tiered by how sensitive the business is to delay:
- Interactive use: real-time chat, code completion, and in-product suggestions care about time to first token and fit a low-latency mode.
- Background work: batch document processing, offline labeling, and overnight report generation are not delay-sensitive and fit a standard mode or batch processing.
- Critical path: steps tied to payment or approval should watch both reliability and a latency ceiling, with timeouts and fallback behavior.
The point of tiering is to give each request resources that match its value. Putting every request on the fastest path raises cost quickly, while most background work gains nothing from it.
6. Tiered Routing: Matching the Model to the Task
Not every task needs the strongest model. Tiered routing assigns requests to models of different capability and price based on difficulty, risk, and latency needs.
A typical implementation includes these steps:
- Classify the request quickly by difficulty, for example simple Q&A, format conversion, complex reasoning, or multi-step planning.
- Set a default model for each class and check its quality floor on the evaluation set.
- When a lighter model is not confident enough or fails validation, escalate automatically to a stronger model.
- Track the escalation rate. If escalation is too frequent, revisit the classification rules or the prompts.
The gain depends on classification accuracy. If classification is often wrong, hard tasks go to an underpowered model, quality drops, and retries multiply, which can raise cost. Classification rules should therefore be part of the evaluation.
7. Budgets and Monitoring
Cost control should not wait for a later invoice review. Production systems need live monitoring and budget limits.
7.1 Key metrics
- Token usage by feature, user group, or tenant
- Average input and output tokens per request
- Trend in cache hit rate
- Retry rate and failure rate
- Day-over-day and week-over-week cost per successful task
7.2 Budgets and alerts
Set a daily and monthly budget for each business module, and alert at 50%, 80%, and 100% of the threshold. Alerts should go to both the technical owner and the business owner so they can decide together whether the strategy needs to change.
7.3 Output limits and rate limits
Where abnormal loops or prompt injection are a risk, set a maximum output length per request and a request-rate cap per user or per task. These limits prevent sudden spend spikes and reduce the chance that the service is abused.
8. Access and Data Governance
In an enterprise setting, model access is usually granted by an administrator by role or workspace. Follow least privilege: open high-cost modes or high-privilege capabilities only to teams that need them, and review the access list regularly.
Data governance matters as well. Prompts should not contain secrets, personal data, or unsanitized business data. Call logs should be kept for audit and troubleshooting, but the logs themselves should be stored and accessed according to data-classification rules.
9. Common Mistakes
In practice, the following habits often lead to runaway cost or weak results:
- Deciding on unit price alone: ignoring differences in token use and success rate, which skews selection
- Ignoring retry and correction cost: leaving failed requests out of the totals
- Using one model for every task: paying more than necessary for simple work
- Sending unbounded history: input grows with each turn, and most of it is irrelevant to the current question
- Setting no output constraint: the model produces long text, which raises both cost and reading time
Avoiding these mistakes is straightforward. Cost has to be part of design, and assumptions have to be checked continuously against real data.
10. Summary
Cost and efficiency for large language model applications are a combined problem of task design, model choice, and engineering governance. Teams should treat cost per task as the core metric, raise cache hit rates with stable request structure, match resources through tiered routing and latency classes, and keep spend under control with budgets and monitoring. Ongoing evaluation and feedback from real data support long-term technical decisions better than a one-time price comparison.
