Slides · Production: cost, serving and observability

Cost and latency optimization

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:

  1. Instrument a request and find the dominant term.
  2. Estimate cost and latency from token counts.
  3. Choose levers and state each one’s risk.
  4. Say which levers change real latency and which only change how it feels.

Math

Cost per request

cost=nin×pin+nout×pout  (+  cache terms)\text{cost} = n_{\text{in}} \times p_{\text{in}} + n_{\text{out}} \times p_{\text{out}} \;(+\; \text{cache terms})
SymbolMeaning
ninn_{\text{in}}Tokens you send: system prompt, tools, retrieved text, question
noutn_{\text{out}}Tokens the model writes, including reasoning tokens if the provider bills them as output
pinp_{\text{in}}, poutp_{\text{out}}Dollars per million tokens, set by the provider and model
cache termsExtra 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.

Source1 Batch processing

Diagram

Latency has two parts

Diagram: Reading downward, a request waits in a queue, the model reads the whole prompt (prefill), and the first token appears.

Request sent

Queueing

Prefill: read the whole prompt

First token appears (TTFT)

Decode: one token at a time

Last token: done

Diagram summary: Reading downward, a request waits in a queue, the model reads the whole prompt (prefill), and the first token appears. Everything up to that point is time to first token. After that, decode writes the rest one token at a time.
total latency=TTFT (queueing+prefill)+noutoutput speed\text{total latency} = \text{TTFT}\ (\text{queueing} + \text{prefill}) + \frac{n_{\text{out}}}{\text{output speed}}
  • 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.

Source2 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

  1. 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.
  2. Report percentiles. Track p50 and p95. The slowest 5 percent are the users who complain.
  3. Find the dominant term: input tokens, output tokens, or the number of model calls.
  4. 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).

Sources2 Reducing latency3 Token counting

Compare

The shape of the app picks the lever

These pairings are common patterns, not rules. Your traces decide.

App shapeOften dominated byFirst levers to try
Long-prompt RAG, short answersInput tokens (cost), TTFTFewer or shorter chunks, stable prefix plus caching
Chat or report writerOutput tokensConcise format, output limit, smaller model for easy turns
Agent loopNumber of model callsFewer calls, parallelize independent calls, cache tool results
Nightly eval or backfillTotal cost, not latencyProvider 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.

PartArithmeticCostShare of tokensShare of cost
Input3,000×21,000,000\dfrac{3{,}000 \times 2}{1{,}000{,}000}$0.00688%60%
Output400×101,000,000\dfrac{400 \times 10}{1{,}000{,}000}$0.00412%40%
Total$0.010100%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+40050=0.6+8.0=8.6 s\text{total} = 0.6 + \frac{400}{50} = 0.6 + 8.0 = 8.6\ \text{s}
ChangeNew totalTime savedWhat the user feels
Baseline8.6 s0Wait, then text
Route to a smaller model (illustrative: TTFT 0.4 s, 100 tokens/s)0.4+400100=4.4 s0.4 + \dfrac{400}{100} = 4.4\ \text{s}4.2 sMuch quicker finish, quality risk
Stream the same answer8.6 s0First 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

LeverCutsQuality or freshness risk
Provider prompt cachingInput cost, TTFTOutput unchanged; needs a stable prefix, short lifetime, write premium
Shorter prompts, fewer chunksInput cost, TTFTThe passage holding the answer may be dropped
Concise format, output limitOutput cost, total timeA hard max_tokens cuts mid-sentence
Model routing or cascadeCost, often latencyHard queries sent to a weak model; router adds time
Exact response cacheCost, latencyStale answers after a document, prompt or model change
Semantic response cacheCost, latencyWrong answer for a similar question; cross-tenant leaks
Smaller, quantized or distilled modelCost, latencyCapability loss on the hardest slice
Parallelize independent callsLatency onlyMore simultaneous load, rate limits
Provider batch APICost onlyResults arrive later; offline work only
StreamingPerceived latency onlyHarder 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).

Sources4 Prompt caching5 Automatic Prefix Caching

Diagram

Static first, variable last

Diagram: Each column reads top to bottom as the prompt is assembled.

Good: prefix reused

System prompt

Tools, documents

Timestamp, user name

Question

Bad: always a miss

Timestamp, user name

System prompt

Tools, documents

Question

Diagram summary: Each column reads top to bottom as the prompt is assembled. In the bad layout a changing timestamp comes first, so no later part can match a stored prefix. In the good layout the unchanging parts come first and the changing parts last, so the long stable prefix can hit the cache.

A timestamp, user name or request id near the top silently turns every request into a miss.

