LLM API Cost Optimization: Choosing Models with A/B Testing
Token pricing alone doesn't tell you what an LLM API will actually cost. This article explains why sticker prices are misleading, breaks down the four components of real API costs, and walks through a practical A/B testing framework for comparing models. Includes a sample Python script for calculating cost per successful task, plus engineering tactics for reducing spend.
Why Unit Price Doesn’t Equal Real Cost
LLM APIs are typically billed by tokens, with input and output priced separately, and output tokens usually cost more than input. Many teams compare the sticker price per million tokens when choosing a model, only to find their monthly bill is far from what they expected after launch. The reason is that actual spending is determined by three variables together: unit price, the number of tokens consumed per request, and the number of calls needed to complete the same task.
Price is only one of the three. A cheaper model may end up costing more per task if it needs extra reasoning rounds, repeated retries, or longer outputs to reach the same quality. That’s why you should evaluate models using “cost per successful task” as the core metric, rather than comparing list prices alone.
The Four Components of Cost
1. Base Pricing
Base pricing includes the input rate, the output rate, and whether prices vary by time of day. Some services charge differently across time periods, so the same model can cost different amounts depending on when you call it. Log a timestamp for every request and break usage down by time period.
2. Cache Hits
When the prefix of a request matches a previous one, the provider may reuse previously computed intermediate results, and those input tokens are billed at a lower rate. For applications with fixed prompt templates and long system instructions, the cache hit rate has a big impact on total cost. Track cached and uncached tokens separately—don’t lump them together.
3. Extra Tokens from Reasoning
Reasoning models generate intermediate thinking content before producing the final answer, and this content usually counts as output tokens. If the model performs multiple internal attempts, actual consumption can be far higher than the length of the returned text. Always rely on the usage fields returned by the API or the billing data for evaluation—never estimate from the final text alone.
4. Retries and Failed Requests
Timeouts, parse failures caused by invalid output formats, and retries after rate limiting all generate extra charges. Your cost analysis must include the consumption of failed requests, or you’ll underestimate real spending. This is exactly why “cost per successful task” is more meaningful than “cost per request.”
Running an A/B Test for Model Selection
Theoretical estimates can’t replace real data. The following approach works well for a comparison over roughly one week.
1. Define Test Objectives
Start by defining two dimensions: cost metrics and quality metrics. Cost metrics include average spend per task, total daily spend, and cost per successful task. Quality metrics can be human ratings, the pass rate of structured output validation, or business-side acceptance and conversion rates. Looking at cost alone will lead you to a cheap but unusable option.
2. Keep Test Conditions Identical
Both groups should use the same prompts, the same input samples, and the same inference parameters, such as temperature and max output length. Use random traffic splitting and run both groups in parallel over the same time window, to rule out interference beyond time-of-day price differences.
3. Determine Sample Size and Duration
Each group should cover several hundred to a few thousand real requests, and the test period should include both weekdays and weekends. If the window is too short, occasional traffic spikes will skew the results. If your traffic has clear daily or nightly patterns, record the time-of-day distribution separately in your test design.
4. Sample Code for Cost Calculation
The following code shows how to convert usage records into costs. Replace the price parameters with your actual rates; the code itself doesn’t represent any specific service.
from dataclasses import dataclass@dataclassclass UsageRecord:input_tokens: int # Total input tokenscached_input_tokens: int # Number of input tokens served from cacheoutput_tokens: int # Output tokens (including reasoning tokens)success: bool # Whether the request produced a valid resultdef estimate_cost(records, price):"""price: price per million tokens, with three fields: input, cached, output.Returns total cost and cost per successful task."""total = 0.0successes = 0for r in records:uncached = r.input_tokens - r.cached_input_tokenstotal += uncached * price["input"] / 1_000_000total += r.cached_input_tokens * price["cached"] / 1_000_000total += r.output_tokens * price["output"] / 1_000_000if r.success:successes += 1cost_per_success = total / successes if successes else float("inf")return total, cost_per_success
Failed requests still count toward total cost but not toward the success count, so the higher the failure rate, the higher the cost per successful task. This is precisely the point to focus on when comparing options.
5. Decision Rules
If the two options are close in quality, simply compare cost per successful task. If the quality gap is significant, set a minimum quality threshold first, then pick the cheapest option that meets it. Define the quality threshold before the test begins to avoid moving the goalposts afterward.
Engineering Tactics to Cut Costs
- Fix and trim your system prompts: Remove wasted tokens from every request and improve cache hit rates at the same time.
- Route by task tier: Use lightweight models for simple tasks like classification and extraction, and reserve high-capability models for complex reasoning.
- Constrain output length: Use explicit format requirements and max output limits to avoid extra charges from verbose answers.
- Schedule work intelligently: Run non-real-time tasks during off-peak or cheaper billing periods, and batch small requests together.
- Build a cost dashboard: Monitor usage by model, feature module, and date, and set budget alerts so overruns are caught before the bill arrives.
Implementation Recommendations
- Start by estimating the theoretical cost of each candidate option from historical logs, and narrow it down to two or three worth testing.
- Run a one-week A/B test on real traffic, recording both cost and quality data.
- Make the final decision using cost per successful task together with your quality threshold, and keep the ability to switch back to the original model quickly.
- Review pricing and usage changes monthly. Model prices and billing policies can change, so your selection conclusions need periodic revalidation.
