Production Guide 25 of 25

LLM cost and latency: caching, batching, routing, and the gateway

Most LLM bills and slow responses trace back to choices a team controls: which model answers, how much it writes, and how requests are reused, deferred, and measured. Here is where the money and milliseconds go.

  • 10 min read
  • Updated 
  • 8 sources

Key takeaways

  • Output drives both bill and wait. Every current Claude model prices output at five times input, and generation is usually the slowest step, so make the model write less first.
  • Prompt caching pays most on long, repeated prompts. Current models bill cache reads at a tenth of input or less, but only while the prompt’s opening stays identical.
  • Anything nobody is waiting for belongs on a batch path. Anthropic’s Batch API halves token prices, and the discount stacks with prompt caching.
  • Model routing pays off on easy traffic and semantic caching on repetitive traffic; both can quietly return worse answers, so put them behind evals and sampled review.
  • A gateway is where these controls and their measurements live. Instrument every call by team, feature, and model before you optimize anything.
On this page 7 sections

The first feature built on a large language model (LLM) rarely raises cost questions. The tenth does. By then several teams call several providers’ application programming interfaces (APIs), each with its own keys, prompts, and retry logic. Nobody can say which feature drives the invoice, or why some responses take seconds longer than others.

Uber hit this early. In an 11 July 2024 write-up, its Michelangelo platform team described more than 60 LLM use cases across the company, integrated in inconsistent ways that duplicated effort (Uber). Its answer was a central gateway, which by then served close to 30 teams and 16 million queries a month.

This guide covers where cost and latency come from, the levers that move them, and why a gateway is where to pull them.

Where do LLM cost and latency actually come from?

An LLM bill is token arithmetic: tokens sent in, tokens generated, and tokens written to or read from a cache. Output is the expensive side. As of October 2026, every model on Anthropic’s price list charges five times as much per output token as per input token. Claude Haiku 4.5 costs $1 per million input tokens and $5 per million output tokens; Claude Opus 5.5 costs $4 and $20.

Model choice moves the bill more than any prompt tweak: among Anthropic’s current models, input prices span a tenfold range, from $1 for Haiku 4.5 to $10 for Claude Fable 5.1. Token counts are not comparable across models either. Anthropic says the tokenizer in Claude 4.7 and later produces about 30% more tokens from identical text, so compare cost per task, not per token.

Latency has two parts. Time to first token (TTFT) covers queuing plus prefill, the parallel pass over your prompt. Decoding follows, emitting the answer token by token, and it usually dominates. OpenAI’s latency guide offers a blunt heuristic: halving the output can roughly halve the wait, while halving the prompt may buy only a 1–5% improvement.

The exception is long context, where prefill becomes a real share of the wait — the part prompt caching can cut. Reasoning models add thinking tokens before the visible answer; OpenTelemetry’s conventions record them as output tokens used for reasoning, and users wait for them like any other output. The order of attack follows: generate less, use the smallest model that passes your evals, reuse what you have already sent, and defer what nobody is waiting for.

Prompt caching: stop paying twice for the same prompt

During prefill, each attention layer computes key and value vectors for every prompt token, which decoding then reads back. That stored state is the key-value (KV) cache. Providers can keep it for a prompt’s opening tokens and reuse it when a later request begins with exactly the same tokens. The model still processes the new material and writes a fresh answer, so caching changes cost and speed, not the response.

The economics have converged. As of October 2026, writing a prefix to the cache costs 1.25 times the normal input rate at both Anthropic (for its five-minute cache) and OpenAI (on GPT-5.6 and later). Reading it back costs 0.1 times, and less on a few flagship models. In OpenAI’s arithmetic, one write plus nine reads costs 2.15 times the base input price, against 10 times uncached.

Speed improves too, mainly on long prompts. When Anthropic launched caching in 2024, it reported TTFT for a cached 100,000-token book falling from 11.5 to 2.4 seconds. On a 10,000-token prompt the gain was smaller, from 1.6 to 1.1 seconds.

What breaks the cache

Matching is by exact prefix. Change one token near the top and everything after it misses. Usual culprits: a timestamp or user name in the system prompt, reordered tools, retrieved passages placed above stable content, and chat history edited instead of appended. Order every prompt from most stable to least stable:

1. tool definitions               stable for weeks
2. system instructions            stable for weeks
3. examples, policies, reference  stable for hours or days
   ---- cache breakpoint ----
4. conversation so far            append only, never rewrite
   ---- cache breakpoint (advances each turn) ----