Source4 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=2,500×21,000,000×(h×0.1+(1−h)×1.25)h=hit rate\text{prefix cost} = \frac{2{,}500 \times 2}{1{,}000{,}000} \times \bigl(h \times 0.1 + (1 - h) \times 1.25\bigr) \qquad h = \text{hit rate}rest of input=500×21,000,000=$0.001output=$0.004\text{rest of input} = \frac{500 \times 2}{1{,}000{,}000} = \$0.001 \qquad \text{output} = \$0.004
Hit rate hPrefix costTotal per requestvs $0.0100 baseline
none (no caching)$0.00500$0.01000%
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=11.25 - 1.15h = 1, so h=0.251.15h = \dfrac{0.25}{1.15}, 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.

Source4 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

AspectProvider prompt cacheExact response cacheSemantic response cache
Skips the model?No, fresh answer each timeYesYes
Match ruleIdentical prefixIdentical normalized input plus model, prompt version, corpus version, tenantPast question close enough in embedding space
Main savingInput cost and TTFTWhole requestWhole request
Main riskLow hit rateStale answers after a changeSimilar but different question gets the wrong answer; cross-tenant leaks
SafeguardsStable prefix, monitor hit rateVersion everything in the key; TTLStrict 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

Diagram: The question is embedded and compared with stored questions.

yes

no

New question

Embed it

Close enough, same tenant and permissions?

Return stored answer

Call the model

Store with a TTL

Sample hits for review

Diagram summary: The question is embedded and compared with stored questions. Only a close match from the same tenant and permission scope returns a stored answer, and a sample of those hits goes to review. Anything else calls the model, and the new answer is stored with a short lifetime.

Compare

Actual or perceived? Who gets the saving?

LeverCuts costCuts real latencyChanges how it feels
Shorter outputYesYesYes
Prompt cachingYes, on hitsTTFT onlyYes
Parallel independent callsNoYesYes
StreamingNoNoYes: first token sooner
Provider batch APIYesNo, it is slowerNo: 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_tokens is 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).

Sources2 Reducing latency1 Batch processing4 Prompt caching

Compare

“Batching” means two things

AspectProvider batch APIContinuous batching on your GPUs
What it isYou submit many requests and collect results laterThe server regroups running requests at every decode step
Effect on cost50 percent discount on Anthropic’s batch APILower cost per token through higher throughput per GPU
Effect on latencySlower: asynchronous deliveryEach request may wait longer when the server is busy
FitsEvals, backfills, nightly jobsSelf-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.

Sources1 Batch processing6 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=$40040{,}000 \times \$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.

Source1 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.

DesignArithmeticCost per requestSaving
Always large1.001.000%
Perfect free router0.5×0.1+0.5×10.5 \times 0.1 + 0.5 \times 10.5545%
Router with its own cost0.55+0.020.55 + 0.020.5743%
Cascade (hard requests pay for both)0.5×0.1+0.5×(0.1+1)0.5 \times 0.1 + 0.5 \times (0.1 + 1)0.6040%
  • 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

Diagram: A request first checks the response cache and returns at once on a hit.

yes

no

simple

complex

Incoming query

Cache hit?

Return cached answer

Classify difficulty

Small, fast model

Large model

Store, then return

Diagram summary: A request first checks the response cache and returns at once on a hit. On a miss it is classified, sent to a small or large model, and the answer is stored before it is returned.

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+15060=2.9 s0.4 + \dfrac{150}{60} = 2.9\ \text{s}. Twelve in sequence: 12×2.9=34.8 s12 \times 2.9 = 34.8\ \text{s}, so the number of calls dominates. Running the six independent calls together takes one call’s time, giving 12−6+1=712 - 6 + 1 = 7 rounds, 7×2.9=20.3 s7 \times 2.9 = 20.3\ \text{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 5.16.0=85\dfrac{5.1}{6.0} = 85 percent of the time. Within it, decode takes 5.1−0.6=4.5 s5.1 - 0.6 = 4.5\ \text{s}, and 4.5×50=2254.5 \times 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×poutn_{\text{in}} \times p_{\text{in}} + n_{\text{out}} \times p_{\text{out}}. Latency = TTFT+noutoutput speed\text{TTFT} + \dfrac{n_{\text{out}}}{\text{output speed}} (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)

  1. Batch processing (opens in a new tab)

    Anthropic2026Documentation

    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.

  2. Reducing latency (opens in a new tab)

    Anthropic2026Documentation

    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.

  3. Token counting (opens in a new tab)

    Anthropic2026Documentation

    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.

  4. Prompt caching (opens in a new tab)

    Anthropic2026Documentation

    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.

  5. Automatic Prefix Caching (opens in a new tab)

    vLLM project2026Documentation

    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)

  1. How continuous batching enables 23x throughput in LLM inference while reducing p50 latency (opens in a new tab)

    Cade Daniel, Chen Shen, Eric Liang, Richard Liaw2023Article

    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).