In this guide
Context and when this applies
This framework is for teams running LLM features in production on metered APIs, whether from OpenAI, Anthropic, Google or an inference provider serving open-weight models. It assumes you already have real traffic, because optimization against synthetic traffic tends to target the wrong requests.
The common pattern is a bill that grows faster than usage. The cause is rarely one bad decision. It is usually several defaults that compound: a long system prompt resent on every call, tool schemas nobody trimmed, chat history that grows without a cap, a retrieval step that returns more chunks than the model uses, a single large model for every step, and retries that are not counted anywhere.
Provider consoles report spend by model, day and API key. That is billing data, not engineering data. To decide what to change, you need spend broken down by feature, token type and outcome.
Where spend comes from
Every provider prices tokens by type. The exact categories and multipliers differ by provider and model, and change over time, so the formula below uses variables. Look up current values on the OpenAI, Anthropic and Gemini pricing pages.
cost_per_request =
T_in_uncached × p_in
+ T_cache_write × p_cache_write # where the provider charges for cache writes
+ T_cache_read × p_cache_read
+ T_out × p_out # include reasoning tokens if billed as output
+ tool_fees # e.g. server-side search, per-call charges
monthly_cost = Σ over request types:
requests × (1 + retry_rate) × steps_per_request × cost_per_request
Three things in this formula tend to surprise teams:
steps_per_request. An agent or multi-step chain that makes five model calls per user action costs roughly five times a single call, and each step usually resends the growing context.retry_rate. Timeouts, rate-limit errors, malformed structured output and validation failures all trigger retries. If you only log successful calls, this multiplier is invisible.- Output tokens. Output is typically priced higher than input. Verbose answers, unconstrained JSON and long reasoning traces add up even when input is well managed.
A reproducible procedure
Step 1: Attribute spend by feature and token type
Log the usage object returned with every response, tagged with feature, endpoint, tenant, model and prompt version. OpenAI reports cached tokens in the usage details (for example usage.input_tokens_details.cached_tokens, per its prompt caching guide). Anthropic reports input_tokens, cache_creation_input_tokens and cache_read_input_tokens separately, as described in its prompt caching documentation. Retain failed and retried calls in the same table.
With a week of data you can build a simple table:
| Feature | Requests | Avg uncached in | Avg cached in | Avg out | Retry rate | Share of spend |
|---|---|---|---|---|---|---|
| (feature A) | ||||||
| (feature B) |
Sort by share of spend. Optimization effort goes to the top two or three rows.
Step 2: Build an eval set before changing anything
Pick 100 to 300 representative requests per top feature from production, anonymize them and define pass criteria. Every change below is scored against this set. Without it, cost reductions cannot be separated from quality regressions.
Step 3: Test levers in order of risk
Work through levers starting with those least likely to affect output quality.
a. Stable prefixes for provider prompt caching. OpenAI enables prompt caching by default on supported models for prompts above a model-specific minimum length, and a hit requires the prefix to match exactly. Anthropic supports automatic caching and explicit cache_control breakpoints, with a short default TTL and an optional longer TTL. Google documents implicit and explicit context caching for Gemini. In all cases, the engineering work is the same: put static content (instructions, tool definitions, reference documents) first, keep it byte-identical across requests, and move variable content such as timestamps, user IDs and retrieved chunks to the end. Anthropic’s documentation notes that changing tool definitions invalidates everything after them, and that tool JSON key order must stay stable.
Check the effect directly:
cache_hit_rate = T_cache_read / (T_cache_read + T_cache_write + T_in_uncached)
Note that some providers charge a premium for cache writes, so caching a prefix that is rarely reused can cost more than not caching it.
b. Context and output budgets. Measure how many retrieved chunks the answer actually uses, cap chat history (summarize or truncate older turns), remove redundant instructions and unused tool schemas, and set explicit output limits and formats. Each change is scored against the eval set.
c. Batch for work that can wait. Evals, backfills, enrichment, classification of historical data and nightly reports rarely need synchronous responses. OpenAI’s Batch API processes requests asynchronously within a completion window at a discount relative to synchronous endpoints, and Anthropic and Google document equivalent batch offerings on their pricing pages. Model it as:
batch_cost = Σ batchable_requests × cost_per_request × (1 − d_batch)
where d_batch is the documented discount for your provider and model at the time you check.
d. Fix retries and loops. Replace blind retries with retries only on retryable errors, with backoff. Use structured output features or validators that repair rather than regenerate. Cap agent steps, tokens and wall-clock time per run.
e. Routing by task difficulty. Only after the above, test whether some requests can go to a smaller or cheaper model. Common patterns: route by task type (classification and extraction to small models), a lightweight classifier that predicts difficulty, or a cascade that tries a cheap model and escalates when a validator or confidence check fails. Routing adds latency, complexity and a new failure mode, so it needs to show a clear gain on cost per successful task.
f. Response caching. Exact-match caching of full responses is safe for deterministic, non-personalized requests. Semantic caching (returning a stored answer for a similar query) can serve wrong or stale answers and should only be used with explicit similarity thresholds, freshness rules and eval coverage.
Limitations and alternatives
Caching depends on traffic shape. Short cache lifetimes mean low-traffic endpoints may rarely hit the cache. Providers also route requests across machines, so hit rates vary; OpenAI’s guide describes a prompt_cache_key for grouping related requests on some models.
Routing can hide regressions. An aggregate pass rate can stay flat while a specific category of requests degrades. Score routing changes per category, not only overall.
Cheaper per token is not cheaper per task. A smaller model that fails more often triggers retries, escalations or human review. Measure cost per successful task, not cost per request.
Self-hosting is a different trade. For steady, high-volume workloads, serving an open-weight model may be worth comparing, but the comparison has to include utilization, peak capacity, engineering time and on-call. It is a TCO question, not a per-token one.
Provider-specific features create coupling. Prompt caching structure, batch formats and usage fields differ across providers. A thin gateway that normalizes usage accounting keeps optimization work portable.
What to measure
- Cost per successful task per feature, including retries and failed attempts.
- Token mix: uncached input, cache writes, cache reads and output as shares of spend.
- Cache hit rate on cache-eligible endpoints, tracked per prompt version.
- Retry and failure overhead: spend on calls that did not produce an accepted result.
- Steps per task for chains and agents, with p95 tracked against a hard limit.
- Eval pass rate per category, before and after each change.
- p50 and p95 latency, since some savings (batch, cascades) trade latency for cost.
Set alerts on spend per feature per day, not just monthly totals, so a prompt change that doubles context is caught quickly.
Assumptions
- Prices, discounts, cache multipliers, minimum cacheable lengths and TTLs are taken from official provider pages at the time you check; they vary by model and change over time. This article intentionally lists none.
- The usage fields named above are as documented on 2026-11-23 and may differ between API surfaces from the same provider.
- Production traffic is representative enough to build an eval set and attribute spend.
- Quality is defined per feature with explicit pass criteria agreed before optimization starts.
- Optimization targets cost per successful task; changes that lower cost but fail the quality threshold are rejected.
- Any example quantities in your own analysis should come from your logs, not from published benchmarks.
Sources
- OpenAI API pricing — accessed November 23, 2026
- Anthropic Claude API pricing — accessed November 23, 2026
- Gemini Developer API pricing — accessed November 23, 2026
- OpenAI prompt caching guide — accessed November 23, 2026
- Anthropic prompt caching documentation — accessed November 23, 2026
- OpenAI Batch API guide — accessed November 23, 2026