LLM API cost optimization starts with measurement, not guesswork. This guide shows how to calculate request costs, set token budgets, route tasks to suitable models, use caching and batching responsibly, and review quality before reducing spend.
Overview
The cost of an LLM application is shaped by more than the model selected. Prompt length, retrieved context, output limits, retries, traffic patterns, caching, tool calls, and the number of workflow steps can all affect the final bill. A low-cost model can become expensive when it receives oversized prompts or is called repeatedly by an inefficient agent loop.
A practical cost-control program has four parts:
- Measure: record input tokens, output tokens, requests, latency, errors, retries, and feature-level usage.
- Budget: define acceptable cost per request, user, workflow, and billing period.
- Choose and route: match model capability to task difficulty instead of sending every request to the same model.
- Validate: compare savings with quality, safety, latency, and completion-rate changes.
Cost reduction should not mean blindly shortening every prompt or always choosing the cheapest available option. The better objective is to meet a defined quality threshold at the lowest predictable cost. For production teams, cost data belongs beside reliability and evaluation data. The LLM observability guide covers the tracing needed to make these measurements useful.
How to estimate
Start with a simple request-level formula. Keep input and output pricing separate because they are often charged differently:
Estimated request cost = (input tokens ÷ pricing unit × input rate) + (output tokens ÷ pricing unit × output rate)
Use the pricing unit specified by the provider or billing system. If rates are expressed per million tokens, the pricing unit is 1,000,000. Add other components when they apply, such as embedding calls, reranking, image or audio processing, tool executions, storage, or retrieval infrastructure.
Then scale the estimate:
Feature cost = requests × average request cost
For a monthly forecast, separate traffic into meaningful segments rather than using one application-wide average. For example:
- Interactive user requests
- Scheduled summarization or classification jobs
- RAG requests with retrieved context
- Agent workflows with multiple model calls
- Retries and fallback requests
For each segment, capture at least the following fields: request count, average input tokens, average output tokens, selected model, cache-hit rate, retry rate, and quality score. Percentiles are valuable too. An average may hide a small number of very large requests that cause a disproportionate share of cost.
Use a spreadsheet or an internal developer tool to calculate both expected and observed cost. The expected figure helps with planning; the observed figure reveals prompt growth, unusual users, failed calls, and workflow branches that the original estimate missed.
Inputs and assumptions
Token budgets
Set budgets at several levels. A request budget limits the normal prompt and completion size. A feature budget limits the cost of one product capability. A user or tenant budget prevents unexpected usage from overwhelming a shared system. A monthly budget supports financial planning and alerts.
Budgets should reflect the task. A short classification call may need a small output ceiling, while a document-generation feature may require more room. Set an output maximum even when the application usually produces shorter answers. Also define behavior when a request exceeds its budget: summarize the input, ask the user to narrow the scope, use a cheaper workflow, or return a controlled limitation message.
Model routing
AI model routing assigns requests to different models according to complexity, risk, latency requirements, or context size. A useful routing policy can look like this:
| Task type | Routing preference | Quality check |
|---|---|---|
| Extraction, tagging, or simple classification | Use a lower-cost model when it meets the schema and accuracy threshold | Validate labels, required fields, and confidence handling |
| Routine summaries and transformations | Use the least capable model that passes representative evaluations | Check completeness, factual consistency, and length |
| Complex reasoning or ambiguous requests | Escalate to a more capable model only when signals justify it | Compare task success, not just fluency |
| High-risk or customer-facing decisions | Apply stricter evaluation and human review rules | Measure errors, refusals, and escalation outcomes |
Routing signals might include document length, user intent, failed validation, low classifier confidence, or a prior model's inability to complete the task. Do not route solely on a vague complexity label. Test the policy on a fixed evaluation set and monitor its decisions in production. For classification workflows, the guidance on taxonomy design, confidence routing, and human review provides a useful evaluation pattern.
Caching and batching
Cache stable work. Good candidates include repeated system instructions, identical document transformations, deterministic lookup results, and embeddings for unchanged content. Define a cache key from the model, relevant prompt version, input content, and important configuration. Invalidate entries when the prompt, source document, or output contract changes.
Semantic caching can improve reuse for similar requests, but it needs a similarity threshold and a quality review. A superficially similar question may require a different answer. For sensitive or personalized data, check retention and access requirements before caching.
Batching can reduce overhead for offline jobs such as tagging a document collection. It is less suitable for interactive requests where users expect an immediate response. Keep batch failures retryable and record each item independently so one malformed input does not obscure the rest.
Worked examples
The following figures are illustrative assumptions, not current provider prices. Replace them with the rates and billing units from the provider you are evaluating.
Example 1: Request and monthly estimate
Assume a feature averages 2,000 input tokens and 500 output tokens per request. For illustration, suppose the input rate is $2 per million tokens and the output rate is $8 per million tokens.
Input cost: 2,000 ÷ 1,000,000 × $2 = $0.004.
Output cost: 500 ÷ 1,000,000 × $8 = $0.004.
Estimated request cost: $0.008. At 50,000 requests, the model portion of the estimate is $400 before retries, caching effects, additional services, or taxes. If a 20% retry rate is included, model calls rise to approximately 60,000, making the corresponding estimate $480. This is why retry rate belongs in a cost model rather than being treated only as a reliability metric.
Example 2: Routing and caching
Suppose 70% of requests are routine transformations and 30% require a more capable model. First, measure quality on both models using the same test set. If the lower-cost model passes the required threshold for routine work, route that segment accordingly while keeping the complex segment on the stronger model.
Next, assume 15% of eligible requests can be served from a validated cache. The model-call reduction is not automatically equal to a 15% total-cost reduction: cache storage, lookup operations, misses, and invalidation work may add cost. Calculate the avoided model calls and subtract the operational cost of the cache. Recheck quality by comparing cached responses with fresh responses on a sample of requests.
Example 3: Cost per successful outcome
A cheaper model is not necessarily more economical if it produces more invalid outputs or requires human correction. Add a success measure to the calculator:
Cost per successful outcome = total workflow cost ÷ number of accepted outcomes
For an agent, include every model call, tool call, retry, and fallback in the workflow cost. This prevents a low per-call rate from hiding an inefficient multi-step design. Review the AI agent architecture patterns guide when tool loops, planning, and approval steps materially affect spend.
When to recalculate
Recalculate the model whenever a provider changes pricing, pricing units, context limits, caching terms, rate limits, or model capabilities. Also update it when your own application changes. A new prompt template, larger retrieval context, additional agent step, higher retry limit, or new output schema can alter both tokens and success rates.
A monthly review is a practical minimum for an active production application. Review sooner after:
- A launch, marketing event, or usage spike
- A change in model, prompt, routing rule, or retrieval configuration
- A sustained increase in token volume, latency, retries, or fallback use
- A quality regression or rise in human-review workload
- A material change in provider pricing or available model options
Use this monthly review template:
- Record request volume and cost by feature, model, tenant, and workflow type.
- Compare actual input and output tokens with the budget.
- Calculate cache-hit, retry, fallback, and validation-failure rates.
- Review quality, latency, safety outcomes, and cost per successful result.
- Test proposed routing or prompt changes against a fixed evaluation set.
- Update rates, assumptions, thresholds, and owners in the cost calculator.
- Set alerts for budget overruns and investigate the largest changes first.
Keep a dated record of assumptions so future comparisons remain meaningful. Pair cost monitoring with the LLM evaluation framework and deployment checks before changing production routing. The goal is a repeatable decision process: measure the current workflow, model alternatives, verify quality, deploy cautiously, and recalculate whenever the inputs move.