Skip to content

LLM cost optimization: 9 ways to cut the bill, by effort

LLM cost optimization means paying less per request without losing answer quality. How the bill is built, how to measure it, and nine cuts ranked by effort.

Published
Reading time
16 min read

In short

  • An LLM bill has four token prices: fresh input, cached input, output, and reasoning tokens billed as output. On mid-tier models from Anthropic, OpenAI, and Google in November 2026, output costs five times input.
  • Measure before cutting. Record the cost of every request with its team, feature, and user attached, then sort, because a provider invoice cannot show which feature spent the money.
  • The low-effort cuts change how a request is sent: turn on prompt caching, cap output and reasoning, and move work nobody is waiting for to a batch or flex tier at half price.
  • A smaller model, a shorter context, or a cached answer can lower quality without raising an error, so run the same eval before and after every cut.

LLM cost optimization is the work of paying less for each request without lowering the quality of the answer. A bill is tokens multiplied by prices, so every technique does one of three things: it sends fewer tokens, it pays a lower price for the same tokens, or it avoids the call. This article ranks nine techniques by effort, with the saving a provider or a primary source documents for each, what it risks, and when to skip it.

How an LLM bill is built

A provider bills a request as tokens times a price, and there are four prices. Fresh input, cached input, output, and reasoning tokens are counted separately, and the whole sum is paid again on every retry.

The table shows list prices for one mid-tier model per provider, in US dollars per million tokens, as published in November 2026.

Provider and modelInputCached input, readOutput
Anthropic, Claude Sonnet 5.5$2.00$0.10$10.00
OpenAI, gpt-6.1-sol$2.00$0.10$10.00
Google, Gemini 4 Carbon$2.00, then $4.00 from December 1, 2026$0.10, then $0.20$10.00, then $20.00

The figures come from the pricing pages for the Claude API, the OpenAI API, and the Gemini API. Prices move, as the Gemini row shows, so check them before a number goes into a budget.

Those pages hold the facts that shape every technique below:

  • Output costs five times input on all three models.
  • Cached input is billed at a fraction of the input price, 5% for these three models.
  • Reasoning tokens are billed as output. OpenAI's reasoning guide says so and notes that the response does not show them. Anthropic bills the full thinking the model generated, not the summary it returns. Google lists its output prices as including thinking tokens.
  • Tool definitions are input. Anthropic counts the names, descriptions, and schemas in tools as input tokens on every request and adds a 286-token tool-use system prompt on Claude Sonnet 5.5. Server-side tools carry separate fees, such as $10 per 1,000 web searches at Anthropic and OpenAI.

Retries multiply all of it. A retry that reaches the model bills the whole request again, and so does a response cut off before it is usable. OpenAI warns that a request that hits max_output_tokens while reasoning can bill input and reasoning tokens and return no visible output.

request-cost.txt
cost of one attempt =
    fresh input tokens    x input price
  + cache write tokens    x cache write price
  + cache read tokens     x cache read price
  + (visible output tokens + reasoning tokens) x output price
  + per-call tool fees
 
cost of one request = the sum over every attempt, retries included

Take one agent turn on Claude Sonnet 5.5: 20,000 input tokens, 18,000 of them read from cache, and 1,000 output tokens. The fresh input costs $0.004, the cache read $0.0018, and the output $0.010, which is $0.0158 against $0.05 uncached. With the prefix cached, the 1,000 output tokens are 63% of the bill.

WHAT IS BILLEDTHE LEVER FOR ITOne requestTOKENS × PRICE× ATTEMPTSFresh inputFULL INPUT PRICECached inputDISCOUNTED READOutput5× INPUT PRICEReasoningBILLED AS OUTPUTRetriesWHOLE REQUEST AGAINTrim context and toolsPrompt cachingCap and shape outputLower reasoning effortRetry limits and budgetsWHOLE REQUESTBatch or flex: half priceSmaller model: lower rateCache hit: no call
Each part of a request's cost has its own price and its own lever. The techniques in the bottom row act on the whole request.

