LLM API Cost Evaluation and Model Selection: A Practical Guide
Comparing per-token prices is a common first step when choosing an LLM API, but it often leads to wrong decisions. This guide explains why list prices mislead, how to build a cost model based on input tokens, output tokens, cache hit ratio, and retries, and which hidden costs are usually underestimated. It also covers an A/B testing method for measuring quality and cost together, the observability infrastructure needed for ongoing cost governance, common pitfalls, and a practical rollout checklist. The goal is to shift model selection from a one-time guess to a repeatable engineering process based on cost per successful task.
1. Why Price Comparison Is Almost Always Wrong
It is normal to see several lightweight model updates within a single week in today’s LLM service market. When selecting a model, developers most often pull the published “price per million input/output tokens” from each provider into a table and pick the lowest one. This approach does not hold up in engineering, for three reasons.
First, billing dimensions are not standardized. Some services set prices by time period, some price input and output separately, some offer significant discounts for cache hits, and others count capabilities such as tool calls and structured output under different metrics. A price table only shows the “sticker price”; it does not show the request patterns you will actually generate.
Second, actual cost is determined by request structure, not by sticker price. The cost of a real business workload is a function of four things: input token volume, output token volume, cache hit ratio, and the number of failed retries. At the same sticker price, two workloads can differ by several times.
Third, model behavior affects token consumption. On complex tasks, some models improve accuracy by increasing the number of internal attempts, and this consumption often shows up on the output side or in the number of calls. Looking only at the input price will systematically underestimate the actual spending on such models.
The right approach is therefore to upgrade “price comparison” into “cost modeling plus empirical calibration.”
2. Build a Cost Model: Break the Bill into Computable Variables
Before you have empirical data, use a simplified model to estimate the order of magnitude. Let the input tokens per request be Tin, the output tokens be Tout, the cache hit ratio be h, the average number of retries be r, the input price be Pin, the output price be Pout, and the discount factor for the cache-hit portion be d (0<d<1). The expected cost per business request can be written as:
Cost_per_request = r * ( Tin * Pin * (h * d + (1 - h)) + Tout * Pout )
This formula reveals three conclusions that are often overlooked:
- The retry count is a multiplicative factor. When
rrises from 1.0 to 1.3, cost goes up by 30% directly, an impact usually larger than the difference in sticker prices between two providers. - The cache hit ratio is the variable with the greatest leverage. Long prompts, fixed system instructions, and repeated knowledge snippets all push
hup significantly; raising the hit ratio from 0.2 to 0.8 can cut input-side cost to roughly a quarter of the original. - The weight of the output price depends on the
Tout/Tinratio. Summarization and rewriting tasks produce short outputs, so the input side dominates cost; code generation and long-form writing produce long outputs, so the output price becomes the main issue.
It is advisable to classify business workloads at the modeling stage rather than represent all traffic with a single average. At minimum, distinguish high-frequency calls with short input and short output, retrieval-augmented calls with long input and short output, and generation calls with short input and long output.
3. Three Hidden Costs That Are Easily Underestimated
3.1 Amplification from Retries and Multiple Attempts
To improve accuracy on complex tasks, two practices are common in engineering: raising the maximum output length for a single generation and allowing multi-step reasoning, or performing multiple samples at the application layer and selecting the best. Both push up actual consumption. When evaluating, put “accuracy improvement” and “token consumption increase” in the same table and calculate the cost per unit of accuracy, instead of looking at the two metrics separately.
3.2 Coupling Between Caching Strategy and Call Orchestration
Whether the cache discount materializes depends on whether the request prefix is stable. If every request prepends a timestamp, a random identifier, or user information to the system instruction, the prefix changes every time and the cache can never hit. The engineering fix is to put stable content first and volatile content last:
[stable system instructions and domain knowledge] -> cacheable prefix[this request's variables and user input] -> changing part
3.3 Mismatch Between Scheduled Jobs and Off-Peak Pricing
For batch offline tasks (such as bulk content summarization, index building, and case library processing), running them during lower-priced periods is the easiest cost optimization to implement. However, off-peak execution brings queuing and timeout risks, so it must be paired with idempotent design and resumable runs.
4. Replace Subjective Judgment with A/B Testing
Conclusions about model selection can only come from empirical testing. A reusable experiment design is as follows:
- Fix the evaluation set. Sample from historical real requests, cover the three workload types above, and use a sample size large enough to reproduce differences stably.
- Fix application-layer parameters. Keep temperature, maximum output length, structured output constraints, and retry policy consistent, and replace only the model.
- Record on two dimensions. For each call, record quality metrics (task success rate, manual spot-check pass rate) and cost metrics (input/output tokens, cache hits, number of calls) at the same time.
- Run for a sufficient period. Cover at least one full workday and weekend cycle to avoid treating occasional jitter as a stable conclusion.
- Produce a decision metric. Use “cost per successful task” as the final comparison measure:
UnitCost = total spend over the period / number of successfully completed tasks
The illustrative record structure can be very simple; the key is to fix the fields so they are easy to aggregate later:
{"task_type": "summary","model_tag": "candidate_a","input_tokens": 1840,"output_tokens": 210,"cache_hit_ratio": 0.72,"attempts": 1,"success": true,"latency_ms": 2300}
5. Integrate Cost Governance into Daily Engineering
For empirical conclusions to stay valid over time, they must rely on observability infrastructure rather than manual bill watching. The recommended minimal combination is:
- Logging service: collect call logs uniformly with fixed fields, serving as the source of truth for cost aggregation.
- Monitoring and alerting: set threshold alerts on cost per task, cache hit ratio, and retry rate so anomalies surface promptly.
- Object storage: store evaluation sets, historical outputs, and regression baselines to keep experiments reproducible.
- Message queue and container platform: host batch offline tasks to enable peak shaving, off-peak execution, and elastic scaling.
At the application layer, two constraints are also needed. One is budget guardrails: set token quotas by tenant or business line, and when exceeded, downgrade to a smaller model or queue requests. The other is routing policy: send simple requests to lightweight models and escalate complex requests to more capable models, using tiered routing to reduce overall cost.
request enters -> complexity assessment -> lightweight model-> strong model (complex / low confidence)-> log and record cost -> aggregate into cost-per-task dashboard
6. Common Pitfalls and How to Avoid Them
- Looking only at sticker price and ignoring hit ratio: treat the cache hit ratio as a first-class metric and keep optimizing it.
- Budgeting with average token counts: long-tail requests significantly raise actual spending, so do capacity planning by percentile (such as P95).
- Ignoring failed retries: timeouts and rate limits silently inflate the bill, so retries must have a cap and backoff.
- Selecting once and never re-evaluating: models iterate frequently, so rerun the evaluation set on a fixed cycle as a routine regression.
- Evaluating accuracy and cost separately: the final decision should be based on cost per successful task, not on either metric alone.
7. Rollout Checklist
- Define business workload categories and build a separate cost model for each.
- Sample and build a fixed evaluation set, managed with versioning.
- Design an A/B test lasting more than a week, recording quality and cost on two dimensions.
- Connect logging, monitoring, and alerting to form a cost dashboard with threshold reminders.
- Enable off-peak execution and idempotent reruns for batch tasks.
- Establish tiered routing and budget guardrails to control spending in extreme scenarios.
- Re-evaluate on a fixed cycle, turning selection from a one-time decision into continuous operations.
Following this process shifts the selection conclusion from “one provider feels cheaper” to “the cost per successful task is lower under the current workload,” and that conclusion rests on an engineering foundation that is reproducible, monitorable, and continuously optimizable.
