LLM Cost Optimization: Routing, Batching and Budgets
Inference cost is the first bill a language model product feels and the last one most teams analyze properly. The invoice arrives as a single number that mixes easy traffic with hard traffic, retries with first attempts, and useful tokens with boilerplate â so the natural reactions, nagging users about verbosity or picking the cheapest model everywhere, either hurt the product or fail to move the number. Real optimization works like capacity planning: instrument where tokens actually go, rank the levers by dollars and risk, apply them in order, and set budgets so the next feature cannot quietly undo the savings. Most teams that do this cut spend by half or more while quality holds or improves, because the first fixes remove waste rather than capability.
Prerequisites
- !How LLM inference is metered in input and output tokens
- !Basic familiarity with retrieval-augmented generation
- !Access to usage logs or a provider billing console
What You'll Learn
- 1Decompose an LLM invoice into drivers you actually control
- 2Route routine traffic to cheap models with a measured fallback path
- 3Trim prompts and context to a token budget without losing answer quality
- 4Batch and deduplicate offline work, and cap spend with runtime budgets
Why One Invoice Hides Six Different Bills
Every lever in this lesson attaches to one row of a decomposition, so the decomposition comes first. Input tokens dominate retrieval-heavy applications, where a question of twenty tokens arrives wrapped in four thousand of context: the user asked about one paragraph and paid for the whole document. Output tokens dominate long-form generation, where the price per token is higher and the model bills for text nobody reads to the end. Around both sit supporting costs â embeddings, reranking, tool calls, and the retries created by timeouts and malformed outputs.
| Cost driver | Typical share of spend | Who controls it |
|---|---|---|
| Static prompt repeated per call | 10 to 40 percent of input | Prompt design, prefix caching |
| Retrieved context length | 20 to 60 percent of input | Chunking, reranking, truncation |
| Long answers nobody finishes | Large share of output | Output contracts, max tokens |
| Retries and duplicate work | 3 to 15 percent | Idempotency, backoff, validation |
| Premium model on routine traffic | Varies widely by product | Routing policy |
| Unbounded agent loops | Occasional but severe | Budgets and hop limits |
Instrument before you change anything: log input and output tokens per request alongside the prompt version, model, feature and tenant. One week of that data usually exposes a single unexamined field â an entire catalog entry passed where three lines would do â costing more than every technique in blog posts combined. It also fixes your baseline â without one, savings are a story rather than a number you can defend.
Routing: Cheap by Default, Escalating on Failure
Routing is the highest-leverage lever because it acts before a single token is billed. A classifier or a handful of rules decides which model handles each request: a small inexpensive model for classification, extraction and routine answers, a frontier model for ambiguous, high-value or multi-step work. The discipline that makes this safe is measurement rather than assumption â a router that sends ninety percent of traffic to the cheap model only helps if the failures it produces are acceptable to the people who receive them.
PRICES = { # USD per 1M tokens: (input, output)
"small": (0.15, 0.60),
"mid": (1.00, 4.00),
"frontier": (3.00, 15.00),
}
def estimate(model: str, in_tokens: int, out_tokens: int) -> float:
pin, pout = PRICES[model]
return (in_tokens * pin + out_tokens * pout) / 1_000_000
def route(question: str, turns: int, needs_tools: bool, score: float) -> str:
if needs_tools or score > 0.8 or turns > 6:
return "frontier" # multi-step, tool-bearing, ambiguous
if score > 0.5:
return "mid" # moderate reasoning
return "small" # routine extraction and lookup
def answer(question: str, score: float, small, frontier, gate) -> str:
if route(question, turns=0, needs_tools=False, score=score) != "small":
return frontier.complete(question)
try:
draft = small.complete(question, max_tokens=500)
except Exception:
return frontier.complete(question) # never fail on transport errors
if gate(draft):
return draft
escalations.inc() # metric you watch weekly
return frontier.complete(question)
The fallback pattern matters more than the classifier itself. Send routine traffic down the cheap path behind a quality gate and escalate whatever fails it, and you keep the savings of the small model with the ceiling of the large one. Watch the escalation rate as the health of the scheme: a rate creeping upward means the gate is misconfigured or the cheap model drifted under a provider update. Pair it with cost per resolved request rather than cost per call, because a cheap request that needs three retries is not cheap.
Squeezing the Prompt You Repay on Every Call
Context reduction costs nothing in quality when it is done with evidence. Passages retrieved but never cited are pure waste: the model reads them, weighs them, then ignores them. Measure how often each retrieved chunk shows up in finished answers and stop paying for the ones that never do. Rerankers earn their fee in exactly this spot â retrieve wide and cheap, then hand only the strongest passages to the generator. The cut often improves answers as well as invoices, because the model sees less competing noise and fewer contradictory excerpts.
def build_context(query, retriever, reranker, llm, budget_tokens=1500):
candidates = retriever.search(query, k=30) # cheap recall
ranked = reranker.rerank(query, candidates, top_k=8) # precise cut
picked, used = [], 0
for doc in ranked:
cost = len(doc.text) // 4 # about 4 chars per token
if used + cost > budget_tokens:
continue
picked.append(doc)
used += cost
if not picked:
return ""
summary = llm.complete(
"Condense these passages to the facts the question needs. "
"Keep names and numbers exact. Maximum 200 words.",
context="\n\n".join(d.text for d in picked[:3]),
)
return summary
Two smaller cuts belong in the same pass. First, the static half of the prompt: system policy, tool definitions and few-shot examples lead every request byte for byte, and providers that support prefix caching discount those tokens when the prefix matches exactly. Keep that block stable, place anything time-varying after it, and never drop a request id or timestamp at the top. Second, the output side: set an explicit ceiling and a shape contract â headings, bullets, a fixed schema â so the model stops when the answer stops instead of padding toward the limit.
Batching Work That Can Wait
Not every request needs an answer this millisecond. Backlog classification, nightly enrichment, evaluation runs and synthetic data generation all tolerate minutes of delay, and they are where provider batch endpoints pay off, commonly at roughly half the interactive rate for a job allowed to return within a day. The other half of batching is deduplication: identical requests arriving from retries, polling loops or a hundred users asking the same popular question should collapse into one billed call, with every caller awaiting the same future.
import asyncio, hashlib, json, time
class OfflineBatcher:
def __init__(self, client, max_wait=1.0, max_size=64):
self.client, self.max_wait, self.max_size = client, max_wait, max_size
self.queue = asyncio.Queue()
self.inflight = {}
async def submit(self, prompt, params):
key = hashlib.sha256(
json.dumps([prompt, params], sort_keys=True).encode()
).hexdigest()
if key not in self.inflight:
self.inflight[key] = asyncio.get_event_loop().create_future()
await self.queue.put((key, prompt, params))
return await asyncio.shield(self.inflight[key])
async def drain(self):
while True:
first = await self.queue.get()
batch, deadline = [first], time.time() + self.max_wait
while len(batch) < self.max_size and time.time() < deadline:
try:
batch.append(self.queue.get_nowait())
except asyncio.QueueEmpty:
await asyncio.sleep(0.05)
outputs = await self.client.batch_complete(
[p for _, p, _ in batch], params=first[2]
)
for (key, _, _), out in zip(batch, outputs):
self.inflight.pop(key).set_result(out)
Interactive traffic stays off that path. Streaming costs nothing extra and improves perceived latency enough that users rarely register the raw speed of the model, so spend your savings where latency does not matter rather than shaving seconds where it does.
Budgets That Stop Spend at Runtime
Optimizations decay. A new agent loop, a wider retrieval window, or a colleague experimenting with a larger model can double spend in a week, and a monthly invoice cannot interrupt any of them. Budgets move the limit into the request path, where it can refuse work, instead of leaving it as a quarterly discovery.
class BudgetExceeded(Exception):
pass
class SpendGuard:
def __init__(self, daily_usd, max_hops=6, max_output_tokens=2000):
self.daily_usd = daily_usd
self.max_hops = max_hops
self.max_output_tokens = max_output_tokens
self.spent_usd = 0.0
self.hops = 0
def before_call(self, model, est_input, est_output):
pin, pout = PRICES[model]
capped = min(est_output, self.max_output_tokens)
estimate = (est_input * pin + capped * pout) / 1_000_000
if self.spent_usd + estimate > self.daily_usd:
raise BudgetExceeded("request would exceed the daily spend cap")
self.hops += 1
if self.hops > self.max_hops:
raise BudgetExceeded("agent run exceeded its hop limit")
return capped
def after_call(self, model, in_tokens, out_tokens):
pin, pout = PRICES[model]
self.spent_usd += (in_tokens * pin + out_tokens * pout) / 1_000_000
Three levels cover almost every product: a daily dollar cap per tenant that returns a clean error instead of a surprise bill, a hop limit bounding tool calls per run, and an output ceiling applied before generation starts. Charge before the work, not after â accounting for tokens already spent only describes what happened. Feed the same counters into alerts at fifty and eighty percent of the cap so someone can react while budget remains.
The Numbers That Prove the Work
Weak metrics make weak optimization programs. Cost per thousand requests drifts whenever the traffic mix shifts, and raw token counts fall the moment a feature is removed. Track a small set that names a cause rather than an effect, and report it beside an evaluation score so the pairing stays honest: cost down with quality flat is a win, cost down with quality down is only a discount.
| Metric | What it exposes | Healthy sign |
|---|---|---|
| Cost per resolved request | Retries, escalation churn, thrash | Flat or falling as volume grows |
| Input tokens per request | Context bloat, dead retrieved chunks | Falling without quality loss |
| Escalation rate | Router accuracy and model drift | Stable, with alerts on step changes |
| Dedup and cache hit rate | Repeated work still being billed | Rising across features |
| Share of spend by feature | Which feature owns the bill | Known and budgeted per team |
| Output tokens per answer | Padding and unbounded generation | Matches the format contract |
Review these weekly and attach a reason to every move, so a regression surfaces within days and its cause is written down before the next team reintroduces it.
When Cheap Answers Cost More Than They Save
Routing and trimming are not uniformly safe. A smaller model that misreads an intent, invents a policy detail or fumbles a tool call is more expensive than the tokens it saved: the user retries, files a ticket, or leaves. Optimize where failure is visible and recoverable â extraction, tagging, drafting text a human reviews â and stay conservative where failure is silent, such as confident answers that happen to be wrong. Reserve frontier capacity for requests that carry revenue, treat every routing threshold as a hypothesis with a measuring period rather than a one-time decision, and re-check it after any provider model update.
đĄOrder of operations
Apply the levers in this sequence: measure the baseline, cut dead context, add routing with a fallback, batch the offline half, then cap everything with budgets. Budgets last because they are the only lever that keeps the savings from eroding.
Common Mistakes
Optimizing before logging tokens per request
Fix: Instrument input, output, model, prompt version and feature first so savings have a baseline
Sending everything to the cheapest model
Fix: Route behind a quality gate and escalate failures; watch the escalation rate weekly
Retrieving wide and sending all chunks to the generator
Fix: Rerank, then fill a token budget and pay only for passages that get cited
Letting agents loop with no ceiling
Fix: Enforce a daily dollar cap, a hop limit and an output token ceiling before each call
Treating cost per call as the north-star metric
Fix: Report cost per resolved request next to an evaluation score
Batching interactive traffic to chase a discount
Fix: Batch only offline workloads; stream interactive answers instead
Best Practices
- Keep the static prompt prefix byte-stable so prefix caching can discount it
- Cap output tokens and demand a structured answer shape in the same request
- Deduplicate identical requests by hashing prompt and parameters together
- Attribute spend per feature and per tenant so budgets have an owner
- Re-measure routing thresholds after every provider model revision
Key Takeaways
- Split the invoice into input, output, retry and model-selection drivers before changing anything
- Routing with a measured fallback delivers the largest savings with the least user-visible risk
- Reranking plus a hard context budget cuts input tokens and often improves answers
- Batch and deduplicate offline work; stream anything a person is waiting on
- Runtime budgets â dollars, hops and output tokens â are what keep savings from decaying
- Track cost per resolved request beside quality, never cost alone