AI State of the Art
MLOps/LLMOps/33 min
Section 200

Cutting the Bill: Caching, Routing, Batching

Listen as a podcast β†’

The problem: a bill that grows while nobody looks

The price of a model call is quoted in dollars per million tokens. Per unit it is negligible. Multiplied by traffic it is a budget line.

The runaway mechanism is always the same, and there is nothing mysterious about it: you are billed per token, and token counts grow on their own. Conversation history that is never truncated lengthens with every turn. The number of documents pushed into the prompt goes up because someone thought it prudent. The system prompt gains paragraphs with each fix. None of those changes looks like a budget decision, and every one of them is.

This page quotes no prices, on purpose

Model prices move within weeks, and a tariff copied into a course is wrong before it is read. The observed figures, with their dates and sources, live in product and API comparison.

What follows covers only the durable reasoning: what makes a bill grow, which levers exist, and in what order to pull them. Those mechanisms outlive any price list.

The three quantities that set the bill

Before any lever, you need to know what you are paying for. A model-serving bill is the product of three things and nothing else:

cost=NreqΓ—(TinΓ—pin+ToutΓ—pout)\text{cost} = N_{\text{req}} \times \big( T_{\text{in}} \times p_{\text{in}} + T_{\text{out}} \times p_{\text{out}} \big)

where NreqN_{\text{req}} is the number of requests, TinT_{\text{in}} the tokens sent per request, ToutT_{\text{out}} the tokens generated per request, and pinp_{\text{in}} and poutp_{\text{out}} the input and output unit prices of the chosen model. In one sentence: you pay for what you send, what you get back, and which model you picked to do it.

Three things the formula makes obvious:

  • Output is priced higher than input at every provider, by a factor running from two to five depending on the model, the price tables in product and API comparison show it line by line. A chatty answer costs more than a long context at equal token count.
  • A token added to the system prompt is paid on every request, forever. It is the one place where an extra sentence becomes a recurring expense.
  • Reasoning models emit intermediate reasoning tokens, billed as output, that never appear in the displayed answer. See thinking budget.

So there are only four levers: shrink NreqN_{\text{req}}, shrink TinT_{\text{in}}, shrink ToutT_{\text{out}}, or lower pp. Everything below fits one of those four boxes.

Lever 1: do not call at all, response caching

This is the lever on NreqN_{\text{req}}, and the only one that can take a cost to zero.

Exact caching

If a request is identical, character for character, to one already handled, return the stored answer. No call, no cost, negligible latency.

Hit rate depends entirely on the application, and it must be measured rather than assumed: an FAQ service, where users genuinely ask the same questions, gains a great deal; an open-ended assistant, where no two users write the same sentence, gains almost nothing. The number to watch is the cache hit rate, and it takes a day to measure.

Semantic caching

Exact caching misses rephrasings. "What's the weather in Paris?" and "Paris forecast today?" ask the same thing and share almost no words.

Hand-drawn three-column diagram. On the left a user box, in the centre a semantic cache box containing three labels miss, set and hit, on the right an openai box. At the top, the request I forgot my password goes from user to the miss box, which passes it to openai; the answer click on reset password link comes back from openai to set, then to user. At the bottom, a second request How to reset my password goes from user to the hit box, and the answer click on reset password link goes straight back to user without touching openai.
The two wordings, I forgot my password and how to reset my password, share almost no words: exact caching would never connect them. Semantic caching recognises them as equivalent, and the second request is served from the cache with no billed call. The whole mechanism rests on a similarity threshold, and that threshold decides whether it saves money or serves wrong answers.Source : Upstash Blog, Semantic Caching for Speed and Savings

Four steps: turn the request into a numeric vector (an embedding, see text embeddings); measure its similarity to previously seen requests via cosine similarity; above a threshold, return the stored answer; otherwise call the model and store the new pair.

Semantic caching is the only lever here that can give a wrong answer

The other levers degrade latency or prose at worst. This one, badly tuned, returns the answer to a different question. Two very similar requests can have opposite answers: "can I terminate my contract?" and "can I terminate my contract within the first year?" differ by four words.

Too low a threshold produces those confusions; too high a threshold never fires. There is no universal correct value: it is set by measuring, on real traffic, how often an answer is served wrongly. On a service where a wrong answer has consequences (regulatory advice, medical information, a contractual commitment) the right decision is often to have no semantic cache at all.

Provider-side prompt caching

A different mechanism, often confused with the previous one. Here you do not reuse an answer: you avoid reprocessing the start of the prompt. When every request begins with the same system instruction, the same reference document or the same history, the provider retains the computed state for that prefix and does not recompute it.

The order of magnitude, sourced in product and API comparison: a cache read costs 10% of the input rate, with the initial write costing somewhat more than a normal call. A factor of ten on the repeated part of the prompt.

