LLM API Pricing and Prompt Caching: A Practical Guide to Cost Optimization
As LLM capabilities keep improving, application-side call volume grows exponentially, and the real constraint on whether an application can run sustainably is the cost model formed by per-token price and request structure. This guide breaks down the three-part billing model of LLM APIs (standard input, cached input, output), explains why cached input is priced far below standard input, and lays out practical levers for reducing spend: layering prompts so stable content comes first, controlling output length, trimming context and improving retrieval precision, batching and model tiering, and building request-level cost observability. It also includes a cost estimation formula, prompt structure examples, and usage-tracking instrumentation.
1. Why LLM API Costs Deserve Their Own Study
As large models keep iterating, call volume on the application side grows exponentially. Model capability matters to enterprises, but what usually determines whether an application can run sustainably is the cost model formed together by per-token cost and request structure. Recently, several model providers have shown two typical pricing shifts when releasing new versions:
- Standard input/output prices trending down overall: new versions are roughly 20% cheaper than the previous generation;
- Cached input priced far below standard input: the unit price for cache-hit tokens is sometimes only one tenth of standard input or lower, a reduction of 50–60%.
Both shifts point to the same trend: the marginal cost of inference is falling fast, and cache reuse has become the biggest lever for cost optimization. Developers who only look at the surface number (“how many dollars per million tokens”) without understanding the billing structure will easily over- or underestimate actual spend.
2. Breaking Down the Billing Model: Three Categories You Should Not Confuse
An LLM API bill is usually made up of three parts, and understanding the differences between them is the prerequisite for any cost accounting.
2.1 Standard Input Tokens
This covers system prompts, user input, conversation history, retrieved context, and so on. This content has to be re-encoded and prefilled on every request, and it is the main source of overhead in the pre-processing stage of inference.
2.2 Cached Input Tokens
For a stable prefix that repeats across requests (fixed system instructions, long domain knowledge, general few-shot examples), the server can reuse the already-computed KV cache and skip the repeated prefill. These tokens are billed at a significantly lower unit price than standard input, but usually come with extra constraints:
- The prefix must match exactly; any character-level difference causes a cache miss;
- Caches have a lifetime and expire after a period without access;
- Some providers bill cache writes and cache hits separately, so read the billing fields carefully.
2.3 Output Tokens
This is the decoding stage of generation, usually the most expensive per token. Output length is directly controlled by the generation strategy: maximum length limits, stop conditions, and whether the model is asked to output its reasoning process.
A common cost estimation formula looks like this:
Cost per request ≈ input tokens × input unit price+ cache-hit tokens × cache unit price+ output tokens × output unit price
Note: whether cache-hit tokens are also charged separately as standard input differs between providers, so verify against the actual billing fields before you commit to a model.
3. The Technical Reasons Behind Cheaper Cached Input
The fact that cached input can cost a fraction of standard input is not merely a commercial promotion; there is clear technical and business logic behind it:
- Prefill is a large share of the cost: in long-context requests, the attention computation over a repeated prefix costs far more than the amortized per-token cost of decoding. A cache hit skips that computation, so the provider saves real compute.
- Better hardware utilization: when a stable prefix is reused across many requests, the KV cache hit rate on the GPU rises, throughput improves, and unit cost naturally drops.
- Steering application-side optimization: low cache prices effectively encourage developers to structure prompts as “stable prefix + variable suffix”, which creates a positive feedback loop with the provider’s scheduling efficiency.
4. Cost-Reduction Practices for Developers
4.1 Layer the Prompt: Put Invariant Content First
Organize the prompt into a “stable layer” and a “dynamic layer”:
SYSTEM_PROMPT = """You are a customer support assistant and must follow these rules:1. ...2. ...(Long fixed guidelines and domain knowledge)"""def build_request(user_query, retrieved_docs):return {# Fixed prefix: system prompt + few-shot examples"system": SYSTEM_PROMPT,# Dynamic part: retrieved content + user question go last"user": f"Reference material: {retrieved_docs}\n\nQuestion: {user_query}"}
Key principle: never insert anything that changes per request (timestamps, random IDs, retrieval results) into the middle of the fixed prefix, or the cache is invalidated from that point onward. If a timestamp is not essential, move it to the end or remove it.
4.2 Control Output Length
Output is usually the most expensive per token, so compressing it pays off most directly:
- Explicitly instruct the model to “answer concisely” or “output JSON only, no explanation”;
- Set a reasonable
max_tokenslimit; - Use structured output (JSON Schema constraints) to avoid verbose natural-language wrapping;
- For classification and extraction tasks, ask for short labels rather than full sentences.
4.3 Trim Context and Improve Retrieval Precision
- Apply a rolling window or summary compression to conversation history so it does not accumulate indefinitely;
- Improve retrieval precision: fewer but more relevant documents beat stuffing in documents and hoping for the best;
- Periodically evaluate how much each part of the context contributes, and delete content with zero gain.
4.4 Batching and Model Tiering
- Use the batch API for offline tasks, which typically comes with an additional discount;
- Use a lightweight model for simple tasks (classification, format validation) and reserve the flagship model for complex reasoning;
- Build a “small first, then large” cascade: escalate to the larger model only when the small model’s confidence is insufficient.
5. Build Cost Observability
Quantify before optimizing, and avoid decisions based on gut feeling. On the application side, record:
| Metric | Description |
|---|---|
| Per-request token usage | Input / cache hits / output recorded separately |
| Cache hit rate | Cache-hit tokens ÷ total input tokens |
| Cost per successful interaction | Bill amount ÷ number of effective interactions |
| Cost per unit of work | For example, “cost per ticket processed” |
Example instrumentation:
def track_usage(response, task_type):usage = response.usagemetrics.emit("llm.input_tokens", usage.input_tokens, tags={"task": task_type})metrics.emit("llm.cached_tokens", usage.cached_tokens, tags={"task": task_type})metrics.emit("llm.output_tokens", usage.output_tokens, tags={"task": task_type})metrics.emit("llm.cache_hit_rate",usage.cached_tokens / max(usage.input_tokens, 1),tags={"task": task_type})
Combined with cloud logging and monitoring alerts, you can catch cost anomalies quickly, such as output length spiking after a version update.
6. Summary
LLM inference prices are on a sustained downward trend, but cost optimization cannot just wait for price cuts. The path you actually control is: understand the three-part billing structure → put stable content first to maximize cache hits → strictly manage output length and context size → build per-request cost observability. For applications at scale, a 10-percentage-point improvement in cache hit rate often saves more than the model’s own price reduction. Treating cost as a first-class engineering metric is what lets an intelligent application keep its quality while staying within budget over the long run.
