LLM Cost and Token Optimization: A Practical Checklist for Production AI Apps
Reducing LLM API costs is usually less about finding one cheaper model and more about controlling the tokens, requests, and workflows that create your bill. This guide provides a repeatable way to estimate usage, identify token-heavy patterns, reduce unnecessary context, set safe output limits, and verify that savings do not reduce answer quality.
Overview
LLM costs are commonly driven by four variables: the number of requests, input tokens, output tokens, and the price assigned to each token category by the provider or model. Some systems also distinguish cached input, batch processing, tool calls, image or audio inputs, and other billable units. The exact billing terminology and rates can change, so treat provider documentation and your own usage logs as the source of truth.
A useful starting formula is:
Estimated cost = (input tokens ÷ 1,000,000 × input rate) + (output tokens ÷ 1,000,000 × output rate)
For a production estimate, multiply that per-request cost by the expected number of requests. Keep input and output separate. A prompt may contain a large amount of context while producing a short answer, or it may use a compact prompt but generate a long response. Those patterns create different optimization opportunities.
Where token usage typically grows
| Workflow pattern | Why it becomes expensive | First optimization to test |
|---|---|---|
| Full conversation history on every turn | Old messages are repeatedly sent as input | Summarize or selectively retain history |
| Retrieval-augmented generation | Too many or overly large documents are inserted | Improve retrieval, chunking, and reranking |
| Long structured outputs | The model returns fields or explanations the application does not use | Define a smaller schema and output limit |
| Multi-step agent workflows | Several model calls repeat overlapping context | Remove redundant steps and route simple tasks separately |
| Batch content processing | Each item carries the same instructions and setup | Batch where supported and cache stable instructions |
How to estimate
Build an estimate from observed or deliberately sampled workloads rather than a single ideal request. Select a representative period or test set, then record request volume, input tokens, output tokens, model, latency, errors, and a quality result. If your provider reports tokens directly, use that value. Otherwise, use the provider's tokenizer or a compatible tokenizer tool for an estimate and label it as approximate.
Step 1: Define the unit of work
Choose a unit that makes sense for your product: one customer-support answer, one document summary, one keyword-clustering job, or one completed agent task. Avoid measuring only individual model calls when users experience a multi-call workflow. A single visible task may trigger classification, retrieval, generation, validation, and retry calls.
Step 2: Measure the baseline
For each unit, capture the average and high-percentile input and output tokens. Also count retries, failed calls, tool calls, and fallback calls. Averages help with planning, while high-percentile values reveal the requests most likely to cause budget surprises.
Step 3: Apply the pricing inputs
Enter the current rates for each model and token category into a spreadsheet or small calculator. Keep the rate table separate from the formulas so it can be updated without rewriting the estimate. If your provider offers discounted cached or batch processing, model those as separate scenarios rather than assuming every request qualifies.
Step 4: Compare cost with quality
Token savings are not useful if they cause incorrect answers, missing fields, poor summaries, or extra retries. Create a small evaluation set with expected characteristics. Depending on the workflow, check factual coverage, schema validity, relevance, tone, refusal behavior, latency, and human review outcomes. The goal is not the shortest possible prompt; it is the lowest cost that meets the product requirement.
Inputs and assumptions
Document these inputs before changing a production prompt or model:
- Request volume: expected requests per day, week, or month, including retries.
- Input tokens: system instructions, user content, conversation history, retrieved documents, tool results, and formatting.
- Output tokens: the generated answer, structured fields, reasoning returned to the application, and any validation response.
- Model mix: which tasks use each model and what percentage of traffic is routed to each one.
- Cache and batch assumptions: which content is stable enough to reuse and which requests can be processed asynchronously.
- Quality threshold: the minimum acceptable result and how it will be tested.
- Retry behavior: the conditions that trigger retries and the maximum retry count.
Remember that “tokens” are not the same as words or characters. Token counts vary by language, punctuation, formatting, code, and tokenizer. JSON can be efficient for machine-readable output, but verbose field names, repeated metadata, and deeply nested structures still add input and output tokens. For coding workflows, filenames, diffs, logs, and stack traces can quietly dominate the context.
Useful reduction techniques include removing duplicated instructions, replacing long prose rules with precise constraints, selecting only relevant conversation turns, trimming document metadata, and asking for the exact fields an application consumes. Do not remove safety rules, required context, or evidence merely to make a prompt shorter.
Worked examples
Example 1: Reducing tokens in a summarization workflow
Assume a hypothetical workflow handles 10,000 requests. Its baseline averages 1,200 input tokens and 300 output tokens per request. For illustration only, suppose the configured rates are $0.50 per million input tokens and $1.50 per million output tokens.
Baseline usage is 12 million input tokens and 3 million output tokens:
- Input: 12 × $0.50 = $6.00
- Output: 3 × $1.50 = $4.50
- Total estimate: $10.50
After removing repeated instructions, limiting retrieved text to relevant passages, and requesting a concise schema, assume usage falls to 700 input tokens and 220 output tokens per request. The same 10,000 requests now use 7 million input tokens and 2.2 million output tokens:
- Input: 7 × $0.50 = $3.50
- Output: 2.2 × $1.50 = $3.30
- Total estimate: $6.80
Under these stated assumptions, the estimated reduction is $3.70, or about 35 percent. Before adopting the change, compare summaries for coverage, factual accuracy, format compliance, and user satisfaction.
Example 2: Comparing model routing
Suppose a workflow currently sends every request to a large model, even though many requests are short classification or formatting tasks. Create two test groups: simple tasks and difficult tasks. Measure quality and token usage separately, then route simple tasks to a less expensive suitable model while reserving the larger model for complex cases. The important calculation is not just the cheaper per-call rate. Include fallback calls, retries, latency-related duplicate requests, and any increase in validation work.
Example 3: Estimating conversation-history savings
For a chat application, compare three history policies: full history, a rolling window, and a compact summary plus the most recent turns. Log input tokens at different conversation lengths. If quality remains acceptable with the summary policy, estimate savings by multiplying the average tokens removed per turn by expected turns and monthly conversations. Re-test after prompt changes because a summary that is too compressed can cause users to repeat information or trigger additional calls.
When to recalculate
Revisit your LLM cost estimate whenever a pricing input, workload, or quality assumption changes. At minimum, recalculate after a provider changes rates, billing categories, context limits, caching features, or model availability. Also review the estimate during a model migration, production launch, major prompt revision, traffic spike, or budget planning cycle.
Use this practical checklist:
- Export a recent sample of production requests, including retries and multi-step calls.
- Separate input, output, cached, batch, and tool-related usage where applicable.
- Update the rate table from the relevant provider documentation.
- Recalculate cost per task, cost per successful task, and projected monthly cost.
- Run the same quality test set against the current and proposed workflow.
- Check high-usage users, long documents, long conversations, and failure paths separately.
- Record the change, assumptions, date, model versions, and decision threshold.
For prompt-heavy workflows, pair this review with a prompt testing process such as the Prompt Testing Workbook. Content teams can also examine how context grows in SEO keyword clustering or customer feedback analysis. A small, maintained cost sheet combined with quality checks is more reliable than a one-time token reduction exercise.