GOAT EngineerPreparing your learning space…

AI Engineering · Concept Library · Free article

LLM Cost Optimization

You cut an LLM bill by pulling levers in order: cap the output, trim the context, route cheap-first, cache the stable prefix, and batch anything nobody is waiting on. Each lever has a failure mode that can cost more than it saves, so the only honest scoreboard is cost per resolved outcome.

An LLM call's cost is tokens × price, with output priced several times higher than input, and at real traffic that per-call number becomes a monthly bill that can quietly make your product unprofitable. Optimizing it is a set of levers, trim output, trim context, route cheap-first, cache the stable prefix, batch the async work, right-size the model, but each has a failure mode (routing that escalates too little costs more; caching a churning prefix costs more; trimming context too far costs more), the levers interact and partly cancel, and the only honest scoreboard is cost per resolved outcome, not cost per token. Cost is a functional requirement, designed in, not cleaned up later.

Wrenlet is working. The assistant drafts good replies, extracts clean data, streams smoothly. Then the first real monthly invoice arrives, and it's a number nobody on the team guessed. Your co-founder does the math out loud: at this rate, each ticket the AI resolves is costing more than it would cost a human to answer it. The product that was supposed to make support cheap is, right now, making it expensive. Nothing is broken. You just never treated cost as part of the design.

The cost model, and the two things that surprise everyone

The base formula is simple: you pay per token, and input and output are billed separately. Two facts about that make the bill land harder than people expect.

Output costs far more than input per token, typically five to eight times as much. Checked in September 2026, it is exactly five across every Anthropic model, five on OpenAI's flagship, and eight on the small gpt-5 tiers; Gemini sits between the two. The assumption worth dropping is that the steep ratios live at the frontier. They do not. The cheap tier is often where output is proportionally dearest, which means the model you picked to save money is the one that punishes a chatty answer hardest. Check the ratio for the exact model and context tier you are on, because it is not a constant, and treat every number on this page as a shape rather than a quote. And the bill is per-call times traffic. A cost that looks trivial per request, a fraction of a cent, becomes a serious monthly number once you multiply by hundreds of thousands of calls a day.

One caution about comparing prices across model generations, because it catches people out: the token count is not a fixed property of your text. Anthropic's own pricing page notes that its newer models use a tokenizer producing roughly 30% more tokens for the same text. A headline price cut across that boundary can be partly or wholly an accounting change, so compare on the cost of a representative request, never on the per-token rate alone.

There's a third surprise hiding in agentic flows. One “resolved ticket” often isn't one call, it's a chain of them (read the ticket, search the docs, draft, check), and each step re-sends the accumulated context, so the input tokens climb turn over turn. The cost you should budget against is per task, not per call. Each figure on this page carries its own illustrative numbers, chosen to make one shape visible, so do not try to add them up into a single ledger; the worked example above is the ledger. Slide the token counts and turn on agentic mode to see the gap open up:

The interactive version of this example is available when JavaScript loads.

Measure cost per outcome, not cost per token

Here's the trap that sinks cost projects. You optimize $/token or $/call, watch it drop, and declare victory, while the number that actually matters, the cost to resolve a customer's problem, quietly goes up. How? You switched to a cheaper model, so each call is cheaper, but it's wrong more often, so tickets take more retries and more human escalations. Cost per call fell; cost per resolved conversation rose.

So write it down, because the two ambiguities in it are where teams quietly disagree with each other.

cost per resolved conversation = (everything you spent on this cohort) / (conversations that ended resolved)

The numerator is every call the cohort made, retries and abandoned sessions included, plus the cost of the human minutes an escalation consumed. The denominator is where the arguments happen, and the two rules worth agreeing on in advance are these: an abandoned conversation counts in the numerator and not in the denominator, because you paid for it and nobody's problem got solved, and an escalated one counts as resolved, because the customer was helped, but its numerator carries the human's time. Both rules make the number look worse. That is the point of them.

Which levers actually reduce your LLM bill?

Output length first, because output is priced several times input, then the context you pay for on every call, then routing, caching and batching. Start where the leverage is highest and the effort is lowest.