Measure before you cut: LLM cost tracking

LLM cost tracking means computing the cost of every request when it is recorded, with the team, feature, and user that caused it attached. Without that, a cut is a guess, because a provider invoice gives totals per account and cannot say which feature spent the money.

A gateway log sees every call, including retries, and an application trace knows which step of which feature made the call. What to record on every request lists the fields and their OpenTelemetry names.

Then read the data four ways:

  • Total spend by route or feature, sorted. Cut at the top of the list. A 50% saving on a route that is 1% of the bill is not worth an afternoon.
  • LLM cost per request by feature, at the median and the 95th percentile. A wide gap points to a few long conversations or runaway agent runs.
  • The share of input tokens read from cache, and the share of output tokens spent on reasoning.
  • Attempts per request. A request that retried twice was billed three times.

Compare cost per request, not price per token. Anthropic notes that Claude 4.7 and later models produce approximately 30% more tokens for the same text than its earlier models.

Before changing anything, run your eval set on the routes you plan to cut and save the scores. LLM evaluation covers how to build that set.

The nine techniques at a glance

The techniques are ordered by effort, lowest first. The first four change how a request is sent. The rest change which model answers, what it reads, or whether it runs at all, so they can change the answer.

TechniqueDocumented savingEffortMain risk
1. Prompt cachingReads at 0.1 times input or less (Anthropic pricing). 41 to 80% lower cost in a 2026 agent studyLowA changed prefix turns reads into writes
2. Cap and shape outputProportional. One output token costs as much as five input tokensLowTruncation, weaker reasoning
3. Batch API50% (OpenAI, Anthropic, and Google docs)Low to mediumResults in up to 24 hours
4. Flex tierBatch rates (OpenAI docs), 50% (Google docs)LowSlow responses, capacity errors
5. Right-size and route20-fold gap between tiers (Anthropic pricing). Over 2 times (RouteLLM paper)MediumA wrong answer with a 200 status
6. Trim context and toolsOver 85% of tool-definition tokens (Anthropic docs)MediumA dropped fact, a cache rewrite
7. Semantic cachingThe whole call on a hit. Up to 68.8% fewer calls (GPT Semantic Cache paper)Medium to highAn answer to a different question
8. Budgets and rate limitsNone per request. Bounds the worst caseMediumBlocking legitimate traffic
9. Self-hostingDepends on utilizationHighPaying for an idle GPU

1. Turn on prompt caching

Prompt caching is the lowest-effort cut. The provider reuses its processing of a prompt prefix it has seen before and bills those tokens at a reduced read rate.

As of November 2026, Anthropic prices cache reads at 0.1 times the input price on most models, 0.05 times on Claude Opus 5.5 and Sonnet 5.5, and 0.025 times on Claude Fable 5.2. A 2026 study of more than 500 agent sessions across OpenAI, Anthropic, and Google measured API costs 41 to 80% lower with caching.

Anthropic charges 1.25 times the input price to write a five-minute cache entry, which one later read pays back. Caching cannot change the answer, since the model still runs on the full prompt. The risk is operational. A timestamp in the system prompt, reordered tool definitions, or a router that moves a session to another key turns reads back into writes, and nothing errors.

Skip it only for prompts below the provider's minimum cacheable length or with no repeated prefix. Prompt caching covers breakpoints, what breaks the cache, and how to measure the hit rate.

2. Cap and shape the output

Output and reasoning tokens carry the highest price on the bill, so the second cut is to generate fewer of them. The controls are a cap, an effort level, a length instruction, and a narrower schema:

  • A hard cap. max_tokens on Anthropic and max_output_tokens in OpenAI's Responses API limit reasoning and visible output together.
  • Reasoning effort. Anthropic's output_config.effort and OpenAI's reasoning.effort set how much the model reasons, and OpenAI's guide says lower effort favors lower token usage.
  • Length. Ask for the level of detail the user needs, or lower OpenAI's text.verbosity setting on supported models.
  • Structure. Request only the fields the application uses, as OpenAI's latency guide recommends.

