LLM Token Pricing and Inference Cost Optimization: A Practical Guide
This guide explains how token-based pricing works for large language models and how to keep inference costs under control. It breaks billing into three components—input, output, and cache-hit tokens—and explains why cache-hit tokens are a subset of input tokens that must be subtracted first. It then compares committed plans against pay-as-you-go, walks through a code-based budget model with worked numerical examples, and lays out practical optimization tactics: stabilizing cache hits, constraining output, routing requests by complexity, trimming context, and using async batch processing. It closes with an FAQ and a list of common pricing mistakes. The core takeaway: measure the real per-task cost of a typical workload instead of comparing sticker prices.
Bottom line up front: Tokens are usually billed separately for input, output, and cache. Cache hits are a subset of input, so you must subtract them before costing. When comparing models, don’t look at unit price alone—look at the real per-task cost of a typical workload. The recommended cost-reduction priorities are: constrain output, keep prefixes stable to hit the cache, send non-real-time tasks through batch processing, and trim context.
1. Why tokens are the billing unit
Large language models don’t charge per character or per request. They first split text into tokens, then run the forward pass over those tokens. The compute a single inference consumes is roughly proportional to the number of tokens the model has to process: the longer the context and the more the model generates, the more memory, attention compute, and memory-access overhead it needs. Anchoring price to tokens keeps the price aligned with actual resource consumption.
Understanding this also helps you read price changes more rationally. When a newer-generation model raises its price, it may be tied to a larger model, a longer context window, and higher compute demand per inference. To judge whether something is expensive, don’t look at unit price alone—look at the combined metric of “real tokens consumed per task × unit price.”
2. How token billing works: input, output, and cache hits
Mainstream LLM services typically split billing into three dimensions:
- Input tokens (prompt): system prompts, conversation history, retrieval-augmented context, and so on. In long-document scenarios this is often the biggest consumer.
- Output tokens (completion): the answer the model generates. Output is usually priced higher because generation is autoregressive and decodes token by token, which costs more compute.
- Cache-hit tokens: when a request’s prefix overlaps heavily with a previous request, the provider may reuse the cached KV; the cached portion is usually billed at a lower rate.
There’s one easy-to-miss detail in this billing model: cache-hit tokens are a subset of input tokens, not a separate line item. So the cost of a single request must first subtract the cached portion from input, then price each part:
Cost per request ≈ (input tokens − cache-hit tokens) × input price+ cache-hit tokens × cache-hit price+ output tokens × output price
Since output usually costs more per token than input, in generation-heavy scenarios where output makes up a large share, controlling output length and cutting redundant generation is often more effective than compressing input. But for tasks with long input and short output, the priority shifts to optimizing context length.
3. Where committed plans and pay-as-you-go draw the line
When choosing a service, teams often weigh a plan/committed usage against pay-as-you-go. First, distinguish two kinds of “subscription”: consumer subscription plans, and API committed usage or reserved throughput. The latter is better suited to large-scale production.
| Dimension | Committed plan / committed usage | Pay-as-you-go |
|---|---|---|
| Cost predictability | High; monthly spend is relatively controllable | Low; fluctuates with call volume |
| Unit-price economics | Cheaper for high-volume, steady workloads | More flexible for low-volume, experimental workloads |
| Suitable scenarios | Stable, scaled production | Spiky, bursty, validation phases |
| Overage risk | Overage is billed on top or discounts lapse, and unused committed volume is still charged | No quota; everything billed by usage |
The cost structures differ sharply. The key is to convert the plan’s quota into usable token volume, then compare horizontally. Dividing the plan’s total included tokens by the plan price gives you a per-million-token unit cost—if that beats the pay-as-you-go unit price, it’s a more reliable basis for the decision. Some vendors also offer committed-usage discounts or reserved throughput, but here too you need to watch the cost of unused capacity.
4. Costing methodology: build a budget model in code
Without a real bill to reference, you can estimate consumption with a tokenizer and build a cost budget model. The prices below are fictional values for demonstration; always defer to the vendor’s official pricing page.
First, install the dependency:
pip install tiktoken==0.7.0
Runnable example:
import tiktokendef estimate_tokens(text: str, encoding_name: str = "cl100k_base") -> int:"""Estimate the number of tokens in a piece of text."""enc = tiktoken.get_encoding(encoding_name)return len(enc.encode(text))def estimate_cost(input_tokens: int,output_tokens: int,cached_tokens: int = 0,p_in: float = 0.0, # Input price per million tokensp_out: float = 0.0, # Output price per million tokensp_cache: float = 0.0 # Cache-hit price per million tokens) -> float:"""Estimate the cost of a single request under token-based billing."""fresh_input = max(input_tokens - cached_tokens, 0)cost = (fresh_input * p_in+ cached_tokens * p_cache+ output_tokens * p_out) / 1_000_000return costprint(estimate_cost(2000, 500, 0, 0.5, 1.5))# Expected output: 0.00175print(estimate_cost(2000, 500, 1500, 0.5, 1.5, 0.05))# Expected output: 0.001075
A note on tokenizer boundaries: cl100k_base is a common tokenizer for OpenAI-family models. Vendors like Claude and Gemini use their own tokenization schemes, so the token count for the same text can differ noticeably. Treat estimates as order-of-magnitude references only; any cross-model price comparison must use the target vendor’s official tokenizer and the latest official prices.
Here’s a minimal worked example with numbers. Suppose a single request has 2,000 input tokens and 500 output tokens, with an input price of 0.5 per million tokens and an output price of 1.5 per million tokens. The per-request cost is:
2000 × 0.5 / 1,000,000 + 500 × 1.5 / 1,000,000= 0.001 + 0.00075= 0.00175
If 1,500 of those tokens hit the cache at a cache-hit price of 0.05 per million tokens, the cost becomes:
(2000 − 1500) × 0.5 / 1,000,000+ 1500 × 0.05 / 1,000,000+ 500 × 1.5 / 1,000,000= 0.00025 + 0.000075 + 0.00075= 0.001075
Compared with the 0.00175 without a cache hit, that’s about a 39% reduction. This shows cache hits can deliver meaningful savings—but only if the request prefix is stable and meets the cache conditions.
If you run 10,000 requests per day, the monthly cost without cache hits is about:
0.00175 × 10000 × 30 = 525
With stable cache hits, the monthly cost is about:
0.001075 × 10000 × 30 = 322.5
So decisions should be based on an end-to-end cost range built from typical tasks, with the official bill as the final authority. If a pricier model is more capable and actually consumes fewer tokens per task, its real cost advantage may not show up on the price sheet at all.
5. Inference cost optimization strategies
5.1 Cache hits: keep fixed prefixes stable to reuse input at lower cost
Putting invariant content—system prompts, fixed instructions, long-document preambles—at the very front of the request helps with prefix reuse. But caching isn’t unconditionally profitable: most vendors require a minimum cacheable length, writing to the cache may incur extra fees, and the cache has a TTL or invalidation mechanism—once the prefix changes, the whole thing may be invalidated. Hit mechanisms also differ across vendors; some cache automatically, others require you to explicitly mark cache breakpoints in the request. Defer to the official documentation for the exact billing rules and behavior.
5.2 Constrain output: use prompts and structured output, not just max_tokens
Because output usually costs more, you should constrain generation length. Note that max_tokens is only a hard cutoff—setting it smaller won’t make the model “naturally say less,” and truncation can leave answers incomplete. A more robust approach is to constrain length through the prompt, for example asking for “brief/detailed,” a word or point count, or a JSON schema. If the platform supports structured output or constrained decoding, prefer that. max_tokens is better treated as a safety net.
5.3 Tiered routing: send simple requests to a light model, escalate complex tasks to a flagship
Not every request needs the strongest model. Judging complexity by prompt length or keywords alone is too crude; more robust signals combine task type, expected output length, and whether multi-step reasoning is needed:
def route_model(prompt: str, task_type: str,expected_output_len: int, needs_multi_step: bool) -> str:# Route on multiple signals; this function is illustrative only.# In production, plug in a classifier or calibrate thresholds# against an evaluation set.if (task_type in ("chat", "rewrite", "extract")and expected_output_len < 300and not needs_multi_step):return "light_model" # Handle simple requests with a light modelreturn "flagship_model" # Escalate complex reasoning to a flagship model
5.4 Trim context: inject only the most relevant snippets
In retrieval-augmented scenarios, avoid “stuffing the context full.” Injecting only the most relevant snippets—combining vector retrieval with Top-K pruning and dropping irrelevant information—usually reduces input token consumption. But the payoff depends on retrieval quality, document redundancy, and prompt-template design, so don’t preset your savings expectation too high.
5.5 Non-real-time tasks: use async batch processing
Latency-insensitive tasks like offline summarization, bulk labeling, and data cleaning can evaluate an async batch endpoint. Some vendors’ batch endpoints offer roughly a 50% discount, but usually with clear conditions, quotas, and turnaround limits—defer to the official pricing page. Batch results are typically returned non-real-time, making them better suited to offline data pipelines or async task queues.
6. FAQ
What is a token?
A token is the basic unit a large model uses to process text. The model first splits text into tokens, then performs computation and billing on them.
Roughly how many tokens is one character?
For Chinese, roughly 1 character ≈ 1–2 tokens; for English, roughly 1 word ≈ 1.3 tokens. It depends on the tokenizer and varies across vendors, so there’s no fixed conversion.
Why is output more expensive than input?
Output requires autoregressive, token-by-token decoding, which costs more compute and memory bandwidth, so output is usually priced higher than input.
How much does 10,000 tokens cost?
General formula: cost = input tokens × input price / 1,000,000 + output tokens × output price / 1,000,000. At an input price of 0.5 per million tokens, 10,000 input tokens is about 0.005; at an output price of 1.5 per million tokens, 10,000 output tokens is about 0.015.
How much can a cache hit save?
Savings = (input price − cache-hit price) × cache-hit tokens / 1,000,000. For example, with an input price of 0.5 and a cache-hit price of 0.05, a 1,500-token cache hit saves 0.000675; in the example request, total cost drops from 0.00175 to 0.001075, about 39% lower.
What are common cost mistakes?
- Looking only at unit price and ignoring actual per-task consumption; 2. Assuming compressing input is always most effective while overlooking the output share; 3. Ignoring both the savings and the invalidation risk of cache hits; 4. Using a single tokenizer to estimate cross-vendor costs.
7. Summary
Faced with model price fluctuations and generational differences, the rational approach isn’t to compare sticker prices, but to build a token-centric costing model: split costs into input, output, and cache; remember that cache-hit tokens are a subset of input and must be subtracted first; measure the average consumption of typical tasks; then compare the per-million-token unit cost of committed plans/committed usage against pay-as-you-go. When a team holds the “real per-task cost” as its measuring stick, it can balance model selection, budget control, and user experience—and assess product value and competitive strategy more steadily.