Control the output. Since output tokens dominate the price, capping length is the single best cheap win: set a hard max_tokens, ask for a one-line answer where one line will do, and prefer a compact structured result over a paragraph of prose when a machine is reading it.

Control the context. Every token you put in the prompt is paid on every call. A bloated system prompt is a tax you pay forever; trim it. If you're feeding retrieved documents, send the top few that matter, not everything you found. Fewer input tokens, lower prefill cost, on every single request.

Context discipline has a floor

Trimming context feels like free money, every token you cut is paid back on every call, so the instinct is to cut hard. But there's a floor. Cut past what the model needs to actually answer, and it starts getting things wrong, which fires the exact retry-and-escalation cost you were trying to avoid. So cost per outcome isn't a slope you can ride to zero; it's a U. There's a trough, enough context to answer, not a token more, and both walls of the U are expensive for opposite reasons. Find the trough:

The interactive version of this example is available when JavaScript loads.

Routing: cheap model first, escalate the hard ones

Most tickets are easy. So don't send them all to your most expensive model, try a small, cheap model first, and only escalate the hard cases to the frontier one. Done well, you pay the cheap price on the easy majority and the frontier price on the difficult minority, and the blended cost drops a lot. As a starting point, a cascade on a support workload tends to land somewhere around a fifth to a third of traffic escalated, and you should treat that as a place to begin tuning rather than a target: the right number falls out of your own error rate and the cost of a wrong answer.

But routing has a failure mode that the naive savings pitch never mentions, and it's the reason routing goes wrong in production. If you escalate too few for how often the cheap model is actually wrong, the wrong answers slip through to real customers, and each one costs a retry and a human to clean up. Price those failures in and the cascade can end up costing more than just using the frontier model for everything. Play with it:

The interactive version of this example is available when JavaScript loads.

Prompt caching: cheap reads, but mind the write penalty

If many of your calls share a big, stable chunk at the front, the same long system prompt, the same tool definitions, the same reference document, you can cache that prefix so the model doesn't re-process it every time. A cache read is dramatically cheaper than paying full input price (on the order of a tenth of it on some providers). This is the discount most articles stop at, and it's real. (It gets its own deep dive.)

One clarification first, because two different caches get confused. Every model already reuses its own working memory within a single request, that's automatic and invisible, and it's not what saves you money. The prompt cache here is the opt-in, cross-request kind: it persists the processed prefix so your next call can skip re-processing it. That's the one you pay for and design around.

Two catches the discount pitch skips, and they differ by provider, so this is one of the places to read your own docs rather than a blog. The first is the write. On Anthropic the call that writes the cache costs 1.25 times a normal input token for the five-minute cache and twice for the one-hour one; OpenAI charges a write premium on its newest models and nothing at all on the rest of its catalogue; Google charges no write premium but bills you storage by the hour, which is a rent rather than a transaction and can be the whole cost for a prefix that is barely read. The second is the clock: the cache lives a few minutes by default, up to an hour or more depending on the provider. And one trap that is universal: any change to the prefix, even a stray timestamp at the top, busts the whole thing silently.

Caching pays only above break-even
SituationWhat happensVerdict
Stable prefix reused many times before it changesOne write, then many reads at a tenth of the input price.The intended case, and 80% off the prefix is ordinary.
Prefix reused even twice before it changesA 1.25x write, then a 0.1x read. Anthropic states the threshold outright: caching pays off after one cache read on the five-minute cache.Already a win, by about a third. The break-even is one reuse, not several.
Prefix changes almost every callYou pay to write a cache you rarely read from.A net loss where a write premium exists, and dead weight where it does not.
Long prefix, read rarely, on a provider that charges storageThe rent runs whether anybody reads it or not.The one case where the hourly bill, not the hit count, decides it.

Batch: half price, if no one is waiting