5. passages retrieved this turn   change every request
6. the new user message           changes every turn

Three operational details catch teams out:

  • Minimum length. Prefixes below a floor are never cached; OpenAI’s floor is 1,024 tokens on its newer models.
  • Expiry. Anthropic sells five-minute and one-hour lifetimes, the longer one at twice the input rate to write. OpenAI keeps newer entries for at least 30 minutes after last use.
  • Placement. Cached state lives on particular machines. OpenAI warns that traffic above about 15 requests per minute can overflow onto machines that lack your entry; on older models, it recommends a stable prompt_cache_key to steer related requests toward the same machine.

Then measure. Both providers report cached tokens in each response’s usage data, and OpenAI suggests tracking a token hit rate: cached input tokens divided by all input tokens, grouped by user, workspace, or day. A hit rate that falls after a deploy usually means someone changed the top of the prompt.

Batch everything nobody is waiting for

Much LLM work has no one watching it: evaluation runs, classifying a backlog, nightly summaries, enriching records. Batch interfaces take many requests in one submission and return the results asynchronously. Anthropic’s Batch API, for example, charges half the normal rate for both input and output tokens, and the discount stacks with prompt caching.

The trade also runs the other way. As of October 2026, Anthropic sells a research-preview fast mode for some Opus models at double the standard token price (Anthropic). Speed is now bought per request, which makes it a product decision: which features justify premium speed, and which can wait for half price? Our rule of thumb: if the result can wait hours rather than seconds, it belongs on the batch path.

Routing: which model should answer each request?

If most traffic is easy, sending all of it to the largest model wastes money and time; smaller models are usually faster as well as cheaper (OpenAI). Routing sends each request to the cheapest model likely to handle it well, in one of three forms:

  • Static routing by task. Classification and extraction go to a small model, open-ended reasoning to a large one, with evals to confirm the split.
  • Cascades. The cheap model answers first, and the request escalates when that answer fails a check such as schema validation. Cheap when most requests pass, slow when many escalate.
  • Learned routers. A trained model, often a lightweight classifier, predicts per request whether the weaker model will do.

A widely cited public study of learned routers is RouteLLM, from the LMSYS team in July 2024. Routing between GPT-4 Turbo and Mixtral 8x7B, with training data augmented by an LLM judge, their best router kept 95% of GPT-4’s quality on MT Bench, a multi-turn chat benchmark. It sent just 14% of calls to GPT-4.

Massive Multitask Language Understanding (MMLU), a knowledge-heavy test, told a different story. Routers trained only on chat data did barely better than random there, and even with in-domain examples added, the best still sent 54% of calls to the strong model. The lesson: savings depend on how much of your traffic is easy and whether the router has seen data like yours, which only your own logs and evals reveal. Routing also adds a failure mode, because a request misjudged as easy gets a worse answer and nothing in the response says so.

Gateways also route for availability, failing over to another deployment or vendor when a provider returns rate-limit or server errors. Give the fallback model its own evals. And expect a cost and latency bump during failover, because the backup provider holds none of your cached prefixes.

Semantic caching: when is “close enough” safe?

Prompt caching reuses computation; a response cache skips the model entirely. An exact-match cache returns a stored answer only for a byte-identical request, which is safe but rarely hit in conversation. A semantic cache embeds each prompt, finds the most similar stored one, and reuses its answer if similarity clears a threshold. “How do I reset my password?” might then reuse the answer to “I forgot my password, what now?”

The catch is the threshold: researchers from UC Berkeley, the Technical University of Munich, and others found that similarity scores for correct and incorrect hits overlap heavily (Schroeder et al.). One global threshold therefore either serves wrong answers or sits so high that it misses many valid hits. Their system, vCache, learns a threshold per cached prompt. In the paper, accepted at ICLR 2026 (the International Conference on Learning Representations), it reported up to 12.5 times more hits and 26 times fewer errors than static-threshold baselines.

The authors describe semantic caches as effective for single-turn, short-to-medium prompts such as search queries and classification, and we agree. Reserve them for public, repetitive questions whose answers do not depend on the user, the account, or the date. Scope caches per tenant, expire entries when source content changes, and sample hits into your evals: a wrong cached answer is served instantly, confidently, and to everyone who asks something similar.

What does an LLM gateway do?

An LLM gateway is a service between your applications and every model provider. Applications call one internal API, and the gateway handles credentials, routing, retries, fallbacks, quotas, caching, redaction, logging, and cost attribution. It is the natural home for every lever above, and for the measurements that prove each one works.

