LLM cost optimization is less about choosing the cheapest model once and more about building a repeatable way to measure, control, and revisit inference spend. This guide shows how to estimate token costs, set budgets, compare model options, use caching and routing responsibly, and identify when a production LLM app needs a new cost review.
Overview
The cost of an LLM feature usually comes from more than the model’s advertised token rate. A realistic estimate may include input tokens, output tokens, repeated context, cached or uncached requests, retries, fallback calls, batch processing, embedding or retrieval operations, and the engineering overhead of operating the workflow.
Start with a simple objective: reduce cost without weakening the outcome that users actually need. A lower per-token price is not automatically a saving if the model produces longer answers, requires more retries, increases human review, or causes a larger percentage of requests to be escalated to another model.
A useful cost review therefore tracks three categories:
- Usage: requests, input tokens, output tokens, cache hits, retries, and concurrent traffic.
- Quality: task success, structured-output validity, retrieval accuracy, refusal behavior, latency, and human escalation.
- Operations: rate-limit handling, observability, fallback calls, storage, and any separate vector, speech, or moderation services.
For application-level guidance, pair this review with an LLM evaluation framework and repeatable test suite. Cost changes are only useful when you can see whether quality changed with them.
How to estimate
Use a request-level formula before projecting monthly spend:
Request cost = (input tokens ÷ billing unit × input rate) + (output tokens ÷ billing unit × output rate) + additional service costs
For a monthly estimate, multiply the request cost by expected requests, then add the cost of retries, fallbacks, retrieval, embeddings, and other services. If a provider quotes separate rates for cached input or batch processing, calculate those paths separately rather than applying one blended rate.
A practical spreadsheet should contain at least these columns:
- Workflow or endpoint
- Requests per day or month
- Average input tokens
- Average output tokens
- Input and output rates from the provider’s current pricing page
- Estimated cache-hit percentage
- Retry and fallback percentage
- Quality result and latency target
Keep rates as editable inputs. Do not place prices directly inside application code or a permanent article table, because provider pricing, context limits, caching terms, and rate limits can change.
Compare model options by workload
Instead of asking which provider is universally cheapest, compare model classes against the same representative task set. The following table is a decision worksheet, not a ranking:
| Option | Best fit to test | Measure | Cost question |
|---|---|---|---|
| Lower-cost, lower-latency model | Classification, extraction, short transformations | Validity, accuracy, latency | Can it complete the task without repair calls? |
| General-purpose model | Summaries, support answers, code assistance | Task success, output length, consistency | Does quality justify the additional token rate? |
| Higher-capability model | Complex reasoning, difficult code, ambiguous requests | Escalation rate, correctness, review effort | Should it handle every request or only selected cases? |
| Fallback model from another provider | Capacity or availability failures | Failure recovery, quality parity, latency | What is the cost of calling it only during defined failure conditions? |
Use a fixed evaluation set and identical output requirements. A prompt with unnecessary context or unconstrained prose can make a capable model look more expensive than the underlying task requires. See the prompt templates for developers guide for ways to make extraction and structured tasks more predictable.
Inputs and assumptions
Token budgets
Set separate maximums for input and output tokens. An output ceiling is not a target: instruct the model to be concise, define the required fields, and reject or truncate work that exceeds the application’s useful limit. Log actual token usage so the budget reflects real traffic rather than only the configured maximum.
Prompt compression
Remove duplicated instructions, stale examples, verbose formatting, and history that is no longer relevant. Summarize conversation history when the task permits it, but test whether the summary introduces errors. For RAG workflows, retrieve fewer, more relevant passages and apply metadata filters before sending context to the model. A vector database comparison for RAG can help frame the retrieval-side trade-offs.
Caching
Cache deterministic or slowly changing work where the response can safely be reused. Common candidates include repeated document transformations, stable system context, and identical user-independent requests. Define cache keys carefully and include the prompt version, relevant model settings, document version, and permission scope when they affect the result. Measure both the hit rate and the invalidation errors; a high hit rate is not useful if stale content creates support or correction work.
Routing and fallback
Route simple, high-volume tasks to a less expensive model only after evaluation shows acceptable quality. Reserve a more capable model for requests that need it, such as low-confidence outputs, complex tool calls, or failed validation. A fallback should have explicit triggers, a retry limit, and an idempotency strategy. Otherwise, transient failures can silently multiply spend. Review the provider fallback and model routing guide alongside your design.
Retries, batching, and limits
Retries should use bounded exponential backoff and should not repeat non-idempotent actions without protection. Queue work that does not need an immediate response, and evaluate batch processing when the provider supports it and the product can tolerate delayed results. Rate limits are both reliability and cost controls: uncontrolled concurrency can create a burst of failures and repeated requests. For implementation details, see the guide to LLM API rate limits and retries.
Worked examples
Assume a hypothetical support-summary endpoint receives 100,000 requests in a month. Each request uses an average of 1,200 input tokens and 300 output tokens. The application’s current provider rates are represented by variables: Ri for the input-token rate per billing unit and Ro for the output-token rate per billing unit.
Total monthly usage is:
- Input: 100,000 × 1,200 = 120,000,000 tokens
- Output: 100,000 × 300 = 30,000,000 tokens
If the billing unit is one million tokens, the estimated model cost is 120 × Ri + 30 × Ro. This formula remains valid when rates change; update the two rate inputs rather than rewriting the calculation.
Now assume prompt cleanup reduces average input to 900 tokens, while output remains 300 tokens. Input usage falls to 90,000,000 tokens, and the new estimate becomes 90 × Ri + 30 × Ro. The saving depends on the actual input rate, but the source of the improvement is clear and measurable.
Consider a second scenario: routing sends 70% of requests to a lower-cost model and 30% to the existing model. Do not estimate this as a simple model-price average until you include validation failures and escalations. If 5% of the lower-cost model’s requests require a second call, add those calls to the forecast. Compare the routed workflow with the baseline on successful completion, output repair, latency, and total cost per successful task.
Finally, calculate a unit metric that stakeholders can understand, such as cost per accepted summary, cost per resolved support interaction, or cost per indexed document. This prevents a cheaper but less useful output from appearing successful merely because its token bill is smaller.
When to recalculate
Recalculate the estimate whenever pricing inputs, model limits, caching features, or provider rate limits change. Also revisit it after a prompt revision, model migration, retrieval change, traffic increase, or new fallback path. A sudden usage spike deserves an immediate review of request volume, token distribution, retries, and cache-hit rates before changing models.
For routine operations, review the dashboard monthly and compare the latest period with the baseline. Set alerts for unusual request growth, average input or output tokens, retry percentage, fallback percentage, and cost per successful task. Keep a dated record of the model, prompt version, rates, assumptions, and evaluation result used for each decision.
Use this action checklist:
- Export usage by workflow, model, and response status.
- Replace stored pricing and limit assumptions with the provider’s current values.
- Recalculate input, output, retry, fallback, and auxiliary-service costs separately.
- Test compression, caching, batching, and routing changes on a fixed evaluation set.
- Check quality, latency, and accepted-task cost—not token price alone.
- Document the change and schedule the next review after the next meaningful traffic or model change.
Cost optimization is an operating practice, not a one-time model-selection decision. A small, versioned spreadsheet and a reliable evaluation suite can make each review faster while protecting the quality users depend on.