Anything that doesn't need an answer right now can go through a batch API at roughly half price: overnight ticket categorization, backfilling tags on the archive, running an eval suite. You hand the provider a pile of requests and collect the results within a delay window rather than instantly. The catch is exactly that window, batch is useless for anything a user is waiting on, so the discount only ever reaches the async slice of your workload. A mostly-live product can barely touch it; a backfill-heavy one saves a lot. See how much of the bill batch can actually reach:

The interactive version of this example is available when JavaScript loads.

The ceiling is the thing to take away, because it is lower than the headline. The discount is about half, but it only ever applies to the async share, so what you save is half of that share and never half of your bill. Push the slider across its range on these illustrative figures and a mostly-live product saves under a tenth, a mixed one lands near a quarter, and even a workload that is nine-tenths backfill stops at 45%. That is the arithmetic to run before anyone promises a 50% saving from batch, and it is also why batch is worth reaching for early on an eval or backfill pile and worth ignoring entirely on an interactive path.

Response caching, right-sizing, compression: what else moves the bill?

Three more, and each one trades something you may not want to trade. A response cache buys the repeats at the price of a wrong answer served confidently, a smaller model buys every call at the price of a little accuracy, and compression buys a big prompt at the price of the detail it dropped. Worth separating the first of those from the lever two sections up, because both get called caching and they are different machines: a prompt cache stores the processed front of a request so the model can skip re-reading it and still generates a fresh answer, while a response cache stores the finished answer and skips the generation entirely. One saves you input tokens on every call. The other saves you the whole call, and can hand somebody the reply to a question they did not ask.

Three more levers, each with its trade

  • Cache the repeats. If customers keep asking the same thing, serve a stored answer instead of paying for a fresh generation, exact-match for identical questions, or semantic matching for near-duplicates. The trade is a false-hit risk: set the similarity threshold too loose and you'll confidently serve the wrong stored answer, which costs you correctness to save pennies.
  • Right-size the model. Recall the lesson from how LLMs work: a smaller, cheaper model with good context often beats a bigger model working blind. A distilled or quantized model cuts the cost of the calls you make constantly. Choose by cost per correct answer, not by parameter count.
  • Compress the prompt. For a prompt that's genuinely large and repetitive, a compression pass can strip it to a fraction of the tokens before you send it. The trade is lossy: compress too aggressively and you drop the detail the model needed, landing you back on the wrong wall of the context U-curve. Worth it only when the prompt is big enough that the saved tokens outweigh the compression step's own cost.

Put it together: stack the levers

No single lever wins alone; you stack them. But stacking is where the subtlety lives, pull one and you can move another, sometimes the wrong way. Turn levers on and watch not just the total but the split between what you pay the provider and the failure tax the levers can add:

The interactive version of this example is available when JavaScript loads.

Two things show up in that panel that a list of levers cannot. The first is that the savings do not add: routing on its own takes about 23% off this illustrative baseline and caching on its own about 19%, and turning both on lands at 26% rather than anywhere near their sum, because the cache is per-model and routing is exactly what fragments it. The second is sharper. With every other lever already on, switching routing OFF lowers the total, from a 44% saving to a 47% one, because at that point routing is buying a shrinking slice of API spend while still paying the full failure tax of an escalation decision that is sometimes wrong. A lever that pays on its own can stop paying once the others are on, which is the argument for measuring the stack rather than the parts.

The levers fight each other

This is the part experience teaches and checklists don't: the levers interact, sometimes badly. Routing across models fragments your prompt cache, because caches are per-model, so the two savings partly cancel. A loose semantic cache trades cost for correctness, which then shows up as more escalations and a higher cost-per-outcome. Batch discounts are worthless for anything latency-sensitive, so they don't help your interactive path at all. Over-trimming context to cut input cost fires the retry tax. Pull one lever in isolation and you can make another one worse. One pair goes the other way, though, and it is the best opportunity on this page: batch and caching multiply rather than cancel. Anthropic states that the caching multipliers stack with the Batch API discount, and OpenAI publishes cached-input prices inside its batch tier, so an overnight backfill over a stable prefix gets the half-price tier and the tenth-price reads at the same time. If you have async work on a fixed prompt, that is the first thing to go and do. Otherwise: optimise the whole cost-per-resolved-conversation number, and watch for a lever that improves the metric it targets while quietly degrading the one that pays the bills.

