LLM API Cost Optimization in Practice: From Unit Price to Total Cost of Ownership
Comparing price per million tokens is only the first step in evaluating an LLM API. Total cost depends on how many tokens an application actually consumes. This article covers common pricing structures, including separate input and output rates, tiered models, and cache discounts. It then describes five cost optimization strategies: context management, context caching, model routing, output control, and batch processing. It ends with how to track per-call cost metrics.
1. Introduction: Why Unit Price Is Not the Same as Cost
When evaluating LLM services, many teams first compare the price per million tokens. In production, however, the same business running the same model capability can receive monthly bills that differ by several times between teams. The reason is that total cost = unit price × actual tokens consumed, and token consumption depends on context length, call frequency, prompt structure, whether caching is enabled, and other factors.
In recent years, leading model providers have lowered their API prices, and some models now offer two price tiers: “thinking mode” and “non-thinking mode.” This reflects differences in inference cost. Long chain-of-thought reasoning generates many hidden tokens. If those tokens are not priced separately, users with simple tasks would pay unfairly for reasoning they do not need. Understanding these pricing designs is a prerequisite for effective cost optimization.
2. Typical Pricing Structures for LLM APIs
2.1 Separate Pricing for Input and Output
The common industry practice is to price input tokens and output tokens separately, with the output price usually several times the input price. The reasons are:
- Input processing is mainly prefill. It can run highly in parallel and keeps GPU utilization high, so the marginal cost is low.
- Output generation is autoregressive. Tokens are decoded one at a time, so memory bandwidth becomes the bottleneck, and each output token requires more compute.
Cost per call ≈ input tokens × input price + output tokens × output price
2.2 Tiered Pricing and Model Tiers
Beyond price differences, watch for these factors:
- Multiple model tiers in one series: Flagship and lightweight models can differ in price by an order of magnitude. Many simple tasks, such as formatting, classification, and short summarization, can be handled by a lightweight model.
- Hidden cost of reasoning models: The thinking tokens of reasoning models are usually billed as output. A single complex reasoning call can produce several times as many output tokens as the final answer.
- Cache hit discounts: When a repeated prefix, such as a long system prompt or knowledge base context, is cached, the cached portion usually receives a substantial discount.
2.3 A Cost Estimation Example
Suppose an application sends 8,000 tokens of system prompt and conversation history per turn and generates about 500 output tokens. Let the input price be P_in and the output price be P_out.
def estimate_cost(turns, input_tokens, output_tokens, p_in, p_out):"""Estimate monthly cost (CNY)."""return turns * (input_tokens * p_in + output_tokens * p_out) / 1_000_000# 10,000 conversation turns per day, 30 days per monthmonthly = estimate_cost(turns=10000 * 30,input_tokens=8000,output_tokens=500,p_in=4, # CNY per million tokens (example value)p_out=16 # CNY per million tokens (example value))print(f"Estimated monthly cost: about {monthly:.0f} CNY")
Even when the input price is far below the output price, total input tokens often exceed total output tokens by more than tenfold. In this example, input tokens outnumber output tokens 16 to 1. Optimizing the input side is often the main opportunity for cost reduction.
3. Five Cost Optimization Strategies
3.1 Context Management: Remove Ineffective Input
In multi-turn conversations, accumulated message history is the main cause of token growth. Common approaches include:
- Sliding window: Keep only the most recent N full turns and compress earlier turns into a short summary.
- Structured trimming: Rank long document retrieval results by relevance and inject only the top-K passages instead of the full text.
- Prompt slimming: Review system prompts regularly and remove repeated instructions and redundant examples.
3.2 Context Caching: Pay for a Repeated Prefix Once
When a fixed prefix, such as a system prompt, few-shot examples, or knowledge base passages, appears repeatedly, enable caching proactively:
# Pseudocode: declare the stable prefix as a cacheable segmentmessages = [{"role": "system", "content": LONG_STABLE_PREFIX, "cache": True},{"role": "user", "content": dynamic_query}]
Cached tokens are typically billed at a much lower rate than standard input tokens, and caching can also reduce time to first token. This makes caching one of the few optimizations that lower cost and latency at the same time. Pay attention to cache lifetime and minimum cache length requirements, and arrange messages so that stable content comes first.
3.3 Model Routing: Match Tasks to the Right Model
Build a lightweight routing layer that sends each request to a model based on task complexity:
def route(task):if task.complexity == "high": # complex reasoning, code generationreturn "flagship_model"elif task.requires_reasoning: # moderate difficultyreturn "standard_model"else: # classification, extraction, rewritingreturn "lite_model"
In practice, simple tasks often account for more than 70% of requests, so routing alone can produce a significant cost reduction. Routing rules can start as keyword rules and gradually evolve into a small model that classifies intent and difficulty.
3.4 Controlling Output Length and Thinking Budget
- Specify the output format and length in the prompt. For example, “Return a JSON array, with each item no longer than 20 characters.”
- For reasoning models, turn deep thinking on or off as needed. Turning thinking off for simple Q&A can save many hidden tokens.
- Set a reasonable maximum output token limit to prevent runaway generation, which can lead to uncontrolled costs.
3.5 Batch Processing and Asynchronous Execution
For tasks that are not time-sensitive, such as offline data labeling, bulk report generation, and evaluation benchmark runs, batch inference interfaces usually offer discounted prices. Separating real-time and non-real-time pipelines is one of the most direct architectural approaches to reducing cost.
4. Building a Cost Observability System
Optimization should be driven by data, not intuition. Record the following metrics for every call and connect them to monitoring and alerts:
{"request_id": "req-xxx","model": "standard","input_tokens": 8120,"cached_tokens": 7680,"output_tokens": 486,"reasoning_tokens": 0,"latency_ms": 1240,"estimated_cost": 0.041}
Build three core reports from this data: cost distribution by business line, traffic share by model route, and cache hit rate trends. When the unit cost per conversation spikes for a business line, these reports show whether the cause is context growth, cache invalidation, or a model routing problem.
5. Conclusion
The evolution of LLM pricing, including price cuts, tiered models, cache discounts, and the split between thinking and non-thinking modes, makes the structure of inference costs more visible. For developers, comparing unit prices matters less than adopting a token budget mindset. Optimize systematically across five areas: context management, cache use, model routing, output control, and batch processing. Support these efforts with a complete cost observability system. This combination helps teams balance model capability against inference cost, so LLM applications perform well and their costs stay easy to account for.