Two method points that decide the real gain:

  • The cache works on a prefix. What is stable therefore belongs at the start of the prompt, and what varies at the end. A service that puts today's date at the top of its system prompt invalidates its cache on every call without noticing.
  • The cache has a short lifetime, minutes by default. On irregular traffic it expires between requests, and you pay for the write without ever getting the read.

Lever 2: call something cheaper, routing

This is the lever on pp.

The idea

Not every request needs the most capable model. A simple factual question and the analysis of a twenty-page contract go down the same pipe and do not have the same requirement. Since the price gap between the small and large model in one family runs into tens, sending the first to the large model is pure waste.

Three ways to route

By estimated complexity. A small classifier reads the request and labels it simple or complex before any call.

By domain. A coding question goes to a coding model, a general one to a generalist. A specialised model is often both smaller and better in its domain.

In cascade. Call the cheap model first; if its answer is unconvincing, escalate to the expensive one. It is the only one of the three that decides after seeing an answer, and therefore the only one not resting on a prediction of difficulty.

NVIDIA architecture diagram. Top left, a User icon sends a Query down over HTTP to a Router Controller. That controller exchanges over HTTP with an NVIDIA Triton Inference Server, itself connected to a Router Model Repository. On the right, a Router Models frame contains three models: Task Router, Complexity Router and Intent Router. At the bottom, the Router Controller dispatches the request to five destinations by label: Few-Shot to Llama3-8B NIM, Summarization to Llama3-70B NIM, Semantic to Llama3-405B NIM, Reasoning to DeepSeek-R1 NIM, and a dotted arrow to a Third-Party LLM API.
Routing wired up concretely. On the right, several small classifier models coexist, one per criterion: task, complexity, intent. The controller reads their verdict and sends the request to an 8, 70 or 405 billion parameter model. Cost per request tracks that size directly. Note that the classifier is itself a model call: it must be small enough that its cost stays negligible against the saving, otherwise the arrangement pays for itself and nothing more.Source : NVIDIA Technical Blog, Deploying the NVIDIA AI Blueprint for Cost-Efficient LLM Routing

Where the reasoning comes from

The idea was formalised in 2023 as FrugalGPT. The authors combine three levers (prompt adaptation, model cascade, and approximation) and measure the trade-off between cost and accuracy.

Three-panel figure. Panel (a) Existing LLM Usage: a Query arrow enters a GPT-4 box and an Answer arrow leaves. Panel (b) Proposed FrugalGPT: two arrows Query and Budget enter a block containing three overlapping circles, Prompt Adaptation, LLM Cascade and LLM Approximation; above the block, labels Zero-shot, Few-shot and CoT, below it labels GPT-J, ChatGPT and GPT-4; an Answer arrow leaves. Panel (c) Performance and cost tradeoffs: a chart with Cost in dollars on the x-axis from 0 to 40 and Accuracy on the y-axis from 0.70 to 0.88; a red FrugalGPT curve climbs very fast then flattens around 0.87 within the first few dollars, while isolated points represent GPT-4, GPT-3J1, ChatGPT, GPT-Neo, Cohere, J1 and GPT-C at higher costs or lower accuracies.
The original figure. The middle panel shows the three levers combined; the right panel explains why cascading pays. The red curve climbs fast then flattens: accuracy reaches its plateau long before the budget is spent, because most requests were already settled by a cheap model. The isolated points are single models used alone, at higher cost or lower accuracy.Source : FrugalGPT paper (Chen, Zaharia and Zou, 2023, figure 1), via ar5iv
What the paper actually claims

The abstract states the arrangement "can match the performance of the best individual LLM (e.g. GPT-4) with up to 98% cost reduction or improve the accuracy over GPT-4 by 4% with the same cost".

Two cautions before quoting that number. "Up to" names the best case observed, not a typical result. And it was measured in 2023, on specific task sets and a generation of models since replaced: the price gap between small and large models, on which the whole argument rests, has moved. What transfers is the shape of the curve (accuracy plateaus before the budget does) not the percentage.

FrugalGPT: How to Use Large Language Models While Reducing Cost and Improving Performance

Deciding whether the small model sufficed

A cascade is only as good as its escalation decision. Three approaches, most to least rigorous:

  • The probability the model assigns its own answer. Available at some providers and not others, and it measures confidence, not correctness, a model can be very confident and wrong.
  • A verifier. A second, small and fast call checks the answer. It adds a cost that belongs in the arithmetic.
  • Simple rules. Abnormally short answer, hedging phrases present, expected format not respected. Cheap, crude, often enough.
Escalation has a cost people forget to count

An escalated request is paid twice: once to the small model, once to the large one. Past a certain escalation rate, the cascade costs more than calling the large model directly. The break-even is computable: with a small model ten times cheaper, the cascade stays ahead while escalation stays well under 100%, but the saving collapses as it rises. Escalation rate is therefore an indicator to track alongside cost, and a router whose distribution nobody measures is not being steered.

Lever 3: send and receive less

This is the lever on TinT_{\text{in}} and ToutT_{\text{out}}. The least spectacular and the most consistent.