Which lever should you pull first?

Faced with a bill that's too high, don't reach for the fanciest lever, reach for the one that matches what's actually driving the cost. Read your token and traffic breakdown first, then pick:

The symptom tells you the lever
What the breakdown showsReach forWatch out for
Output tokens dominate the per-call costCap max_tokens; ask for terse / structured answersA cap so tight it truncates real answers
A big system prompt or RAG payload paid every callTrim context to the top-few factsCutting past the floor → the retry tax
A stable prefix repeated across many callsPrompt-cache the prefixChurning prefixes; per-model fragmentation under routing
Most tickets are easy; a few are hardRoute cheap-first, escalate the hard sliceUnder-escalation letting wrong answers slip
Lots of work no user is waiting onBatch it at half priceAnything latency-sensitive, batch can’t help it
The same questions asked over and overResponse cache (exact, then semantic)A loose threshold serving the wrong stored answer
Spend is high, durable, and predictableEvaluate self-hosting, but do the cheap levers firstThe fully-loaded break-even, not the GPU price

Guardrails against the bill that runs away overnight

Averages aren't the only danger; the scary bills come from the tail. A buggy agent stuck in a loop, a runaway context that keeps growing, a prompt-injection that goads your assistant into calling the model over and over, any of these can generate a shocking bill in an hour. So put hard limits in place: a token ceiling per request, a budget per session, a daily cap, and a detector for loops and ballooning context.

Should you self-host to save money?

At some volume, running your own model on your own GPUs looks cheaper than paying an API per token, and eventually it can be. But the break-even is further out than the raw GPU price suggests, because the GPU is only a fraction of the true cost. Add the engineers to run it, the idle capacity you pay for around the clock, the on-call, the scaling headaches. Fully loaded, self-hosting often costs a multiple of the bare hardware. The honest guidance: stay on the API until your spend clearly and durably clears a real, fully-loaded break-even, and even then, do the smaller optimizations first, because they're free of all that operational weight.

The landscape you’re choosing from

Two shelves matter here: the provider features that give you the discounts, and the gateway/router tooling that helps you pull the levers without hand-rolling everything. The features rhyme across providers even where the field names differ.

Where the levers live
Lever / toolWhat it isReach for it when
Price tiers (per family)Every provider ships three or four tiers, and the cheapest is often a lite variant below the one you have heard of. Output is priced several times input on all of them, and most steeply on the small ones.Right-sizing: match the tier to the task, not to the reputation. Read the current ladder off the pricing page, because the names turn over faster than the shape does.
Batch APIOpenAI Batch, Anthropic Message Batches, Gemini batch mode, ~50% off, results within a delay window (up to ~24h).Async work: categorization, backfills, evals, never the live path.
Prompt cachingAnthropic cache_control breakpoints, OpenAI automatic cached-input pricing, Gemini context caching, cheap reads on a stable prefix, a write premium, a short TTL.A large stable prefix reused above break-even.
Self-hosted gateway (LiteLLM is the live example)A proxy you run in front of every provider. Real budgets that block: past a key’s limit the request fails, at key, user, team and model granularity.Enforcing spend caps one layer out, and measuring cost by route.
Hosted intermediary (OpenRouter)The same unified API plus routing, fallbacks and workspace budgets, but it takes custody of the billing relationship. That is the real difference from a self-hosted proxy, not the feature list.Getting the caps and the routing without running the proxy.
Model routersA classifier that picks cheap against frontier per request. The category is alive and has largely become a gateway feature; the standalone projects people still cite for it have mostly stopped shipping, so check the last release date before you adopt one.Automating the escalation decision a cascade depends on.
Self-host runtime (vLLM, SGLang)High-throughput serving of open-weight models on your own GPUs, with their own prefix-cache reuse. Hugging Face put its own TGI into maintenance mode and now points at these two.Durable high volume, past the fully-loaded break-even.
Service tiers (the lever most teams miss)The same model at several prices on the same provider: standard, a batch or flex tier at about half, and a fast tier at a premium. Note that a fast tier can invalidate your prompt cache, so the tier choice and the caching choice interact.Moving work between tiers without changing the model at all.
Prompt compressorsA pre-pass that drops low-information tokens from a big prompt. Narrower than it looks now: caching beats it on long static prefixes, so it only earns its keep on long DYNAMIC context such as an agent trace or a retrieved set.Large, repetitive, changing prompts, lossily.

