LLM cost optimization is less about choosing the cheapest model and more about understanding what each feature spends, why it spends it, and whether that spend produces a successful result. This guide provides a repeatable method for measuring token use, setting input and output budgets, shortening prompts, applying safe caching, routing work between models, controlling retries, and monitoring cost per successful task without sacrificing answer quality.
Overview
Production LLM costs usually come from several interacting factors: request volume, input tokens, output tokens, model rates, retries, failed tasks, tool calls, retrieval context, and background jobs. A small change in any one of these can materially change the monthly bill as traffic grows. The first step in LLM cost optimization is therefore not a model switch. It is creating a cost view that connects spend to a product feature and a user outcome.
Track costs by workflow rather than only by provider account. Useful workflow labels include support assistant, document summarization, code generation, RAG question answering, extraction, classification, and evaluation. For each workflow, record request count, input tokens, output tokens, model, latency, errors, retries, and whether the task was completed successfully. A request that is cheap but requires several retries may cost more than a single, slightly more expensive request that reliably completes the task.
A practical operating metric is cost per successful task:
cost per successful task = total workflow cost ÷ successfully completed tasks
Use this alongside cost per request and quality measures. A lower token bill is not an improvement if it causes more escalations, incorrect answers, abandoned sessions, or manual review. For model-selection decisions, compare quality, latency, and cost together. The LLM model selection guide provides a useful framework for making that comparison.
How to estimate
Begin with a simple monthly estimate for each workflow. Keep pricing inputs in a separate configuration file or spreadsheet so they can be updated without changing the calculation.
monthly input cost = requests × average input tokens ÷ 1,000,000 × input price per million tokens
monthly output cost = requests × average output tokens ÷ 1,000,000 × output price per million tokens
estimated monthly cost = input cost + output cost + tool or retrieval costs + retry cost
If your provider expresses rates using a different unit, convert the rate before applying the formula. Do not mix token counts from one unit with prices expressed in another. Also separate normal requests from retries. If 8% of calls are retried, the approximate request volume used for cost planning is:
effective requests = normal requests × (1 + retry rate)
This is an estimate, not a billing statement. Actual usage may vary because tokenization differs across models, prompts are not always the same length, and some workflows include conditional tool calls or multiple model steps.
For every workflow, capture these spreadsheet-ready fields:
- Date range and environment
- Feature or workflow name
- Requests started
- Successful tasks
- Input tokens
- Output tokens
- Model and model version
- Input and output price assumptions
- Retry count and retry rate
- Cache reads, cache writes, or cache hits where available
- Average and upper-percentile latency
- Quality score, pass rate, or human-review rate
- Total cost and cost per successful task
Use a representative sample before making a major routing decision. A short sample from one quiet day can hide long prompts, peak traffic, or expensive edge cases. Segment the data by request type when the workflow has substantially different paths.
Inputs and assumptions
Set input and output token budgets
Token budgets are operational limits, not just model parameters. Set an input budget for the information sent to the model and an output budget for the response it may generate. Input limits encourage concise system instructions, focused retrieved context, and compact conversation history. Output limits reduce unbounded responses and make cost more predictable.
Choose limits from observed usage rather than an arbitrary maximum. Review a representative set of successful and unsuccessful requests, then set a limit that supports the task while exposing unusually large inputs or responses. When a request exceeds the limit, use a deliberate fallback such as summarizing older conversation turns, retrieving fewer documents, or asking the user to narrow the request. Do not silently truncate information that changes the meaning of the task.
Shorten prompts without removing necessary controls
Prompt optimization should target repeated tokens first. Consolidate duplicated rules, remove examples that do not affect decisions, and avoid sending the same static instructions in multiple message fields. Keep output schemas precise, especially for extraction and tool-calling workflows. A shorter prompt is not automatically better if it increases invalid JSON, missing fields, or downstream retries.
Use prompt tests to verify that a shorter version preserves required behavior. The prompt testing framework guide can help organize regression cases around quality, structure, and failure handling.
Cache only safe, repeatable work
Prompt caching can reduce repeated processing for stable content, but cache design requires care. Identify which parts of a request are stable, such as long system instructions, reference material, or a fixed policy block, and which parts change for every user. Cache keys should include every input that can change the expected answer. Include tenant, permission, locale, model configuration, document version, and other relevant boundaries where applicable.
Do not cache responses merely because they are expensive. Avoid caching personalized or permission-sensitive results unless the key and invalidation strategy prevent cross-user or stale-data errors. Measure cache hit rate, cache-related cost, freshness failures, and quality—not just the number of cache reads.
Route tasks by difficulty and risk
Routing can send routine classification, formatting, extraction, or short summarization tasks to a lower-cost model while reserving a more capable model for ambiguous, long-context, or high-impact work. Define routing rules that can be tested, such as input length, required tool use, confidence signals, language, document complexity, or a failed validation check.
Start with a shadow evaluation: run candidate routes against a fixed test set and compare answer quality, schema validity, latency, and estimated cost. Add a fallback for cases that fail validation or fall below a quality threshold. For tool-calling workflows, validate arguments and permissions before execution; the tool-calling guide covers these controls.
Control retries and background work
Retries should be bounded and classified. Retry transient transport failures differently from invalid output, timeouts, rate limits, or a model response that fails a business rule. Use exponential backoff where appropriate, cap the number of attempts, and avoid retrying a request that cannot succeed without changing its input. Log the reason for each retry so that prompt, schema, provider, and infrastructure problems do not look like the same issue.
Batch offline work such as document indexing, evaluation, or nightly summaries when the provider and application requirements support it. Batching may improve utilization, but it can also increase delay and complicate partial failure handling. Compare the operational trade-off rather than assuming it is always cheaper.
Worked examples
Assume a support workflow handles 100,000 requests in a month. Each request averages 1,500 input tokens and 350 output tokens. The model’s input and output prices are variables in this example, represented as Pi and Po per million tokens.
Input usage is:
100,000 × 1,500 = 150,000,000 input tokens
Output usage is:
100,000 × 350 = 35,000,000 output tokens
The estimated model cost is therefore:
(150 × Pi) + (35 × Po)
If the workflow has a 6% retry rate, model usage may be closer to 106,000 effective requests unless retries are handled outside the measured path or use a different model. Recalculate both token totals using the effective request count, then add any retrieval, tool, or embedding charges separately.
Now consider an optimization that reduces average input tokens from 1,500 to 1,050 by removing duplicated instructions and limiting retrieved context. The new input usage is 105,000,000 tokens. The difference is 45,000,000 input tokens, but the saving is meaningful only if quality remains within the workflow’s acceptance criteria. Compare answer pass rate, escalation rate, citation or retrieval correctness where relevant, and cost per successful task before adopting the change.
For routing, suppose 70% of requests are routine and 30% require a more capable model. Estimate each route separately:
- Routine route: request count × average tokens × lower-cost model rates
- Complex route: request count × average tokens × higher-capability model rates
- Fallback route: failed or uncertain requests × retry or escalation model rates
This three-part estimate is more useful than applying one blended average because it shows whether the fallback path is becoming a hidden cost center.
When to recalculate
Recalculate LLM costs whenever a pricing input, model, prompt, traffic pattern, or workflow outcome changes. At minimum, review the calculation during monthly finance checks and conduct a broader operational review each quarter.
Trigger an earlier review when:
- A provider changes input, output, cached-input, batch, or context-related pricing.
- You migrate models, change model versions, or alter routing rules.
- A prompt, RAG configuration, conversation window, or tool schema changes.
- Traffic grows materially or usage shifts toward longer requests.
- Retry rates, latency, failed validations, or human-review rates increase.
- A budget alert fires or cost per successful task rises without a clear product reason.
- New privacy, permission, freshness, or reliability requirements affect caching.
Use this optimization checklist after each recalculation:
- Export usage by feature, model, environment, and date range.
- Separate successful tasks, failures, retries, and fallbacks.
- Update provider pricing and other cost assumptions from the relevant billing documentation.
- Recompute input cost, output cost, total cost, and cost per successful task.
- Inspect the largest token-consuming prompts and retrieved contexts.
- Test shorter prompts, tighter budgets, caching, batching, or routing on a fixed evaluation set.
- Compare quality, latency, reliability, and cost before releasing a change.
- Record the decision, assumptions, owner, and next review date.
For RAG systems, include retrieval volume and context size in the review; the RAG chatbot guide explains how chunking and retrieval choices affect the material sent to a model. Treat cost optimization as a recurring production practice, not a one-time model purchase decision. With stable measurement fields and explicit quality checks, you can reduce unnecessary token use while preserving the behavior users depend on.