How to Cut LLM API Costs: A Practical Guide to Caching, Context, and Routing
Rising LLM API bills can usually be reduced without switching providers. This guide breaks down the cost formula behind every inference request and walks through four engineering levers: prefix caching, context governance, tiered model routing, and observability with budget guardrails. It also covers how billing models, prepaid token packages, and free tiers affect total spend, with code examples you can adapt.
1. Understand the Bill Before Cutting Costs
When LLM API costs climb, most teams reach for a new vendor first. A more effective starting point is decomposing the bill. The cost of a single inference request typically comes from three parts: the volume processed on the input side, the volume generated on the output side, and waste from repeated computation. The third part is the easiest to overlook, yet it often holds the largest optimization headroom.
Writing cost as a quantifiable expression helps locate the bottleneck:
total cost ≈ Σ(input tokens × input price) + Σ(output tokens × output price) − cache discount
The formula shows there are only four paths to lower cost: reduce input volume, reduce output volume, increase the cache discount, and lower the unit price. The first three are controllable on the engineering side; the fourth belongs to procurement. Engineering optimizations are usually “free” and their effects stack, so they should come first.
2. Cache Hits: Turn Repeated Computation into Zero Cost
Most mainstream inference services offer prefix caching: when a request’s prompt prefix is identical to a previous request, that portion of the input is not recomputed, and billing is significantly reduced, sometimes free in certain scenarios. Capturing this benefit comes down to putting stable content first and volatile content last.
The practical rules:
- Keep system prompts, tool definitions, few-shot examples, and long document background at the very front of the request, and do not concatenate strings per request;
- Move volatile fields such as timestamps, random IDs, and user input to the end of the prompt;
- Never inject dynamically rendered content into the stable prefix. For example, putting
current time: {{now}}in the system prompt invalidates the entire prefix on every call.
A structural comparison:
# Bad: dynamic content pollutes the prefix, so the cache never hitsprompt_bad = f"""You are an assistant. Current time {datetime.now()}. Tool definitions: {tools}User question: {question}"""# Good: stable prefix + volatile suffixSYSTEM = "You are an assistant. Tool definitions: " + tools # in-process constant, never changesdef build(question: str) -> list:return [{"role": "system", "content": SYSTEM},{"role": "user", "content": question + f"\n[req_id={uuid4()}]"},]
In coding scenarios, long text such as repository rules, directory structure, and coding conventions is naturally suited to a stable prefix. In practice, fixing this background in place typically pushes the cache hit rate above 90%, meaning most input is no longer billed. Note that caches have a time-to-live, and services differ in their minimum cacheable length, so measure the hit rate with a small traffic canary rather than estimating by feel.
3. Context Governance: Long Windows Are Cost Amplifiers
Native support for million-token context does not mean stuffing a million tokens into every request. Context length affects cost linearly or even superlinearly, and long context also dilutes the model’s attention, degrading output quality — a lose-lose of more expensive and worse.
Governance measures:
- Retrieval instead of full-volume feeding. Use vector or keyword retrieval to recall Top-K fragments, keeping the recalled volume in the low thousands of tokens;
- Layered summarization. Summarize long documents offline and store them, so online requests carry only the summary and the matched fragments;
- History trimming. For multi-turn conversations, use a sliding window plus rolling summary instead of unlimited appending;
- Output constraints. Explicitly cap output format and length to avoid output bloat from free-form generation.
A reusable trimming function:
def fit_context(system: str, retrieved: list[str], history: list[dict],budget: int = 8000) -> list:used, msgs = len(system) // 2, [{"role": "system", "content": system}]for chunk in retrieved: # guarantee retrieved content firstif used + len(chunk) // 2 > budget * 0.6: breakmsgs.append({"role": "user", "content": f"[doc]{chunk}"})used += len(chunk) // 2for turn in reversed(history): # then add the most recent turnsif used + len(turn["content"]) // 2 > budget: breakmsgs.append(turn); used += len(turn["content"]) // 2return list(reversed(msgs))
4. Call Orchestration: Match Models to Capability Tiers
Having a single model handle every task is a common source of waste. The more economical approach is difficulty-based routing: send requirement breakdown, solution planning, and result review — steps that need strong reasoning — to a more capable, higher-priced model; send code completion, format conversion, batch rewriting, and log classification — deterministic execution steps — to a lightweight, low-priced model.
A typical three-stage pipeline:
Plan (strong model, low-frequency calls)↓ produces structured stepsExecute (lightweight model, high-frequency calls, batched and concurrent)↓ produces candidate resultsReview (strong model, sampled only on high-risk cases)↓ pass / send back for redo
Three points for implementation: first, the planning output must be a structured intermediate artifact (such as a JSON step list) so downstream stages can consume it reliably; second, the execution stage should run concurrently and merge requests to cut network and scheduling overhead; third, review should sample rather than run in full, keeping strong-model calls down to a few percent of the total.
To be objective, weaker models are often “not proactive enough” in long-chain autonomous tasks and need upstream planning to specify every step, otherwise they stall midway or drift from the goal. Tiered routing is therefore not a simple cost compromise but an engineering choice that pushes uncertainty upstream and certainty downstream.
PLAN = """You are a planner. Break the task into an array of steps, each with action/tool/input.Output JSON only: {"steps":[{"action":"...","input":"..."}]}"""async def pipeline(task: str):plan = await strong_model(task, system=PLAN, temperature=0)results = await gather(*[weak_model(s["input"]) for s in plan["steps"]])return await strong_model(task, system=REVIEW, context=results)
5. Procurement and Quota Strategy: Token Packages, Free Tiers, and Usage Accounting
Beyond unit price, the billing model also affects total cost. Three common models exist: pay-as-you-go by token, prepaid token packages, and trial channels with free quotas. When usage is predictable and stable over the long term, prepaid packages cost considerably less per token than pay-as-you-go; when usage fluctuates or you are in a validation phase, pay-as-you-go and free quotas fit better.
A practical capacity calculation: first measure average daily input and output tokens, multiply by the cache hit rate to get the actual billed volume, then choose a tier accordingly.
daily billed volume = daily total tokens × (1 − cache hit rate)monthly package need = daily billed volume × 30 × safety factor (1.2–1.5)
If the measured hit rate exceeds 90%, a package with a nominal quota of 50 million tokens can support several times the call volume. Base accounting on monitoring data, not theoretical estimates.
6. Observability: No Measurement, No Cost Reduction
Cost reduction must rest on observability. Collect at least these metrics and build dashboards and alerts: input/output tokens per request, cache hit rate, cost per request, cost share broken down by business line, and failure and retry rates. Retries are a hidden cost driver — a single timeout retry can double that request’s cost — so bring retry counts and timeout settings into governance scope.
Also set budget guardrails: assign daily/monthly quotas per business line, and when nearing a threshold, downgrade to the lightweight model or queue, so a single misbehaving task cannot blow through the budget.
7. Conclusion
Faced with rising call costs, the most robust path is not rushing to switch services but doing three things first: restructure prompts into a cache-friendly shape, compress context to what is necessary, and route tasks by difficulty. Stacked together, these engineering optimizations typically cut cost by an order of magnitude while quality rises rather than falls. On top of that, combining procurement strategy around token packages and free quotas with thorough usage monitoring and budget guardrails forms a sustainable cost-control loop. For an out-of-the-box, low-barrier validation environment, you can also look at the free quotas and trial channels offered by Baidu AI Cloud, validate with a small step under real business traffic, and only then commit at scale.