Uber’s design remains a useful reference (Uber). Its GenAI Gateway, written in Go, copies the request and response format of OpenAI’s API, so teams write OpenAI-style client code whether the model comes from an outside vendor or is hosted by Uber. It adds authentication, metrics for alerting, and audit logs used for cost attribution, security review, and quality evaluation.

A personally identifiable information (PII) redactor swaps names and phone numbers for numbered placeholders before a request reaches an outside vendor, then restores them in the response. Uber is candid that this step “introduces challenges to both latency and result quality.” Note the scale, too: a peak of 25 queries per second (QPS) in July 2024. The value is control, not throughput — one place to enforce policy, see spend, and switch providers without touching every application.

Instrument it in a portable format

Measure before you optimize. OpenTelemetry, the open observability standard, publishes generative AI conventions, still marked as in development as of October 2026 (OpenTelemetry). They define per-call attributes such as gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.usage.cache_read.input_tokens, and gen_ai.usage.reasoning.output_tokens. Tag them with team, feature, model, and route, and “why did the bill go up?” becomes a query instead of a meeting.

Mind the gateway’s own overhead. It adds a network hop, so run it near its callers and stream responses through rather than buffering them. If a gateway forces every provider into one schema, check that it still passes through provider-specific fields such as Anthropic’s cache breakpoints, or the discounts vanish.

Where to start on cost and latency

LeverWhat it savesWhat it risksReach for it when
Shorter outputs, lower reasoning effortLatency and output spendAnswers that lose needed detailAlways; cap and measure
Prompt cachingMost repeated input cost; TTFT on long promptsA rigid prompt layout; write premiumLong stable prefixes, multi-turn chat, agents
Batch processingHalf the token price at AnthropicResults arrive laterEvals, backfills, offline enrichment
Model routingLarge-model spend on easy requestsSilent quality loss when misroutedHigh volume with many easy requests
Semantic cachingEntire model callsWrong answers served with confidencePublic, repetitive, single-turn questions
GatewayDuplicate integrations; invisible spendAn extra hop; a single point of failureMore than a couple of teams or providers
  1. Measure first. Log input, cached, output, and reasoning tokens, TTFT, and total latency per call, tagged by feature and team. Budget per feature, not per company.
  2. Fix the prompt layout. Stable content first, volatile content last, history append-only. Recheck the hit rate after every prompt change.
  3. Make the model write less. Use tight output formats, length caps, and the lowest reasoning effort that passes your evals.
  4. Split traffic by urgency. Interactive requests take the standard path, deferrable work goes to batch, and premium speed goes only where a product owner can justify it.
  5. Route with evidence. Start with static routing per task. Add a learned router only for high, varied volume, and rerun evals whenever a model or price changes.
  6. Gate response caching hard. Use exact-match caching where it helps, and semantic caching only for narrow, non-personalized traffic with sampled review.
  7. Centralize when a second team or provider arrives. Adopt an existing open-source or managed gateway before building one, and confirm it streams and passes provider-specific features through.

Prompt layouts, cache hit rates, and cost dashboards rarely make a demo, yet they decide whether an LLM product is affordable at scale. SurgeX Labs puts cost per completed task on the first dashboard of every production system, next to quality, because a cheaper call that fails more often is not cheaper.

Sources

  1. Navigating the LLM Landscape: Uber’s Innovation with GenAI Gateway (opens in new tab) — Uber Engineering, 2024 uber.com

  2. Pricing (opens in new tab) — Anthropic (Claude Platform documentation), 2026 platform.claude.com

  3. Prompt caching with Claude (opens in new tab) — Anthropic, 2024 claude.com

  4. Prompt caching (opens in new tab) — OpenAI (API documentation), 2026 developers.openai.com

  5. Latency optimization (opens in new tab) — OpenAI (API documentation), 2026 developers.openai.com

  6. RouteLLM: An Open-Source Framework for Cost-Effective LLM Routing (opens in new tab) — LMSYS Org, 2024 lmsys.org

  7. vCache: Verified Semantic Prompt Caching (opens in new tab) — UC Berkeley, Technical University of Munich, et al. (ICLR 2026, arXiv), 2025 arxiv.org

  8. Semantic conventions for generative client AI spans (opens in new tab) — OpenTelemetry (GitHub), 2026 github.com

Where this shows up in our work

Building this? Talk to an engineer.

If this guide maps to a system you’re planning, send a short brief. A senior engineer replies within one business day.