Cutting LLM Costs: Prompt Caching, Model Routing, and Token Budgets
Derar SattoufUpdated AI engineering

The first LLM bill is a pleasant surprise. The tenth is a meeting. As usage grows, agents loop, contexts balloon, and every feature quietly defaults to the biggest model, spend climbs faster than revenue. The good news: LLM costs are unusually compressible. Most applications can cut spend by half or more with changes that users never notice, because most tokens in a typical request are repeated, unnecessary, or processed by a model more powerful than the task needs.
Start by measuring cost per task and per feature, not just the monthly invoice. You cannot optimize what you cannot attribute. Then go after prompt caching: put stable content (system prompt, tool definitions, documents) at the start of the prompt so providers can reuse it at a steep discount. This is often the single biggest win for agents and RAG.
After that, route by difficulty, using small, cheap models for simple tasks and escalating only when needed. Trim tokens with shorter system prompts, fewer retrieved chunks, compacted history and concise output limits. Batch non-urgent work for discounts, and cache repeated requests, both exact and semantic. Finally, add budgets and alerts so a runaway loop cannot generate a five-figure surprise.
Pricing changes often and differs by provider, so treat the numbers below as illustrative and check your provider's current pricing and feature docs.
Know where the money goes
Cost per request is roughly:
cost = (input_tokens x input_price)
+ (cached_input_tokens x cached_price) # discounted
+ (output_tokens x output_price) # typically several times input price
+ (reasoning/thinking tokens x output_price)Output tokens usually cost several times more than input tokens, and reasoning models can generate large numbers of hidden thinking tokens. Agents multiply everything: each step resends the whole growing context.
Instrument every call
type Usage = {
feature: string; // "support-bot", "doc-summary"
userId?: string;
model: string;
inputTokens: number;
cachedInputTokens: number;
outputTokens: number;
latencyMs: number;
costUsd: number;
};
export async function tracked<T>(feature: string, call: () => Promise<{ result: T; usage: RawUsage; model: string }>) {
const t0 = performance.now();
const { result, usage, model } = await call();
await metrics.record({
feature, model,
inputTokens: usage.input_tokens,
cachedInputTokens: usage.cache_read_input_tokens ?? 0,
outputTokens: usage.output_tokens,
latencyMs: performance.now() - t0,
costUsd: priceOf(model, usage),
} satisfies Usage);
return result;
}Build a dashboard answering: cost per feature, cost per user and per tenant (find the 1 percent of users generating 40 percent of spend), average tokens per request by feature, cache hit rate, and cost per successful task (including retries). An LLM gateway (see the AI gateway post on this blog) gives you much of this for free.
Prompt caching: the biggest lever
Providers can cache the processed prefix of a prompt. When a later request starts with the same prefix, the cached portion is billed at a fraction of normal input price (commonly around 10 percent for cache reads, with a modest premium to write the cache on some providers) and also returns faster.
Rules (details vary by provider; read the docs):
- Caching works on an exact prefix match. Anything that changes early in the prompt invalidates everything after it.
- Therefore order prompts static to dynamic: system instructions, tool definitions, reference documents and few-shot examples first; conversation history next; the new user message last.
- There are minimum prefix lengths for caching, and caches expire after a short TTL (minutes), refreshed on use. Frequent traffic keeps the cache warm.
- Some providers require you to mark cache breakpoints explicitly; others cache automatically.
Bad vs good prompt layout
BAD (cache never hits: timestamp changes every request at the top)
"Current time: 2026-11-09T10:15:30Z. User: Ada. You are a support agent..."
[20,000 tokens of policy docs]
[user question]
GOOD (stable prefix, dynamic bits at the end)
"You are a support agent..." <- static
[20,000 tokens of policy docs] <- static
[tool definitions] <- static, sorted deterministically
---- cache breakpoint ----
"Context: time=..., user=Ada" <- dynamic
[conversation history]
[user question]Example with an explicit cache marker
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const response = await client.messages.create({
model: "claude-sonnet-5-5",
max_tokens: 800,
system: [
{ type: "text", text: SYSTEM_INSTRUCTIONS },
{
type: "text",
text: POLICY_DOCUMENTS, // large, stable reference material
cache_control: { type: "ephemeral" }, // cache everything up to here
},
],
messages: [{ role: "user", content: userQuestion }],
});
console.log(response.usage);
// { input_tokens, cache_creation_input_tokens, cache_read_input_tokens, output_tokens }Check cache_read_input_tokens to confirm hits; if it is zero, something in your prefix is changing (timestamps, random IDs, unsorted JSON keys, reordered tools).
Where caching shines
- Agents that resend long histories and tool definitions every step.
- RAG over a fixed document set (put the documents in the cached prefix instead of retrieving per query, when they fit).
- Few-shot prompts and large style guides.
- Multi-turn chat: cache the conversation up to the previous turn.
A prompt with a 20,000-token stable prefix called 1,000 times per hour can cut input costs by roughly 80-90 percent on that portion. Make cache hit rate a tracked metric.
Model routing and cascades
Not every request needs your best model. Classification, extraction, formatting, and simple Q&A are well within small-model capability, at a fraction of the price and latency.
Static routing by task
const MODEL_BY_TASK = {
classify_intent: "claude-haiku-5-5",
extract_fields: "claude-haiku-5-5",
draft_reply: "claude-sonnet-5-5",
complex_analysis: "claude-opus-5-5",
} as const;Cascade: try cheap first, escalate on low confidence
export async function answer(question: string) {
const first = await ask("claude-haiku-5-5", question, { schema: AnswerWithConfidence });
const needsEscalation =
first.confidence < 0.7 ||
first.answer.length === 0 ||
!passesValidators(first.answer);
if (!needsEscalation) return first.answer;
const second = await ask("claude-sonnet-5-5", question, { schema: AnswerWithConfidence });
return second.answer;
}Confidence from the model itself is imperfect; combine it with deterministic validators (schema validation, tests, citation checks) and, when worthwhile, a small trained router. Validate on your eval set that the cascade preserves quality: measure pass rate and cost together. Track the escalation rate; if 90 percent of requests escalate you have added latency and cost for nothing.
Use the largest models for planning, hard reasoning, and final review, and cheaper ones for the high-volume steps in between (a pattern that works well in multi-agent pipelines).
Trim the tokens you send
Every token you send is paid for on every call.
System prompts
- Remove redundancy, politeness filler, and rules the model follows by default. Test shorter versions against your eval set.
- Move rarely needed instructions into tools or on-demand retrieval rather than the always-on prompt.
Retrieved context (RAG)
- Retrieve fewer, better chunks: add a reranker and pass the top 4-6 rather than 20. Better retrieval beats bigger contexts.
- Deduplicate overlapping chunks and strip boilerplate.
Conversation history
// Keep the last N turns verbatim, summarize the rest
export async function compactHistory(messages: Message[], keep = 6) {
if (messages.length <= keep + 2) return messages;
const old = messages.slice(0, -keep);
const summary = await summarize(old); // use a cheap model
return [{ role: "user", content: `Summary of earlier conversation: ${summary}` }, ...messages.slice(-keep)];
}(Compaction changes the prefix, which breaks caching for that conversation once; do it rarely and in larger steps rather than every turn.)
Tool results
Agents often pour entire API responses, file contents, and web pages into context. Instead:
- Return only the fields needed; truncate with a clear marker.
- Prefer search/snippet tools over "read the whole file."
- Clear stale tool results from context once they have been used.
Images and documents
Images and PDFs are tokenized, sometimes expensively. Resize images to the minimum useful resolution, extract text from PDFs yourself when layout does not matter, and send only relevant pages.
Control the output
Output tokens are the expensive ones.
- Set
max_tokensdeliberately per feature. - Ask for concise formats: "Answer in at most 3 sentences", or structured JSON with short fields, rather than essays.
- Use structured outputs to avoid verbose preambles and retries from parse failures.
- Use stop sequences where appropriate.
- For reasoning models, set the thinking/reasoning budget or effort level to match the task; do not run maximum reasoning for a simple lookup.
- Avoid asking the model to repeat the input back (for example regenerating a whole document to change one line). Use patch/diff formats or tool calls that edit specific sections.
Batch and defer
Many workloads are not interactive: nightly summarization, backfills, classification of historical data, evaluation runs, embeddings. Providers offer batch APIs at roughly half price with relaxed turnaround (often within 24 hours).
// Pseudocode: submit many requests as one batch job, poll for completion
const batch = await client.messages.batches.create({
requests: tickets.map((t) => ({
custom_id: `ticket-${t.id}`,
params: { model: "claude-haiku-5-5", max_tokens: 200, messages: [{ role: "user", content: classifyPrompt(t) }] },
})),
});
// later: retrieve results by custom_id and write them to your databaseAsk of each LLM call: "Does a human wait for this right now?" If not, batch it. You can combine batching with prompt caching for the shared prefix where the provider supports both.
Cache whole responses
Exact-match cache
Deterministic tasks (classification, extraction, translation of fixed strings) repeat inputs more than you expect.
export async function cachedCompletion(key: object, run: () => Promise<string>, ttlSec = 86400) {
const k = "llm:" + sha256(JSON.stringify(key)); // model + prompt + params
const hit = await redis.get(k);
if (hit) return hit;
const out = await run();
await redis.set(k, out, { EX: ttlSec });
return out;
}Semantic cache
Embed the query and return a stored answer when a sufficiently similar question was answered before. It can slash costs for FAQ-style traffic but carries risk: a near-duplicate question with a small but important difference ("refund within 30 days" vs "refund after 30 days") can return a wrong answer. Use a high similarity threshold, scope by tenant and context, never cache personalized or time-sensitive answers, and evaluate false-hit rates before turning it on.
Reduce calls, not just tokens
- Avoid LLM calls where code works: regex, rules, lookup tables, and classical ML handle many classification and formatting tasks for free.
- Collapse multi-step chains when one well-designed call suffices.
- Cap agent loops: maximum steps, maximum tool calls, and a token budget per task; abort and escalate to a human when exceeded.
- Deduplicate retries: retry only on transient errors, with backoff; do not retry on validation failures without changing the prompt.
- Parallelize wisely: fan-out multiplies cost; confirm the benefit.
- Stream and cancel: if the user navigates away or a validator rejects early, stop generation.
const BUDGET = { maxSteps: 12, maxTotalTokens: 150_000 };
let tokens = 0;
for (let step = 0; step < BUDGET.maxSteps; step++) {
const r = await model.step(state);
tokens += r.usage.total;
if (tokens > BUDGET.maxTotalTokens) throw new BudgetExceeded({ step, tokens });
if (r.done) break;
}Guardrails against runaway spend
- Per-user, per-tenant, and per-feature rate limits and daily budgets, enforced in your gateway.
- Alerts on spend rate (for example 3x the trailing average), cache-hit-rate drops, and average tokens per request.
- Hard monthly caps at the provider where available, plus a kill switch for each feature.
- Protect expensive endpoints from abuse with authentication, CAPTCHAs, and quotas. Public chatbots without limits become free inference for strangers.
- Review the top 20 most expensive requests weekly. They are usually bugs (a loop, a giant paste, a missing
max_tokens).
A prioritized action plan
| Priority | Action | Typical effort | Typical impact |
|---|---|---|---|
| 1 | Instrument cost per feature and task | Low | Enables everything else |
| 2 | Reorder prompts for caching; track hit rate | Low-Medium | Very high for agents/RAG |
| 3 | Set max_tokens, trim output formats | Low | Medium |
| 4 | Route simple tasks to small models | Medium | High |
| 5 | Retrieve fewer chunks, compact history, trim tool outputs | Medium | Medium-High |
| 6 | Batch offline workloads | Low-Medium | Up to ~50% on those workloads |
| 7 | Exact and (carefully) semantic caching | Medium | Workload-dependent |
| 8 | Budgets, alerts, loop caps | Low | Prevents disasters |
One guardrail applies to every step: run your eval suite before and after. A cost cut that quietly degrades answers is not a saving, it is a deferred support cost. Track cost per successful task as the headline metric.