Slides · Production: cost, serving and observability
Cost and latency optimization
1 / 27
Cost and latency optimization
How to find out where the money and the seconds go, and which lever to pull without breaking quality.
Concept
The bill doubled. What do you do first?
- Every teammate has a remedy: a smaller model, shorter answers, turn the feature off for some customers.
- Nobody has opened the usage report yet.
- Two numbers decide whether an LLM feature survives real traffic: what one request costs and how long the user waits.
By the end you can:
- Instrument a request and find the dominant term.
- Estimate cost and latency from token counts.
- Choose levers and state each one’s risk.
- Say which levers change real latency and which only change how it feels.
Math
Cost per request
cost=nin×pin+nout×pout(+cache terms)| Symbol | Meaning |
|---|---|
| nin | Tokens you send: system prompt, tools, retrieved text, question |
| nout | Tokens the model writes, including reasoning tokens if the provider bills them as output |
| pin, pout | Dollars per million tokens, set by the provider and model |
| cache terms | Extra read and write prices when prompt caching is on (later slides) |
- Providers price the two directions separately. In Anthropic’s batch price table, output costs five times input for every model listed (page viewed 2026-10-23).
- Billing is per token. It is not quadratic in prompt length, even though attention work is.
Source[1] Batch processing
Diagram
Latency has two parts
- Anthropic’s latency guide defines TTFT as the time from sending the prompt to the first generated token.
- Output speed is tokens per second during decode.
Source[2] Reducing latency
Concept
Mental model: a taxi meter and a stopwatch
- The meter charges per token read and, at a higher rate, per token written.
- The stopwatch runs while the driver reads your address (TTFT), then while the route is spoken aloud word by word (output tokens divided by speaking speed).
- That gives three dials: read less, write less, pay less per word.
- Streaming is a fourth thing. It changes what the passenger feels, not the meter and not the stopwatch.
Process
Measure first, per stage
- Tag every request, per stage if there are several (retrieve, rerank, generate): input, output and cached tokens; TTFT and total time; cost; model, prompt version and cache outcome.
- Report percentiles. Track p50 and p95. The slowest 5 percent are the users who complain.
- Find the dominant term: input tokens, output tokens, or the number of model calls.
- Pull one lever, re-measure, compare quality.
Two cautions from provider docs:
- Get a prompt that works well first, then optimize. Squeezing latency too early hides what top quality looks like (Anthropic latency guide).
- Token counts are model-specific. Anthropic notes that Claude 4.7 and later models use a newer tokenizer that produces approximately 30 percent more tokens for the same text, so recount against the model you will run (token counting page, viewed 2026-10-24).
Compare
The shape of the app picks the lever
These pairings are common patterns, not rules. Your traces decide.
| App shape | Often dominated by | First levers to try |
|---|---|---|
| Long-prompt RAG, short answers | Input tokens (cost), TTFT | Fewer or shorter chunks, stable prefix plus caching |
| Chat or report writer | Output tokens | Concise format, output limit, smaller model for easy turns |
| Agent loop | Number of model calls | Fewer calls, parallelize independent calls, cache tool results |
| Nightly eval or backfill | Total cost, not latency | Provider batch API |
A lever aimed at the wrong term does nothing.
Worked example
Worked example: where the cost sits
All prices are illustrative: 2 dollars per million input tokens, 10 dollars per million output tokens. One request: 3,000 input tokens, 400 output tokens.
| Part | Arithmetic | Cost | Share of tokens | Share of cost |
|---|---|---|---|---|
| Input | 1,000,0003,000×2 | $0.006 | 88% | 60% |
| Output | 1,000,000400×10 | $0.004 | 12% | 40% |
| Total | $0.010 | 100% | 100% |
- At 100,000 requests a day that is $1,000 a day.
- Output is 12 percent of the tokens but 40 percent of the cost, so “be concise” is a cost lever.
Worked example
Worked example: where the seconds sit
Assume TTFT 0.6 s and output speed 50 tokens per second, for the same 400-token answer.
total=0.6+50400=0.6+8.0=8.6 s| Change | New total | Time saved | What the user feels |
|---|---|---|---|
| Baseline | 8.6 s | 0 | Wait, then text |
| Route to a smaller model (illustrative: TTFT 0.4 s, 100 tokens/s) | 0.4+100400=4.4 s | 4.2 s | Much quicker finish, quality risk |
| Stream the same answer | 8.6 s | 0 | First word at 0.6 s |
- Generation is almost all of the wait here, so output speed or output length is the lever. Even a prompt that shrank to nothing could save at most the 0.6 s of TTFT.
- Streaming makes the wait feel shorter. The last word still arrives at 8.6 s.
Compare
Every lever has a price
| Lever | Cuts | Quality or freshness risk |
|---|---|---|
| Provider prompt caching | Input cost, TTFT | Output unchanged; needs a stable prefix, short lifetime, write premium |
| Shorter prompts, fewer chunks | Input cost, TTFT | The passage holding the answer may be dropped |
| Concise format, output limit | Output cost, total time | A hard max_tokens cuts mid-sentence |
| Model routing or cascade | Cost, often latency | Hard queries sent to a weak model; router adds time |
| Exact response cache | Cost, latency | Stale answers after a document, prompt or model change |
| Semantic response cache | Cost, latency | Wrong answer for a similar question; cross-tenant leaks |
| Smaller, quantized or distilled model | Cost, latency | Capability loss on the hardest slice |
| Parallelize independent calls | Latency only | More simultaneous load, rate limits |
| Provider batch API | Cost only | Results arrive later; offline work only |
| Streaming | Perceived latency only | Harder to check output before the user sees it |
No lever is free. Two of them, batch API and streaming, do not touch latency the way people assume.
Concept
Provider prompt caching: skip work you already did
The model must read the whole prompt before it writes. If the first 2,500 tokens are identical on every request, the provider can reuse the work for that prefix.
What Anthropic’s docs say (page has no date; viewed 2026-10-23):
- A hit needs an exact, identical prefix, built in the order tools, then system, then messages. A change at one level invalidates that level and everything after it.
- Caching has no effect on the generated output.
- Reads cost a fraction of the base input price; a 5-minute write costs 1.25x and a 1-hour write 2x. The read fraction is 0.1x in general, with lower figures listed for some models.
- The default lifetime is 5 minutes, refreshed each time the entry is used. Prompts shorter than a model’s minimum are processed without caching and without an error.
- Usage fields report cache-read and cache-creation tokens, so you can compute your real hit rate.
Self-hosted engines such as vLLM do the same on their own GPUs, hashing full blocks of a prefix (see the serving lesson).
Diagram
Static first, variable last
A timestamp, user name or request id near the top silently turns every request into a miss.
Source[4] Prompt caching
Worked example
The hit rate decides the saving
Same request as before: 3,000 input tokens, 2,500 of them a stable prefix, 400 output tokens, illustrative prices. Simplified rule: a hit costs 0.1x the prefix price, and every miss rewrites the cache at 1.25x.
prefix cost=1,000,0002,500×2×(h×0.1+(1−h)×1.25)h=hit raterest of input=1,000,000500×2=$0.001output=$0.004| Hit rate h | Prefix cost | Total per request | vs $0.0100 baseline |
|---|---|---|---|
| none (no caching) | $0.00500 | $0.0100 | 0% |
| 100% | $0.00050 | $0.0055 | -45% |
| 70% | $0.002225 | $0.007225 | -27.75% |
| 50% | $0.003375 | $0.008375 | -16.25% |
| 20% | $0.0051 | $0.0101 | +1% (worse) |
- Break-even: 1.25−1.15h=1, so h=1.150.25, about 22 percent. With the 2x one-hour write, break-even is about 53 percent.
- Below break-even, caching costs more than not caching. Watch the cache-read share in the usage fields.
Source[4] Prompt caching
Check yourself
Check: a mid-day deploy
A service caches a prefix made of tool definitions, then a system prompt, then retrieved documents, then the question. At noon a developer adds one new tool definition. What happens to the cache, and what would you watch?
Answer
Per Anthropic’s docs, changing tool definitions (names, descriptions or parameters) invalidates the whole cache, since tools sit first in the prefix. The next requests are misses and write the cache again at the write premium, so cost per request briefly rises above the cached level. You would watch the cache-read share in the usage fields recover, and avoid editing tools often.
Compare
Three caches, three different things
| Aspect | Provider prompt cache | Exact response cache | Semantic response cache |
|---|---|---|---|
| Skips the model? | No, fresh answer each time | Yes | Yes |
| Match rule | Identical prefix | Identical normalized input plus model, prompt version, corpus version, tenant | Past question close enough in embedding space |
| Main saving | Input cost and TTFT | Whole request | Whole request |
| Main risk | Low hit rate | Stale answers after a change | Similar but different question gets the wrong answer; cross-tenant leaks |
| Safeguards | Stable prefix, monitor hit rate | Version everything in the key; TTL | Strict tuned threshold, scope by tenant and permissions, short TTL, invalidate on document change, sample hits |
“Reset my password” and “reset my 2FA device” can be close neighbours with different answers.
Diagram
Semantic cache flow
Compare
Actual or perceived? Who gets the saving?
| Lever | Cuts cost | Cuts real latency | Changes how it feels |
|---|---|---|---|
| Shorter output | Yes | Yes | Yes |
| Prompt caching | Yes, on hits | TTFT only | Yes |
| Parallel independent calls | No | Yes | Yes |
| Streaming | No | No | Yes: first token sooner |
| Provider batch API | Yes | No, it is slower | No: results come later |
- Anthropic’s latency guide says streaming improves perceived responsiveness. It does not shorten generation.
- Anthropic’s batch page says the Message Batches API charges 50 percent of standard prices, most batches finish within an hour, and a batch expires if not done within 24 hours.
max_tokensis a blunt ceiling that can cut an answer mid-sentence. Ask for a shorter format in the prompt first; sentence or paragraph limits work better than word counts (Anthropic latency guide).
Sources[2] Reducing latency[1] Batch processing[4] Prompt caching
Compare
“Batching” means two things
| Aspect | Provider batch API | Continuous batching on your GPUs |
|---|---|---|
| What it is | You submit many requests and collect results later | The server regroups running requests at every decode step |
| Effect on cost | 50 percent discount on Anthropic’s batch API | Lower cost per token through higher throughput per GPU |
| Effect on latency | Slower: asynchronous delivery | Each request may wait longer when the server is busy |
| Fits | Evals, backfills, nightly jobs | Self-hosted serving at scale |
An Anyscale post reports, against naive batching on OPT-13B and one A100 40GB in 2023, up to 23x throughput for vLLM (continuous batching plus its own memory optimizations) and 8x for continuous batching in Ray Serve and text-generation-inference. Treat these as one benchmark, not numbers for your workload.
Sources[1] Batch processing[6] How continuous batching enables 23x throughput in LLM inference while reducing p50 latency
Check yourself
Check: the overnight eval
An eval run sends 40,000 requests at the illustrative $0.010 each (synchronous) and nobody needs results before morning. What does the provider batch API change in cost and in timing?
Answer
Cost: 40,000×$0.010=$400 synchronous. At 50 percent of standard prices that is $200. Timing: the run becomes asynchronous. Anthropic’s page says most batches finish within an hour, but anything not finished within 24 hours expires, so you must handle expired requests. It is a cost lever that costs latency, and it suits this job because nobody is waiting.
Source[1] Batch processing
Worked example
Routing: the arithmetic and its catch
Let the large model cost 1 unit per request and the small one 0.1. Suppose 50 percent of traffic is easy (illustrative). A router has its own cost, here 0.02 units per request.
| Design | Arithmetic | Cost per request | Saving |
|---|---|---|---|
| Always large | 1.00 | 1.00 | 0% |
| Perfect free router | 0.5×0.1+0.5×1 | 0.55 | 45% |
| Router with its own cost | 0.55+0.02 | 0.57 | 43% |
| Cascade (hard requests pay for both) | 0.5×0.1+0.5×(0.1+1) | 0.60 | 40% |
- Real savings are lower still: mistakes in routing are not in this arithmetic.
- The price is quality. Measure the routed system on a labelled set, per query type, before and after.
Diagram
Cache, then route
Check yourself
Check: the slow agent
Traces for an agent task show 12 sequential model calls, each about 0.4 s to first token plus 150 output tokens at 60 tokens per second. Six of the calls do not depend on each other. Find the dominant term and estimate what running those six in parallel saves in time and in cost.
Answer
Per call: 0.4+60150=2.9 s. Twelve in sequence: 12×2.9=34.8 s, so the number of calls dominates. Running the six independent calls together takes one call’s time, giving 12−6+1=7 rounds, 7×2.9=20.3 s, about 42 percent faster. Cost is unchanged because the same tokens are billed. The price is more simultaneous load and rate-limit pressure.
Check yourself
Check: read the stage times
A RAG request takes 6.0 s in total. Stage times: rewrite 0.3 s, retrieve 0.2 s, rerank 0.4 s, generate 5.1 s, of which TTFT is 0.6 s. Output speed is 50 tokens per second. Which stage do you attack, and roughly how many tokens is the answer?
Answer
Generate is 6.05.1=85 percent of the time. Within it, decode takes 5.1−0.6=4.5 s, and 4.5×50=225 output tokens. Shortening the answer is the first lever. Trimming the retrieve or rerank stages could save at most 0.6 s together.
Concept
Common mistakes
- Optimizing before measuring. “Use a smaller model” without a trace is a guess.
- Streaming as a cost fix. It changes feel only.
- Batch API for a chat box. The delay is the price of the discount.
- A timestamp at the top of the prompt. Every request becomes a cache miss.
- Trusting the average after routing or trimming. Check quality per slice, because a small slice can collapse while the average holds.
- Assuming every lever is quality-neutral. Each row of the lever table names a risk.
Summary
Recap
- Cost = nin×pin+nout×pout. Latency = TTFT+output speednout (TTFT = queueing + prefill).
- Measure by stage first. Pull the lever that attacks the dominant term, one at a time.
- Prompt caching needs a stable prefix and a hit rate above break-even. It does not change the output.
- Streaming changes perceived latency only. A batch API trades delay for a discount.
- Response caches and routing save money only if you guard freshness and measure quality per slice.
References
References & Sources (1 of 2)
Batch processing (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/batch-processing
Used for Batch API charges 50 percent of standard prices, most batches finish within an hour, 24-hour expiry; batch price table lists output at five times input.
Reducing latency (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/reduce-latency
Used for TTFT definition, optimize only after a prompt works well, concise-output advice, max_tokens as a blunt cutoff, and streaming as a perceived-responsiveness feature.
Token counting (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/token-counting
Used for Token counts are an estimate and depend on the model's tokenizer: Claude 4.7 and later models use a newer tokenizer that produces approximately 30 percent more tokens for the same text, so recount against the model you will use.
Prompt caching (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/prompt-caching
Used for Exact-prefix matching in the order tools, system, messages; invalidation; read and write price multipliers; 5-minute default lifetime; usage fields; no effect on generated output.
Automatic Prefix Caching (opens in a new tab)
vLLM project2026Documentation
https://docs.vllm.ai/en/stable/design/prefix_caching/
Used for Self-hosted prefix caching reuses KV-cache blocks of a shared prefix to avoid redundant prompt computation, without changing outputs.
References
References & Sources (2 of 2)
Cade Daniel, Chen Shen, Eric Liang, Richard Liaw2023Article
https://www.anyscale.com/blog/continuous-batching-llm-inference
Used for Reported results versus naive batching in one 2023 setting (OPT-13B, one A100 40GB): up to 23x for vLLM, which pairs continuous batching with its own memory optimizations, and 8x for systems using continuous batching without them (Ray Serve, text-generation-inference).
Keys: ← → move, Home End first and last, F full screen.