Sending less

  • Select documents harder before putting them in the prompt. Going from ten passages to three divides the document share by three, and often improves the answer: a model drowned in weakly relevant passages answers worse. See reranking.
  • Summarise instead of attaching long documents, where the task tolerates it.
  • Prune the system prompt. It is the only text billed on every request; it is also the one nobody rereads once written.
  • Cut the number of examples shown before the question. Every example is text billed on every call. Careful: this changes the score, so it must go through the evaluation set before adoption (see building your own evaluation).
  • Truncate conversation history. This is the leading cause of silent drift: without truncation, the cost of an exchange grows with the square of the turn count, since every turn resends everything before it.

Receiving less

  • Cap generated tokens. A high default cap costs nothing when unreached, but it prevents nothing on the day the model loops.
  • Ask for structured output. A compact JSON object carries the same information as three paragraphs of courtesy, for far fewer tokens. See structured output.
  • Ask for brevity explicitly in the instruction.

Lever 4: pay less for the same work

Batch processing

When a task is not urgent (running an evaluation set, classifying an archive, extracting fields from records) it can go through an asynchronous queue whose results arrive within hours. The announced discount is 50% on both input and output, a figure recorded in product and API comparison.

This is the best effort-to-gain ratio on the page: it requires no change to prompts and no loss of quality, only accepting a delay. See also Mistral's batch API.

Self-hosting

Running an open model on your own machines removes the per-token price and replaces it with an infrastructure cost. The reasoning is that of any rent-versus-own decision: it turns favourable above some volume, and exactly where that point sits depends on hardware prices, the model chosen, and the utilisation achieved.

Total cost of ownership, and utilisation

Cost per token is not total cost. Total cost of ownership (TCO) covers renting or buying the accelerators, operations, monitoring, security updates, and the time of engineers who know how.

The decisive number is utilisation. A rented machine is paid by the hour whether it serves or not. A service whose traffic clusters in office hours leaves its cards idle two thirds of the time, and the real cost per token is then three times the theoretical one. Conversely, batch work that keeps machines full is where self-hosting wins most clearly.

Two non-financial reasons also favour self-hosting: the data does not leave, and the model does not change unless you decide it does. See on-premise deployment.

Geography is not free

Requiring computation to happen in a given region has a published price: a 1.1 multiplier on every token category in the case recorded in product and API comparison, i.e. 10% more.

The interesting part is not the amount but that it is published: a data residency requirement becomes a quantifiable budget line, one you can put in front of whoever writes it into a contract.

The order to act in

The levers are not equal, in effort or in risk. This order maximises gain per unit of effort and minimises the risk of degrading the service:

OrderLeverEffortRisk to quality
1Measure firstLowNone
2Batch the non-urgentLowNone
3Prompt caching, with the prompt reorderedLowNone
4Prune system prompt and historyMediumLow, verify by evaluation
5Routing or cascadingHighReal, must be measured
6Semantic cachingMediumHigh, wrong answers possible
7Self-hostingVery highNone on quality, high in operations

The first three degrade nothing and take days to install. They frequently suffice, and people frequently start at number five.

Measure, or nothing

A cost you do not break down is a cost you do not steer. Five indicators, one dashboard:

  • Cost per request, split between input and output, and by model.
  • Cost per user, to spot abnormal usage.
  • Cache hit rate, exact and prompt caching counted separately. If it is low, the cache is badly placed in the prompt or expiring too fast.
  • Routing distribution. If nearly everything goes to the expensive model, the router is not working.
  • Cost against outcome. Cost per request only means something next to what the request earns or avoids.

And two alerts worth more than the five indicators combined: a budget with threshold notifications, and anomaly detection on volume. A bug that multiplies context size (a document reinserted in a loop, a history never truncated) multiplies the bill by the same factor, and can go unnoticed for weeks. See LLM observability.

Why it matters

This is the chapter where a product description and a best-practice guide read most alike, which makes the anchor all the more useful. Adding a cache, routing to a small model and batching are standard moves, documented by the providers themselves, and they form the common floor of the field.

What can rise above that floor lives in the decision rules: the mechanism that learns the escalation threshold from past escalations instead of fixing it; the one that decides a cache entry's validity from the nature of the question rather than a numeric resemblance; the one that allocates a budget across competing requests by their value; the one that automatically reorders a prompt to maximise the cacheable share. The vocabulary here exists to place a description on that scale, and to ask the one question that settles it: is the threshold given, or computed?

Check your understanding0 / 5

1. Of the levers on this page, which one can make the service return a plainly wrong answer, and why?

2. A service puts today's date at the top of its system prompt and finds the provider's prompt cache never saves it a cent. Why?

3. A cascade calls a small model ten times cheaper first, then escalates to the large one when the answer is unconvincing. Which indicator decides whether it pays?

4. A conversational assistant's bill climbs while traffic stays flat. What is the most likely cause?

5. Where should you start on a production service whose bill is running away?