The levers, in code

Four minimal shapes cover most of what you'll actually write. The point is the surface, not the syntax.

Cost control, four ways

  • Count before you send. Estimate a prompt's tokens before the call so you can budget, truncate, or reject, with OpenAI's tiktoken locally, where the count is len(enc.encode(prompt)) in Python and .length in the JavaScript port, or with Anthropic's count_tokens endpoint. Counting on the way in is how you catch a ballooning context before it's billed, not after.
  • Route cheap-first with an escalation gate. Send to the cheap model, then decide: if a confidence/verification check passes, return the cheap answer; else re-run on the frontier model. The whole saving lives in that if, if (score < threshold) return await call(frontier, prompt), so calibrate the threshold against real outcomes, not a guess.
  • Batch the async pile. Instead of a call per item in a loop, submit them as one job (client.batches.create(...) / the Message Batches API) and poll for completion. Same tokens, ~half the price: the trade is you collect results from the finished job later, not inline.
  • Cap spend at the gateway. Put every model call behind one proxy that checks a budget first, if (session.spend + estimate > cap) throw new BudgetExceeded(), and only then forwards to the provider. Because the check isn't in the agent's own loop, a looping agent can't skip it.

What belongs on a cost dashboard?

Cost per resolved outcome as the headline, then the split between input, output and reasoning tokens, then cost by route and by model, the cache hit rate, and the p99 of tokens per task. “The bill went down” is not a measurement. Instrument the few numbers that tell you whether a change helped and where the money actually goes, so a saving in one place can't hide a regression in another.

The numbers to put on the dashboard

  • Cost per resolved outcome: the headline. Spend divided by resolved conversations, with retries, abandons, and escalations counted. This is the one a cost project is allowed to celebrate moving.
  • Cost split: input vs output vs reasoning, so you know which lever even applies. Output-heavy says cap length; input-heavy says trim context or cache; a fat reasoning-token share says right-size off the deliberate model.
  • Cost by route and by model, with a cascade or a gateway, break spend down per lane. This is how you catch an under-escalating route or a cache that's fragmented across models.
  • Cache hit rate and effective discount: the read/write ratio and the net saving. A low hit rate or a write-heavy pattern means the prefix isn't stable enough to be worth caching.
  • The p99 of tokens per task, averages hide the tail, and the tail is where the runaway bills live. Watch the 99th percentile of tokens and calls per task, and alert on it.

The seven habits, and the invoice each one prevents

Each row is a habit and the mistake it is bought to prevent
The habitThe mistake it prevents
Put cost per resolved outcome on the dashboard on day one, failures in the numerator, and make every optimisation prove itself against that.Optimising cost per call while cost per outcome rises. The cheaper model that is wrong more often moved the cost; it did not remove it.
Pull the levers in order: cap output, trim context, then route, cache, batch and right-size.Reaching for the heavy lever first. A verbose answer is usually a bigger lever than a long prompt, and self-hosting is the last resort rather than the first idea, because the GPU is a fraction of the real cost.
Tune the escalation threshold against real outcomes, and re-check it as the models and traffic drift.Under-escalating a cascade, so wrong answers reach customers. Priced honestly, that can cost more than always using the frontier.
Cache stable prefixes, and order the prompt volatile-last so the stable head can cache.Caching a prefix that changes every call, which is where the write premium turns a discount into a surcharge.
Keep a floor under the trimming, and watch the retry rate when you lower it.Cutting past the floor, where the model can no longer answer and the retry tax overtakes the tokens you saved.
Enforce per-request, per-session and daily caps at the gateway every call passes through.Putting the budget check inside the agent, where the misbehaving agent is also the thing that skips it.
Track the input, output and reasoning split, cost by route, cache hit rate, and the p99 tokens per task.A win in one place hiding a regression in another, which averages are very good at.