No provider publishes a percentage, because the saving is proportional to the tokens removed. Track it through reasoning_tokens on OpenAI and thinking_tokens on Anthropic, both under output_tokens_details.

The risks are truncation and weaker answers. A response cut off at the cap is still billed, and lower effort saves nothing if a hard task then fails and runs again. On Anthropic, changing the effort level between requests can invalidate the prompt cache, so pick one level per conversation.

Where long output is the product, as in drafting or code generation, keep the cap as a safety limit and skip the shaping.

3. Send work nobody is waiting for to a batch API

A batch API takes a file of requests, processes them asynchronously, and bills them at half price. OpenAI, Anthropic, and Google each offer a 50% batch API discount on input and output tokens.

ProviderDiscountTurnaroundLimits per batch
OpenAI50%Within 24 hours, often sooner50,000 requests, 200 MB input file
Anthropic50%Most batches under 1 hour, expiry at 24 hours100,000 requests or 256 MB
Google Gemini50%Target of 24 hours2 GB input file

The terms are from OpenAI's Batch API guide, Anthropic's batch processing docs, and Google's Batch API docs, read in November 2026.

OpenAI's batch rate limits are separate from its per-model limits, so a backfill does not compete with live traffic. Anthropic's batch discount stacks with prompt caching, with cache hits on a best-effort basis and typical hit rates of 30 to 98%.

What you give up is latency, with no guarantee shorter than a day, and expired requests must be resubmitted. Use batch for evals, backfills, classification, enrichment, and nightly summaries. Skip it whenever a user or another system waits on the answer.

4. Use a flex tier for slow synchronous work

A flex tier keeps the normal synchronous API and trades speed and availability for a lower price. It suits work that needs its answer in the same code path and can wait minutes for it.

OpenAI's Flex processing is selected with service_tier: "flex". Tokens are priced at Batch API rates, and prompt caching discounts still apply. It is in beta on a limited set of models, and when capacity is short the API returns a 429 Resource Unavailable error, which is not charged.

Google's Flex inference, in preview as of November 2026, offers a 50% reduction with a latency target of 1 to 15 minutes. It can return 503 or 429 at capacity.

Anthropic has no discounted synchronous tier as of November 2026. Its service tiers page lists Priority, which is no longer sold, Standard, and Batch.

The cost is engineering around slowness: longer timeouts, backoff on capacity errors, and a fallback to the standard tier. Skip flex for anything interactive.

5. Right-size the model and route by difficulty

Right-sizing means serving each route with the cheapest model that passes its eval, and routing means making that choice per request. The saving comes from the price gap between model tiers, which is wider than any discount.

As of November 2026, Anthropic lists Claude Haiku 5.5 at $0.10 input and $0.50 output per million tokens for prompts up to 100,000 tokens, Claude Sonnet 5.5 at $2 and $10, and Claude Fable 5.2 at $8 and $40. That is a 20-fold step, then a 4-fold step. OpenAI's list runs from gpt-6-luna at $0.10 and $0.50 to gpt-6.1-sol at $2 and $10.

Per-request routing has support on benchmarks. The RouteLLM paper reports cutting costs by over 2 times in certain cases without lowering response quality.

Do the static step first. Pick a model per route from eval results, and move classification, extraction, and short summaries down a tier wherever the score holds.

The risk is a wrong answer with a 200 status. A classifier also adds latency and cost to every request it judges, and moving a conversation between models discards its prompt cache. Skip per-request routing until you have an eval set and quality metrics per target. LLM routing covers the strategies in the order to adopt them.

6. Trim context and tool definitions

Every token in the context window is billed on every call, and an agent loop resends the window on each turn. Trimming removes the tokens the model does not need.

Start with tool definitions. Anthropic's tool search documentation says a typical five-server MCP setup can consume about 55,000 tokens in definitions before any work is done, and that loading tools on demand typically cuts that by over 85%. MCP code mode goes further by having the model write a short script against tool stubs, so only the result returns to the window.

