LLM API Cost Optimization: Cached Inputs and Request Pipeline Design
Reduce LLM API costs by improving input cache reuse and optimizing the request pipeline. This article explains prefix caching, six practices for stabilizing reusable context, cost and quality monitoring, reliability controls, and a staged rollout process for validating savings without sacrificing task performance.
1. Break Down the Bill: Focus on Input Tokens
LLM API pricing typically has two components: input tokens and output tokens. Many teams focus on shortening responses, but real workloads often involve long context and short answers. In retrieval-augmented generation (RAG), codebase Q&A, long-document summarization, and multi-turn customer support, input tokens can account for more than 80% of total token usage.
That makes the input side the primary opportunity for reducing per-request costs.
Start with a measurable cost model:
Cost per request = Input tokens × Input rate + Output tokens × Output rateInput tokens = Cached input tokens + Uncached input tokens
Cached input tokens typically cost substantially less than uncached tokens. Discounts vary by provider, so consult the relevant API documentation for current pricing.
The goal is therefore not simply to write shorter prompts. It is to increase the share of reusable input, measured by the token-level cache hit rate:
Cache hit rate = Cached input tokens / Total input tokens
Several cloud providers have reduced general-purpose LLM API prices and introduced substantial discounts for cached inputs. These pricing changes shift repeated context from full-price processing to discounted processing.
For developers, the architectural implication is straightforward: stable, reusable context can translate directly into a lower bill.
2. What Input Caching Actually Reuses
Common prefix-caching implementations rely on a simple but strict requirement: the prefix must match exactly. Conceptually, the service compares request content from the beginning and identifies the longest matching token prefix. Eligible matching tokens receive cached-input pricing; tokens from the first difference onward are processed as uncached input.
This creates three constraints:
- Order matters. A change near the beginning prevents subsequent content from being reused as part of that prefix. Place changing content later in the request.
- Exact content matters. Semantic equivalence is not enough. Preserve identical serialized content: an extra space, revised wording, or changed line ending can break the match.
- Timing matters. Cache entries have a lifetime, and providers may require a minimum prefix length. Check the official documentation for platform-specific rules.
These constraints explain many cases where caching is available but produces little or no savings.
3. Six Practices for Building Stable Prefixes
3.1 Version System Prompts Instead of Generating Them Dynamically
Treat system prompts, tool schemas, and few-shot examples as code assets. Assign versions, review changes, and release them gradually.
Do not insert the current time, request IDs, or user nicknames into the reusable prefix at runtime.
3.2 Separate Stable Prefixes from Dynamic Content
# Pseudocode: stable prefix + dynamic suffixSYSTEM_PROMPT = load_versioned("system_prompt", "v3") # Fixed contentTOOL_SCHEMA = load_tool_schema("v3") # Fixed structuredef build_messages(history, user_input):prefix = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "system", "content": TOOL_SCHEMA},]tail = history + [{"role": "user", "content": user_input}]return prefix + tail # Dynamic content always comes last
Keep the reusable section deterministic, and append request-specific content after it.
3.3 Make Serialization Deterministic
Tool definitions and structured context need stable serialization. Sort map keys, avoid nondeterministic iteration, and eliminate ordering differences caused by changing hash seeds.
JSON field order is not inherently consistent across language runtimes. Define it explicitly rather than relying on runtime behavior.
3.4 Place Retrieved Content Later and Organize It into Chunks
In RAG workflows, placing changing retrieved documents early in a request can disrupt an otherwise reusable prefix.
A recommended structure is:
Stable prefix → Current question → Retrieved passages
For large collections of passages, sorting by document ID and applying a fixed truncation policy can improve consistency and reuse where prefixes match across requests.
3.5 Append to Multi-Turn Conversations
Append each new turn at the end rather than rewriting earlier messages.
When history needs correction, add a correction message instead of editing a previous turn. This preserves the existing prefix.
3.6 Remove Hidden Sources of Variation
Common prefix breakers include:
- Timestamps
- Random trace IDs
- Differences in floating-point formatting
- Template-engine whitespace handling
- A/B test assignment markers
- Staged-rollout flags
Move these values into the dynamic section of the request.
4. Observability: Attribute Costs Before Optimizing Them
Cost reduction must be measurable. Instrument the request pipeline across three dimensions and connect the resulting data to logging, monitoring, and alerting:
- Tokens: Record total input tokens, cached input tokens, output tokens, and cache-hit status for every request.
- Costs: Aggregate by business line, use case, and model tier. Track both cost per request and cost per business outcome, such as cost per 1,000 answered questions.
- Quality: Higher cache hit rates must not come at the expense of results. Track task success rates and human handoff rates alongside costs.
Example metrics dashboard├─ Cache hit rate by use case and model tier├─ Average input tokens and P95 input tokens├─ Cost per request and daily cost trends└─ Task success rate, timeout rate, and rate-limit events
Alerts for sudden drops in cache hit rate can often help teams trace a problem to a prompt release or template change within minutes.
5. Reliability Controls: Rate Limits, Retries, and Fallbacks
Cost efficiency and reliability are closely connected. Recommended engineering practices include:
- Exponential backoff with jitter: Automatically retry only idempotent read requests. Write operations require idempotency keys.
- Client-side rate limiting and queue-based traffic smoothing: Use message queues to spread out bursts and avoid retry storms after peak traffic triggers provider rate limits.
- Separate timeout budgets: Set individual budgets for retrieval, generation, and post-processing so that long-tail requests do not undermine the entire pipeline.
- Tiered model routing: Send simple classification, extraction, and formatting tasks to smaller models, and reserve larger models for complex reasoning. Tiered routing is often the next major source of savings after caching.
- Context compression: Extract structured information or summarize long documents before passing them to the model, reducing unnecessary input tokens.
6. Validate Savings and Roll Out Gradually
Do not estimate savings by intuition. Use reproducible offline replay to compare implementations:
- Sample real requests from the previous seven days and remove sensitive information to create a replay dataset.
- Run both the original and optimized request pipelines in a staging environment.
- Compare four metrics: cache hit rate, average input tokens, cost per request, and task success rate.
- Once targets are met, expand production traffic gradually from 5% to 20% to 50%, with a one-click rollback available.
The recommended implementation order is:
Instrumentation and cost attribution → Stable-prefix separation → Moving retrieved content later → Tiered model routing → Context compression
The first two steps often deliver a substantial share of the benefits while carrying the lowest implementation risk.
7. Anti-Patterns to Avoid
- Putting private data, secrets, or session data into a shared reusable prefix. This creates cross-request disclosure risks. Multi-tenant systems require logical isolation.
- Padding prompts with irrelevant content to meet cache-length thresholds. A higher hit rate can still produce a higher total bill.
- Optimizing cost without monitoring quality. Poorer results can shift expenses back to human operators.
- Treating provider discounts as permanent. Preserve the ability to replace models and providers rather than tying the architecture to one pricing policy.
Conclusion
Reducing LLM API costs is not a one-time pricing negotiation. It is an ongoing engineering discipline: use stable prefixes to enable cache reuse, route tasks to models that match their complexity, and attribute spending to business outcomes through observability.
As request volume grows, the cumulative benefits of these practices can outweigh the short-term gains from a single price reduction.
Organizations already using general-purpose LLM APIs, logging, and monitoring services—including those from Baidu AI Cloud where available—can build these practices into their existing infrastructure.