Interview cheat-sheet, intern to principal

What are the two facts about LLM pricing that most surprise people?
First, output tokens cost far more than input, commonly ~4 to 6× (often 5 to 6× on frontier models), so verbose answers are disproportionately expensive and 'be concise' is a cost lever. Second, the bill is per-call × traffic, so a fraction-of-a-cent call becomes a serious monthly number at scale, and in agentic flows one resolved task is several calls with growing context, so cost-per-call understates it. Reasoning models add a third: hidden thinking tokens billed at the output rate.
What metric should you optimize, and why not cost per token?
Cost per resolved outcome (e.g., per resolved support conversation), with a numerator that includes retries, abandoned sessions, and human escalations. Cost per token or per call can fall while cost per outcome rises: the classic trap of switching to a cheaper-but-wronger model. The true cost per outcome is often several times the naive token math.
How does a routing cascade save money, and how can it backfire?
You run a cheap model on the easy majority and escalate only the hard cases to the frontier model, so the blended cost drops. It backfires when you escalate too few for how often the cheap model is wrong: those wrong answers slip to customers and cost retries and human cleanup, which, priced honestly, can exceed just using the frontier for everything. The cascade lives or dies on the escalation decision's calibration, not the price gap.
Prompt caching is “90% off.” What does that miss?
The write penalty. The first call that populates the cache costs more than a normal call, and the cache expires after a short window. So caching only pays if you reuse the stable prefix enough to earn back the write surcharge, below break-even, or with a prefix that changes every call, caching makes you MORE expensive. It also interacts with routing: caches are per-model, so aggressive routing fragments your hit rate.
Why is trimming context not a lever you can ride to zero?
Because cost per outcome is a U, not a slope. Every token you cut lowers the API bill, but cut past what the model needs to answer and it's wrong more often, firing the retry-and-escalation tax, which overtakes the saving. The cheapest prompt is the smallest one that still answers, not the shortest one; there's a trough, and both walls of the U are expensive.
When can batching help, and when can it not?
Batch APIs run ~half price but return results within a delay window (up to ~24h), so they only help work no user is waiting on, categorization, backfills, evals. The saving is capped by your async share: a mostly-live product barely benefits, a backfill-heavy one saves a lot. Batch never helps the interactive path.
What does it mean that “the levers fight each other”? Give an example.
Optimizing one lever can worsen another, so you have to optimize the whole cost-per-outcome number. Example: routing across models fragments the per-model prompt cache, so turning on both saves less than their sum. Others: a loose semantic cache lowers API cost but raises escalations; over-trimming context fires the retry tax; batch does nothing for latency-sensitive work.
Where do you enforce spending guardrails, and why there?
At the gateway every model call passes through, not inside the agent's own code. The failure you're guarding against is the agent misbehaving (a loop, runaway context), and an in-agent check is exactly what a broken agent skips. A hard per-request/per-session/daily ceiling one layer out catches the runaway before it becomes an invoice. Watch the p99 tokens-per-task, not just the average.
When should you self-host instead of using an API to cut cost?
Later than the raw GPU price suggests. The GPU is only a fraction of the fully-loaded cost, add engineers, idle capacity, on-call, and scaling, so self-hosting often costs a multiple of the hardware. Do the cheap optimizations first (output/context discipline, routing, caching, batch), and only move off the API once spend clearly and durably clears a real, fully-loaded break-even.
You need to cut the bill this week. How do you decide which lever to pull?
Read the breakdown first, then match the lever to the symptom. Output-dominated → cap length. Big prompt paid every call → trim context or cache the stable prefix. Easy-majority traffic → route cheap-first with a calibrated escalation. Async pile → batch. Repeated questions → response cache. Don't reach for the fanciest lever; reach for the one that fits what's actually driving the cost.

By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.