Cost & Latency Engineering
Capacity math, routing, caching, streaming and the ROI-ordered playbook.
Earlier chapters introduced the pieces: token prices (section 11.7), prompt caching (section 11.6), streaming (section 11.3), routing by difficulty (sections 10.6 and 16.5). This chapter puts them in order. It starts with the arithmetic that says where the money and the time go, then works through the levers from the largest to the smallest, each one gated by the evaluation suite of Chapter 23 so that a saving never arrives as a quiet loss of quality.
Prices change every few months, so every price here is illustrative, and the habit worth keeping is the arithmetic. The experiments are a simulation of routing and cascades, and exact computations of when caching and reserved capacity pay.
28.1Two budgets
Cost and latency share one lever and differ in the rest.
cost = input tokens × input price + output tokens × output price money, summed over traffic
latency = time to first token (reading the input) time, per request
+ output tokens ÷ generation speed (writing the output)Shorter input helps both: fewer tokens to pay for and fewer to read before the first token (section 2.7). After that the levers part. A smaller model cuts cost a lot and latency somewhat. Streaming cuts perceived latency and no cost at all. A long cached prompt with a short answer is expensive to write once and then cheap and fast; a short prompt with a long answer is cheap and slow.
So set two targets per route, managed differently. Latency is a per-request objective, usually the 95th percentile of time to first token and of total time. Cost is an aggregate, such as cost per task or per active user per month. Trades between them, a faster model that costs more or a cheaper one that adds 400 ms, should be decisions, made with both numbers on the screen.
Common take“We need to make it faster and cheaper.”
Sharper take“Those are two budgets. Users complain about time to first token, so I’ll cut input. The bill is mostly output on one route, so I’ll shorten answers there. Each fix is checked against the other budget.”
28.2Capacity math
Estimate before optimizing, so the effort lands where the money is.
Section 1.3 used this arithmetic to decide whether to rent or train. Here it decides what to fix first.
1M requests a day; 3,000 input and 500 output tokens each
mid-tier model at $3 per million input tokens and $15 per million output (illustrative)
input: 1M × 3,000 × $3 ÷ 1M = $9,000 a day
output: 1M × 500 × $15 ÷ 1M = $7,500 a day
total ≈ $16,500 a day, about $500,000 a month
cache the 2,500-token fixed start of the prompt (reads at a tenth of the price):
input: 1M × (2,500 × 0.1 + 500) × $3 ÷ 1M ≈ $2,250 a day was $9,000
route 60% of requests to a small model at a tenth of the price, if evals allow:
output: 1M × 500 × (0.4 × $15 + 0.6 × $1.50) ÷ 1M ≈ $3,450 a day was $7,500
total ≈ $5,700 a day, a third of the start- input tokens
- output tokens
The constants will be out of date within a year. The method will not: state the assumptions out loud, compute the bill by component, and see which component dominates. It is usually one of three things: the same long context sent again on every call, an expensive model answering easy requests, or answers longer than anyone reads.
Common take“The model costs $3 per million tokens, so we’re fine.”
Sharper take“At a million requests a day that’s about half a million dollars a month, mostly the repeated system prompt and the output. Caching and routing take two-thirds off, if the evals hold.”
28.3Routing and cascades
Spend model capability per request, and check before escalating.
The price gap between a provider’s smallest and largest models is often ten to fifty times, so sending each request to the smallest model that can handle it is usually the largest single saving. There are two ways to decide. A router predicts difficulty before answering, with rules or a small classifier, and dispatches. A cascade answers with the small model first, checks the answer, and escalates to the large model only when the check fails.
To compare them I simulated 20,000 requests of varying difficulty, mostly easy. A small model at one-twentieth of the large model’s price is right 97% of the time on the easiest requests and much less on hard ones; the large model degrades far less. The router estimates difficulty with some error. The cascade’s check catches a given share of the small model’s wrong answers and wrongly flags 5% of its right ones.
- router, from all small to all large
- one model for everything
- cascade, labeled with the share of small-model errors its check catches
The router traces a smooth trade: the more traffic it sends to the large model, the closer it gets to the large model’s accuracy and cost. The cascade does better than the trade, because it uses information the router lacks: the actual answer. With a check that catches 80% of the small model’s errors, it beat the large model alone on accuracy, 91.6% against 90.7%, at less than a third of the cost, escalating 24% of requests. That works only where a check exists: a schema, a test, a calculation, a lookup against data (section 19.2). With a weaker check catching 60%, it fell to 87%.
Three cautions. A misrouted hard request is a quality incident disguised as a saving, so evaluate each route and each slice separately (section 23.4). Escalation adds a second call, so the escalated path is slower; that is acceptable when escalation is uncommon. And a small model fine-tuned on the large model’s answers for your task (section 10.9) is the end point of routing: the large model’s quality on the narrow task at the small model’s price.
Common take“We use the best model for everything, to be safe.”
Sharper take“Most of our traffic is easy. Where I can check an answer, a small model answers first and escalates on failure; elsewhere a router decides. Each route is evaluated by slice, so savings don’t hide regressions.”
28.4Caching as architecture
Order every prompt by how often each part changes.
Prompt caching (section 11.6) reuses the processed start of a prompt. Once it matters to the bill, it constrains the design.
- Fixed parts first. System prompt, tool definitions, examples; then content that is stable within a conversation, such as retrieved documents; then the new message. One changing value near the top, a timestamp or a user ID, invalidates everything after it.
- Conversations extend the prefix. History only grows, so each turn can reuse the previous turn’s cache, turning the cost of resending history from quadratic toward linear (section 11.1) and cutting time to first token too.
- Routing splits caches. Each model keeps its own cache, so traffic spread across many models stays cold. Keep prefixes shared within a route.
Whether caching pays depends on traffic. Caches expire, usually after minutes, and many providers charge extra to write one. With one common scheme, where a write costs 1.25 times the normal input price for a five-minute cache or twice for a one-hour cache, and a read costs a tenth, the arithmetic for one prefix receiving requests at random is exact.
- five-minute cache
- one-hour cache
- no caching
Below about three requests an hour for the same prefix, a five-minute cache costs more than no cache, because most writes expire unread. The one-hour cache breaks even at under one request an hour and cuts input cost by about 90% from around ten an hour; the five-minute cache reaches that only at about a hundred an hour. So a busy endpoint should cache aggressively, a long tail of rarely used prompts should not, and the cache hit rate per prompt version belongs on the dashboard (section 24.3), where a deploy that broke the ordering shows up the same day.
Common take“Caching is on, so we’re getting the discount.”
Sharper take“Only if the start of the prompt is identical and the prefix is busy enough to stay warm. I keep changing values at the end, watch the hit rate per prompt version, and turn caching off where traffic is too sparse to pay for the writes.”
28.5Semantic caching and its risks
Reusing an answer for a similar question is a correctness decision.
A prompt cache reuses computation, and the model still answers each request. A semantic cache reuses whole answers: it embeds each incoming question, and if a stored question is close enough, returns the stored answer without calling the model at all. For high-volume, repetitive questions it can remove both cost and latency. It is also a new way to be wrong.
| Risk | Example | Control |
|---|---|---|
| Similar wording, different meaning | “How do I cancel my order?” and “How do I cancel my subscription?”; a negation flips the intent but barely moves the embedding (section 14.1) | A high similarity threshold, tuned on labeled pairs; cache only question types tested for this |
| Personal answers served to others | “What’s my balance?” answered once and replayed | Never cache answers that depend on the user or tenant, or include them in the key |
| Stale answers | A cached policy answer outlives the policy | Short lifetimes; invalidate when source documents change (section 15.8) |
| Cross-tenant leakage | One customer’s cached answer quotes their documents to another | The tenant in every cache key, always |
Treat the similarity threshold like any model setting: measure the false-match rate on real question pairs, include near-miss pairs in the test set, and watch the share of cached answers that users retry.
Common take“A semantic cache will cut our costs by 40% for free.”
Sharper take“It will return some answers to questions that weren’t asked. I cache only generic question types, keep the tenant in the key, set the threshold on labeled pairs, and track retries on cached answers.”
28.6First token and total time
Attack the input for the first, the output for the second.
| Time to first token | Total time |
|---|---|
| Shorter input: fewer tools, fewer and better-chosen retrieved chunks, trimmed history (Chapter 20) | Shorter output: a sensible maximum, instructions to be brief, no restating the question |
| Cache hits, which skip reading the cached part | A faster model or faster serving |
| A smaller model reads faster | Less reasoning, or a lower reasoning setting (section 10.5) |
| Fewer sequential calls before the answer starts | Work done in parallel instead of in sequence |
Streaming (section 11.3) changes what users feel without changing either number: people read at about the speed tokens arrive, so an eight-second answer that starts in 300 ms feels quick. It does not reduce cost or load, and it does not help when a program needs a complete structured object before acting. When users say an assistant is slow while the measured numbers look healthy, check whether streaming survives every proxy between the model and the screen.
Agents add a third term: the number of sequential steps. Ten tool calls at a second each is ten seconds before anything is said. Fewer, task-shaped tools (section 18.2), parallel tool calls where the steps are independent, and a spoken or written progress line while work happens (section 22.7) do more for an agent’s latency than a faster model.
Common take“Latency is the model’s speed.”
Sharper take“Latency is input length, output length and the number of sequential calls. I measure each per route and fix the largest; usually that’s a long prompt or a chain of steps, not the model.”
28.7Batch and service tiers
Work that can wait should be priced as work that can wait.
Not everything is interactive. Embedding a corpus, nightly evaluations, labeling with a judge, generating synthetic data, summarizing yesterday’s tickets: none needs an answer within seconds. The major providers’ batch interfaces accept such work as a file of requests, return results within a day, usually much sooner, and charge half the normal price; at several providers the batch discount also combines with prompt caching. Some providers also sell cheaper, slower tiers for patient interactive work and dearer priority tiers with steadier latency.
Batching for cost at the provider is different from batching inside a server (Chapter 29), where many requests share each pass through the model and are still streamed back individually. Both raise throughput; only the first is a pricing decision you make per job.
Common take“Our evaluation runs use the same API as production.”
Sharper take“Nightly evaluations, judge labeling and corpus embedding go through the batch interface at half price. Only traffic with someone waiting pays full price.”
28.8Reserved capacity, local and edge
Paying for capacity wins only when you keep it busy.
Pay-per-token pricing charges nothing for idle time. Reserved capacity, whether provisioned throughput from a provider or your own GPUs, charges by the hour whether used or not. Its effective price per token depends entirely on utilization.
effective price per million tokens = hourly price ÷ (millions of tokens per hour at full use × utilization)
capacity for 10M tokens an hour at $40 an hour; pay-per-token price $8 per million (illustrative)
at 100% utilization: $4.00 per million
at 50% utilization: $8.00 per million break-even
at 20% utilization: $20.00 per millionReal traffic has daily peaks, and capacity must cover the peak, so average utilization of 30 to 50% is common unless batch work fills the troughs. The usual answer is a hybrid: reserve for the steady base, pay per token for peaks and for rare requests. Reserved capacity also buys things that per-token pricing cannot, such as guaranteed throughput and steadier latency.
Running small models locally, on a laptop through tools such as Ollama and llama.cpp, or on a device, pays in four situations: data that may not leave the machine, steady high volume of an easy task for a small fine-tuned model, offline or poor-network use, and development, where a test suite run a thousand times costs nothing. It does not pay for frontier-level capability, or for bursty traffic that leaves hardware idle. And it means operating an inference service, which is the subject of Chapter 29.
- reserved capacity
- pay per token
Common take“Self-hosting will be cheaper than the API.”
Sharper take“At what utilization? Below the break-even, we pay for idle hardware that the API would have charged nothing for. I’d reserve only the steady base and keep peaks on per-token pricing.”
28.9Cost attribution
Know the cost of every tenant, feature and successful task.
A single monthly bill cannot be managed. Tag every model call with its tenant, feature, route and prompt version (section 24.2), and sum costs along each. Three numbers follow.
- Cost per successful task, not per request. Retries, escalations and failed agent runs are all part of what a success costs.
- Cost per tenant against what that tenant pays. A few heavy customers on a flat plan can turn a profitable product unprofitable; Chapter 31 builds pricing from these numbers.
- Cost per feature, so that a new feature’s spend is visible before it becomes the largest line on the bill.
Then set budgets that act: spending caps per tenant and per user, alerts when a tenant’s daily spend leaves its normal range (section 26.10), and limits on steps and tokens per task (section 19.7).
Common take“AI spend was $80,000 last month.”
Sharper take“Per successful task it was 6 cents on the main route and 90 cents on the agent route. Three tenants account for 40% of it, and one of them is on a plan that doesn’t cover it.”
28.10The playbook, in order of return
Measure, then pull the largest lever first, with the evals watching.
Each lever spends something. Routing risks misroutes; caching constrains prompt design and is fragmented by routing; smaller models trade some quality; batching trades time; reserved capacity trades flexibility for a commitment. The job is to spend the cheapest of these for the largest gain, and the evaluation suite is what tells you whether the price was quality.
Common take“We’ll switch to a cheaper model to cut costs.”
Sharper take“First I measure where the cost is. Usually routing and caching remove most of it without touching quality on the hard requests. Every change goes through the evaluation gate, so a saving can’t be a hidden regression.”
Key takeaways
- Cost and latency are two budgets. Shorter input helps both; most other levers help one.
- Do the capacity math first, by component. The money is usually in repeated context, oversized models on easy requests, or long answers.
- Route each request to the smallest capable model. In simulation, a cascade with a check catching 80% of small-model errors beat the large model alone, 91.6% against 90.7%, at under a third of the cost.
- Order prompts by volatility to cache them. With 1.25× writes and 0.1× reads, a five-minute cache loses money below about three requests an hour per prefix.
- Semantic caching reuses answers, so it can return the wrong one. Keep the tenant in the key and tune the threshold on labeled pairs.
- Time to first token follows the input; total time follows the output and the number of sequential steps. Streaming changes perception, not cost.
- Run anything nobody is waiting for through batch interfaces at half price.
- Reserved capacity pays only above a break-even utilization; reserve the steady base and pay per token for peaks.
- Attribute cost to tenants, features and successful tasks, and pull levers in order of return, with the evaluation gate on every step.
Check your understanding
-
Prompt caching is enabled, but input costs barely moved and the cache hit rate is 15%. Name the two most likely causes, how to tell them apart, and the fix for each.
Answer outline
Either something that changes per request sits near the start of the prompt, such as a timestamp, a request ID or per-user text in the system prompt, so every prefix is new; or traffic per prefix is too sparse for the cache to stay warm, for example because many prompt variants or models split it. Tell them apart by looking at the hit rate per prompt version and per route alongside requests per hour per prefix: a busy prefix with a low hit rate means the prefix changes; a rare one means sparsity. Fix the first by moving changing values to the end. Fix the second by consolidating prompt variants, keeping a route on one model, using a longer cache lifetime where traffic is moderate, or turning caching off where writes outnumber reads (section 28.4).
-
After routing 70% of traffic to a small model, costs fell 50%, overall quality was flat, and complaints rose in one customer segment. Diagnose and fix without abandoning routing.
Answer outline
The router misjudges difficulty for that segment: its requests look easy but are not, perhaps because of domain vocabulary or longer documents. The overall average hid it because the segment is small (section 23.4). Add the segment as a slice in the routing evaluation, measure the router’s accuracy and the small model’s quality on it, and either route that segment to the large model, retrain the router with examples from it, or switch that route to a cascade if its answers can be checked. Track complaints, retries and escalations by segment and route from now on.
-
Your team proposes buying reserved capacity to cut costs on a product whose traffic is ten times higher at midday than overnight. What do you need to know, and what would you propose?
Answer outline
Compute the effective price at realistic utilization: capacity sized for the midday peak sits mostly idle overnight, so average utilization may be well under the break-even (section 28.8). Ask what work could fill the troughs, such as evaluations, batch labeling and embedding, and whether the reservation guarantees latency that the product needs. Propose reserving capacity for the steady overnight base plus whatever batch work can fill it, and paying per token for the peak, then re-run the numbers monthly as traffic grows.
Further reading
- Chip Huyen, AI Engineering, chapter 9: inference optimization, including caching, batching and the trade-offs between cost and latency.
- Shreya Shankar and Hamel Husain, Evals for AI Engineers (O’Reilly, 2026): the chapter on cost optimization, which treats every saving as a change to evaluate.
- Lingjiao Chen, Matei Zaharia and James Zou, “FrugalGPT” (2023): an early systematic study of model cascades.
- Your providers’ pricing pages on prompt caching, batch processing and service tiers; the multipliers change, and the arithmetic in this chapter needs current ones.