Then retrieve fewer passages, clear tool results the model has already acted on, and compact long histories at a threshold. Context engineering covers how to budget each part of the window.

Pricing decides where to trim. A token read from cache already costs a fraction of the input price, so start with the uncached tail: fresh tool results and recent history.

The risk is a dropped fact, and compaction rewrites the prefix, which costs a fresh cache write. Trimming is also the one cut that can raise quality, because model accuracy declines as the input grows. Context rot has the research.

7. Add semantic caching where questions repeat

Semantic caching stores responses and returns one when a new prompt is close enough in meaning to a stored prompt. A hit skips the model call, so it saves the whole request.

The saving depends on how much your traffic repeats. The GPT Semantic Cache paper reported up to 68.8% fewer API calls, with more than 97% of hits judged correct, on query categories chosen to repeat. The MeanCache paper puts repeated queries at about 31% of the total.

It is also the technique most likely to return a wrong answer. Two prompts can sit close in embedding space and need different answers, and a cache shared across users can hand one user's answer to another. Every semantic miss also pays for an embedding call and a vector search.

Start with an exact-match cache, which catches retries, reloads, and repeated batch items with no risk of matching a different meaning. Add similarity matching per route, scoped by tenant and user, only where questions repeat and a stored answer is acceptable. Skip it for personalized answers, tool calls, long conversations, and live data. Semantic caching covers thresholds, scoping, and false hits.

8. Set budgets and rate limits as a guard

Budgets and rate limits do not lower the cost of a request. They bound the worst case: a retry loop, an agent that never stops, a leaked key, or a batch job pointed at the wrong model.

Give each team, application, and environment its own key with a dollar budget and a token rate limit, and keep a provider-side spend cap above the sum as a backstop. Bound each call with max_tokens, each agent run with a step limit, and each request with a retry limit. LLM failover covers retry policy, since every retry that reaches a model is a billed attempt.

Coding agents need the same treatment, since they run long sessions from developer machines, outside the application's dashboards. Running Claude Code through a gateway puts each developer on a key with a budget, and Claude Code usage covers what each developer's spend looks like before and after.

A budget cap overshoots, because the cost of a request is known only after the response. A hard cap also blocks legitimate traffic when it trips, so alert below the cap and return an error that clients cannot mistake for a rate limit. Virtual keys covers the key hierarchy and the error design.

9. Self-host an open model, past the break-even

Self-hosting replaces a price per token with a price per GPU-hour, and the GPU bills whether it is busy or idle. It lowers cost only when volume is steady enough to keep the hardware in use and an open model passes your eval for the route.

As a dated example, Lambda's on-demand price list showed one NVIDIA A100 40 GB at $1.99 per GPU-hour on November 16, 2026, which is about $1,430 for a 30-day month. That is the API spend the server has to displace before any staff time. At the $0.50 per million output tokens that Claude Haiku 5.5 and gpt-6-luna charge, $1,430 buys about 2.9 billion output tokens, or roughly 1,100 tokens every second of the month.

The cost case is therefore strongest against larger hosted models on high, steady volume. Data residency and control over latency are separate reasons that do not depend on this arithmetic.

What you take on is the operating work: drivers, capacity, upgrades, access control, and monitoring. vLLM vs Ollama vs llama.cpp covers which engine fits which job, and vLLM vs SGLang covers serving at scale.

Cost attribution and enforcement at the gateway

A gateway is the one component that sees every model call, so it is the natural place to attribute cost and to enforce limits. Bifrost, an open-source AI gateway by Maxim AI, is a worked example of both.

For attribution, its built-in observability logs tokens, cost in dollars, latency, and the number of retries for every request, and the log API filters by cost range. The Prometheus counter bifrost_cost_total is labeled with provider, model, virtual key, team, and customer. An x-bf-dim-* request header adds a dimension of your own, such as a feature name.

spend-by-team.promql
sum by (team_name) (increase(bifrost_cost_total[1d]))

