Token Billing for LLM APIs: How Pricing Works and How to Cut Costs
Most mainstream large language model (LLM) APIs charge by token rather than by call or by time, because the compute cost of a request is closely tied to how much text is generated. This guide explains the core mechanics behind token billing — what a token is, why input and output are priced separately, and how prompt caching creates a price difference between cache hits and cache misses — and then walks through a layered cost-estimation model and practical engineering techniques for keeping spend predictable: trimming prompts, constraining output length, maximizing cache hit rates, routing requests to the right model tier, and instrumenting usage with monitoring and budget alerts. Prices and free-tier details vary by provider and model, so this article stays at the level of general billing principles and optimization patterns.
1. Why Token Billing Became the Standard Model for LLM APIs
Traditional software is billed per call or per unit of time. LLM inference is different: compute cost scales with the length of the generated content, so a simple per-call charge does not reflect the real resource consumption. That is why most mainstream LLM APIs bill by token — you pay for the tokens sent in and the tokens received back. Understanding this model is the first step toward controlling application cost.
One caveat before going further: unit prices, caching policies, and free quotas differ across cloud providers and model families. This article covers only general billing principles and optimization methods. For actual numbers, always refer to the latest official pricing documentation for the platform you use.
2. The Basics of Token Billing
2.1 What a Token Is
A token is the smallest unit an LLM processes text in, and it is not equivalent to a character or a word. For Chinese text, a single character usually maps to one or a few tokens. For English, one word may be split into several tokens. Punctuation, code symbols, and whitespace consume tokens as well. Practically, this means:
- The longer the prompt, the more input tokens it consumes;
- The longer the response you expect the model to produce, the more output tokens it consumes;
- System prompts, few-shot examples, and conversation history all accumulate as input tokens.
2.2 Input Tokens and Output Tokens Are Priced Separately
Nearly all LLM APIs split the bill into two parts:
- Input tokens (prompt): content you or your system send to the model;
- Output tokens (completion): content the model generates and returns.
The two are usually priced separately, and the output rate is often significantly higher than the input rate. The reason lies in the autoregressive nature of generation: decoding proceeds token by token, and each step must attend to the full context, so the marginal compute cost per token is higher. As a result, controlling output length usually yields more savings than compressing the input.
A general cost model for a single request (numbers are illustrative only; refer to your platform’s pricing for real values):
def estimate_cost(input_tokens, output_tokens,input_price_per_million, output_price_per_million):"""Estimate the cost of a single request using per-million-token prices.Prices are expressed as the currency amount per 1M tokens."""input_cost = input_tokens / 1_000_000 * input_price_per_millionoutput_cost = output_tokens / 1_000_000 * output_price_per_millionreturn input_cost + output_cost
3. Caching: The Price Difference Between Hits and Misses
3.1 What Prompt Caching Does
In scenarios such as retrieval-augmented generation (RAG), multi-turn conversations, and fixed system prompts, a large share of the input is repeated across requests and shares a common prefix. To avoid recomputing that work, many platforms offer prompt caching (prefix caching): frequently reused prefix content is cached, the portion of a later request that hits the cache is billed at a lower rate, and only the portion that misses is billed at the standard input rate.
Input tokens therefore split further into two categories:
- Cache miss: the first request, or a request whose prefix does not match, requiring full recomputation at the highest price;
- Cache hit: a request that matches an already-cached prefix, typically priced well below the miss rate.
3.2 The Key to Cache Hits: Prefix Stability
Whether a request hits the cache depends on whether its prefix is byte-for-byte identical. Common causes of cache misses in practice:
- Injecting dynamic content such as timestamps or random IDs into the system prompt, which changes the prefix on every request;
- An unstable prompt ordering, which makes the prefix structure drift;
- Placing dynamic data ahead of fixed instructions, which breaks prefix consistency.
The design rule that follows is to put stable content first and dynamic content last:
[Stable prefix] System role definition, fixed rules, few-shot examples[Semi-stable] Long knowledge-base documents (reused across requests)[Dynamic tail] The user's current question, timestamps, other volatile data
4. Cost Estimation and Capacity Planning
Real business cost equals the cost of a single request multiplied by request volume, but production also has to account for concurrency, peak-and-trough traffic patterns, and the overhead of failed requests and retries. A layered estimation model works well:
- Per-request cost: input (split by cache hit vs. miss) plus output;
- Daily/monthly cost: multiplied by average daily request volume and a growth factor;
- Buffer factor: reserve 10%–30% headroom for retries and timeout-driven resends.
def estimate_monthly_cost(req_per_day, days,avg_input_tokens, avg_output_tokens,avg_cache_hit_ratio,input_price, cache_hit_price, output_price,retry_overhead=0.2):# Input cost = cached portion at cache price + uncached portion at standard pricecached_input = avg_input_tokens * avg_cache_hit_ratiouncached_input = avg_input_tokens * (1 - avg_cache_hit_ratio)per_req = (uncached_input / 1e6 * input_price+ cached_input / 1e6 * cache_hit_price+ avg_output_tokens / 1e6 * output_price)daily = req_per_day * per_reqreturn daily * days * (1 + retry_overhead)
5. Engineering Practices for Cost Optimization
5.1 Trim the Input Prompt
Removing redundant phrasing, cutting down the number of few-shot examples, and avoiding stacked, duplicated context is the most direct cost lever. In RAG systems, improving retrieval relevance lets you substitute a few well-targeted chunks for large blocks of concatenated text.
5.2 Constrain Output Length
Use parameters such as max_tokens to cap generation length, and explicitly request concise answers in the system prompt. This suppresses unnecessary growth in output tokens, which are usually the more expensive ones.
5.3 Maximize Cache Hit Rate
Placing fixed content first, keeping the prefix byte-level stable, and maintaining a stable cache for long knowledge documents lets large volumes of repeated input qualify for the cache discount.
5.4 Model Tiering and Routing
Route requests by complexity: send simple tasks (intent classification, format conversion, summarization) to lightweight models, and reserve high-capability models for complex reasoning. Tiered routing can substantially reduce overall cost while preserving quality.
5.5 Monitoring, Budgets, and Alerts
Use general cloud capabilities such as log services and monitoring and alerting to build observable metrics for token consumption, per-request cost, and cache hit ratio, and configure budget-threshold alerts so that anomalous traffic (for example, infinite loops or scraping bots) cannot push costs out of control. You can also archive call logs in object storage and use a message queue to smooth out traffic spikes, decoupling asynchronous batch jobs against the model from online requests.
6. Summary
Token billing for LLM APIs is essentially a precise meter of compute consumption: separate pricing for input and output, plus differentiated pricing for cache hits and misses, form the two central levers for cost optimization. If you apply the principles of stable prefixes, controllable output, tiered routing, and end-to-end observability from the architecture-design stage onward, you can keep invocation cost within a predictable and sustainable range without sacrificing application quality. Understanding the billing model is a fundamental engineering skill for building any LLM application.