For enforcement, virtual keys carry budgets and rate limits. Each request is checked against the provider config, the key, its team, and its customer, and any exhausted level blocks it. An exhausted budget returns HTTP 402 with the type budget_exceeded, and a rate limit returns 429.

POST /api/governance/virtual-keys
{
  "name": "support-prod",
  "provider_configs": [
    { "provider": "anthropic", "weight": 1.0, "allowed_models": ["claude-sonnet-5-5"], "key_ids": ["*"] }
  ],
  "team_id": "team-support",
  "budgets": [{ "max_limit": 500.0, "reset_duration": "1M" }],
  "rate_limit": {
    "token_max_limit": 200000,
    "token_reset_duration": "1h",
    "request_max_limit": 300,
    "request_reset_duration": "1m"
  },
  "is_active": true
}

The same gateway runs two of the techniques above: semantic caching with an exact-match lookup before the similarity search, and routing rules that can read budget use, so a rule such as budget_used > 85 moves traffic to a cheaper model before a budget runs out.

All of this is in the open-source gateway, which is free under Apache 2.0. The Enterprise tier, which is custom-priced, adds alerting on budget thresholds and real-time synchronization of budget state across the nodes of a cluster. A gateway computes cost from its own price table, so reconcile its totals against the provider invoice every month.

Which cuts to make first

Make the structural cuts first: prompt caching, output caps, and a batch or flex tier for work that can wait. Caching and the discounted tiers leave the answer unchanged, and an output cap puts it at little risk.

The remaining cuts trade against quality. A smaller model, a shorter context, or a stored answer can each be wrong, and none of them raises an error when it is. Quality is the price of cutting too far, and only an eval shows when that price is being paid.

Make one change at a time on the routes at the top of the spend list, run the same eval before and after, and keep the change only if the score holds within its error bars.

Frequently asked questions

What is LLM cost optimization?

LLM cost optimization is the practice of lowering what an application pays for model calls without lowering answer quality. It works on the number of tokens sent and generated, the price per token, and the number of calls. The main techniques are prompt caching, output limits, batch and flex pricing tiers, model routing, context trimming, and semantic caching.

How do you reduce LLM costs without hurting quality?

Start with the cuts that cannot change the answer: turn on prompt caching, and move work nobody is waiting for to a batch API at half price. Then cap output length and reasoning effort. For any change to the model or the context, such as routing to a smaller model, run the same eval before and after and keep the change only if the score holds.

How much is the batch API discount?

OpenAI, Anthropic, and Google each price batch requests at 50% of the standard rate for input and output tokens, as of November 2026. The trade is latency. Results can take up to 24 hours, though Anthropic says most batches finish in under an hour. On Anthropic, the batch discount stacks with prompt caching.

How do you track LLM cost per request?

Compute it when the request is recorded: multiply the fresh input, cached input, and output token counts by their separate prices, and add every retry. Attach the team, feature, user, and model to the record so spend can be grouped. A gateway log covers every call, including retries.

Is self-hosting an LLM cheaper than using an API?

Only at steady, high volume. A GPU is billed per hour whether it is busy or idle, so its cost per token depends on utilization. At Lambda's November 2026 on-demand list price of $1.99 per hour, one A100 GPU costs about $1,430 a month before staff time, and the open model still has to pass your evals.

Sources

  1. 01PricingClaude API docs
  2. 02PricingOpenAI API docs
  3. 03Gemini Developer API pricingGoogle AI Studio docs
  4. 04Batch processingClaude API docs
  5. 05Batch APIOpenAI API docs
  6. 06Batch APIGoogle AI Studio docs
  7. 07Flex processingOpenAI API docs
  8. 08Reasoning modelsOpenAI API docs
  9. 09Steering thinkingClaude API docs
  10. 10Tool search toolClaude API docs
  11. 11Don't Break the Cache: An Evaluation of Prompt Caching for Long-Horizon Agentic TasksarXiv:2601.06007
  12. 12Budget and limitsBifrost docs