Leer en español · Lire en français · Auf Deutsch lesen
Section 12.7 of 12.8 · Advanced · 26 min read
Cost, latency and LLMOps
Video lesson
5 min · narrated, with captionsListen only (audio)
Read the transcript
A feature that works in a demo can still be too slow or too expensive in production. This lesson covers what drives the cost and latency of model calls, and how to operate them.
Using a hosted model is like hiring an interpreter who charges by the word. You pay a small fee for every word you read out to them. And a larger fee for every word they say back. If you repeat the whole conversation each time you speak, the bill climbs quickly. And waiting has two parts: how long before the interpreter starts speaking, and how fast they talk once they start.
Hosted models charge per token. Input tokens are everything sent: the system prompt, tool definitions, retrieved documents, the history and the new message. Output tokens usually cost several times more, because they're generated one at a time. Reasoning models also bill their hidden reasoning as output. In a chat, the whole history is sent again with every turn, so total input grows roughly with the square of the conversation's length. In most assistants, input dominates the bill. So express cost per unit of business value, such as per resolved ticket, and compare it with the alternative, such as a human agent's handling cost.
Where does the time go? First, your own work, such as guards and retrieval: about nought point four seconds here. Then queueing at the provider, and the prefill, about nought point six. Together, that's the time to first token: about one second. Then the decode: two hundred and fifty output tokens at eighty a second, about three point one seconds. Output length is usually the biggest lever on latency. Streaming doesn't finish sooner. But the first words appear after about one second, instead of the whole answer after about four, and users judge speed mostly by when something starts. And every tool call repeats the cycle, with another prefill and decode.
Prompt caching reuses the provider's work on an identical prompt prefix. Cached input is billed at a steep discount, and its prefill is skipped. It's the most effective cost optimisation for assistants with long, stable instructions. But the prefix must be identical, byte for byte. So put the system prompt and tool definitions first, and the content for each request last. A timestamp at the top silently defeats the cache. Semantic caching reuses whole answers for questions with a similar meaning. It suits repetitive questions, such as delivery hours. But similar questions can need different answers. And anything personal must never be served from a shared cache.
Let's cost the support assistant. A typical conversation has four turns. Each call sends a three thousand token static prefix, retrieved context and the growing history: nineteen thousand seven hundred input tokens in all, and eight hundred output. On a large model with no caching, at the section's illustrative prices, that's seven point one cents a conversation. At one point two million conversations a month, about eighty five thousand three hundred dollars. The static prefix is identical in every call, so prompt caching hits almost every time. Cost falls to three point nine cents, forty six per cent less. Add a cascade: seventy per cent of conversations stay on a small model, and thirty per cent escalate. The expected cost is about one point four cents, eighty one per cent below the baseline. But the first turn of an escalated conversation pays for both attempts: about five point six seconds, slower than the baseline. The average improves while the ninety fifth percentile can get worse. And the savings hold only if the small model passes the evaluations, and escalation stays near thirty per cent. At sixty per cent, cost rises to about two point five cents.
LLMOps is the practice of building and running applications on large language models, or LLMs. Its first rule: everything that shapes behaviour is versioned, including prompts, models pinned to dated versions, retrieval settings and evaluation sets. Second, trace every model call, with the model, prompt version, tokens, latency and cost, so a slow or wrong answer can be followed step by step. Recording the text of prompts and replies captures personal data, so it needs retention and access controls. Third, monitor cost like latency. Set budgets and alerts on cost per conversation, and watch for warning signs, such as a prompt change that doubled input tokens, or an agent stuck in a tool loop.
The full section also covers streaming, batching, fallback ladders and a tracing example. Next, in Section twelve point eight, we look at data governance, responsible AI and the EU AI Act. See you there.
What you need to know
- Model calls are billed per input token and per (more expensive) output token; chat history, tool definitions, retrieval and agent loops drive input volume, so cost per conversation grows faster than the number of turns.
- Latency is time to first token (pre-processing, queueing, prefill) plus output tokens divided by generation speed; output length and tool-call round trips are the largest levers, and percentiles matter more than averages.
- Streaming improves perceived latency but complicates proxies, output guardrails, structured outputs and billing.
- Prompt caching discounts and speeds up repeated identical prefixes, so put static content first; semantic caching reuses answers to similar questions and is unsafe for personal or policy-dependent answers.
- Batch interfaces trade latency for large discounts on work that can wait; cascades and routing send most requests to small models but can worsen tail latency.
- Quotas, rate limits, timeouts, back-off and evaluated fallback ladders with a total time budget keep AI features available and affordable.
- LLMOps versions prompts, models, tools, retrieval settings and eval sets together, traces every call (OpenTelemetry's generative AI conventions, still at Development status in October 2026) and monitors cost per unit of work.
Token economics
Hosted models are priced per token, usually quoted per million tokens, with separate prices for input tokens (everything sent: system prompt, tool definitions, retrieved documents, conversation history and the user's message) and output tokens (everything generated). Output tokens typically cost several times more than input tokens, because input is processed in parallel in one pass (the prefill), whereas output is generated one token at a time, each needing its own pass through the model (the decode). Reasoning models (section 12.1) also bill their internal reasoning tokens as output, even when those tokens are not shown, so the same question can cost very different amounts depending on how long the model thinks.
The cost of one call is simply input tokens × input price + output tokens × output price. The architectural surprises lie in what drives the token counts. In a chat, the whole history is normally sent again with every turn, so input grows with each turn and the total over a conversation grows roughly with the square of its length. Tool definitions and a long system prompt are paid for on every call. Retrieval adds thousands of tokens per question, and agents that loop through tools (section 12.4) make several calls per user request. In most production assistants input tokens dominate the bill even though each one is cheaper.
Self-hosting an open-weight model changes the shape of the cost rather than removing it: you pay for GPU time whether or not it is used, so cost per token depends on utilisation and on how many requests the server can process together. The FinOps habits of section 10.8 apply directly: express cost per unit of business value (per conversation, per resolved ticket, per document processed), compare it with the alternative (a human agent's handling cost), and allocate it to features and teams. The prices in this section are illustrative figures chosen for easy arithmetic, not current list prices; real prices differ between providers and have fallen steeply over time.
Illustrative price tiers used in this section
| Tier (illustrative) | Input, per million tokens | Cached input, per million | Output, per million tokens | Typical use |
|---|---|---|---|---|
| Small model | $0.20 | $0.02 | $0.80 | Routing, classification, extraction, simple answers |
| Medium model | $1.00 | $0.10 | $4.00 | Most assistant turns; generation in evals |
| Large model | $3.00 | $0.30 | $15.00 | Hard reasoning, escalations, judging |
Latency: time to first token and generation speed
The latency of a model response has two main parts. Time to first token (TTFT) covers everything before the first output token arrives: your own pre-processing (input guards, retrieval, re-ranking), the network, queueing at the provider, and the prefill, which grows with the number of input tokens. After that, output arrives at the model's generation speed, measured in output tokens per second, so total time is roughly TTFT + output tokens ÷ tokens per second. Reasoning models add a thinking phase before the first visible token, which can take seconds or minutes.
Two consequences follow. First, output length is usually the largest lever on latency: halving a 400-token answer saves more time than any network optimisation. Asking for concise answers, setting a maximum output length and using structured outputs instead of prose all help. Second, every tool call is a full extra round trip with its own prefill and decode, so an agent that makes four tool calls before answering is four times as slow as a single call, whatever the model's speed. Specify and monitor latency as percentiles, not averages (section 2.4): p95 TTFT and p95 total time per turn, because model providers' queueing makes the tail much longer than the median at busy times.
Where the time goes
Streaming
Streaming sends tokens to the client as they are generated, typically as server-sent events over HTTP. It does not make the answer finish sooner, but users judge responsiveness largely by when something starts to happen, so a 4-second answer that starts after 1 second feels much faster than one that appears all at once. Streaming has architectural costs. Every proxy, gateway and load balancer on the path must pass the stream through without buffering and keep long-lived connections open. Output guardrails (section 12.6) can no longer inspect the whole answer before the user sees it, so they either check chunks as they pass (and may have to retract text already shown) or hold back the stream by a sentence or so. Structured outputs that drive actions cannot be acted on until they are complete and validated, so stream the prose to the user and keep the actions for the end. Billing, logging and tracing must cope with streams that the client abandons halfway.
Prompt caching and semantic caching
Prompt caching (also called prefix caching or context caching) reuses the provider's computed internal state for an identical prompt prefix that was processed recently. Cached input tokens are billed at a steep discount (some providers charge around a tenth of the normal input price, others less of a discount, and some charge extra to write the cache) and the prefill for that part is skipped, which also lowers TTFT. It is the single most effective cost optimisation for assistants with long, stable instructions. It only works if the prefix is byte-for-byte identical, so prompt layout becomes an architectural concern: put static content first (system prompt, tool definitions, policies, few-shot examples), then slowly changing content (conversation history), and per-request content last (retrieved documents, the new message). A timestamp or user name at the top of the system prompt silently defeats the cache. Self-hosted inference servers such as vLLM offer the same technique, known as automatic prefix caching.
Semantic caching is different: it stores whole responses keyed by the meaning of the question, using embeddings, and returns a stored answer when a new question is similar enough, skipping the model entirely. It can save a great deal for repetitive, non-personal questions (what are your delivery hours?
), but it is riskier than it looks. Similar questions can need different answers (can I cancel my order?
and cancel my order
), the similarity threshold trades hit rate against wrong answers, and the rules of section 7.6 still apply: the key must include everything that changes the answer, cached answers go stale when policies change, and anything personal must never be served from a shared cache. Measure the false-hit rate on a labelled sample before relying on it. A plain exact-match cache for deterministic calls, such as classification at temperature 0, is simpler and safe.
Batching
Not every model call needs an answer in seconds. Nightly summarisation, tagging a backlog of tickets, generating embeddings for a re-index and running evaluation suites can all wait. Most large providers offer batch interfaces that accept a file of requests and return results asynchronously within a stated window (commonly up to 24 hours) at a substantial discount, often around half the normal price, and with separate, larger rate limits. Architecturally this is the queue-based, asynchronous processing of section 9.3: design the job to be idempotent, track each request's status and handle partial failures.
On self-hosted models, batching happens inside the inference server: continuous batching interleaves the decode steps of many concurrent requests on one GPU, multiplying throughput. The trade-off is the familiar one between throughput and latency: larger batches mean cheaper tokens but slower individual responses, so interactive and offline traffic are often served by separate pools with different settings.
Model selection and cascades for cost
The biggest cost decision is which model handles each task, and the answer is usually the smallest one that passes the evaluation suite for that task
(section 12.5). Prices between small and large models commonly differ by a factor of ten or more, while many tasks (classifying intent, extracting an order number, answering a status question from structured data) do not need a large model. Routing sends each request to a suitable model based on a cheap classification; a model cascade tries a small model first and escalates to a larger one when the output fails validation or the small model signals low confidence (section 12.2). FrugalGPT (Chen, Zaharia and Zou, 2023) showed cascades matching the quality of the strongest model at a fraction of the cost on their benchmarks.
The expected cost of a two-step cascade is the small model's cost plus the escalation rate times the large model's cost. Cascades therefore pay only when most requests stay on the small model, and they have a latency catch: escalated requests pay for both attempts, so the tail gets slower even as the average improves. Up-front routing avoids the double attempt but depends on the router's accuracy. Other token reductions are often cheaper still: trim the system prompt, retrieve fewer but better chunks, summarise older conversation turns, cap output length, lower the reasoning effort of reasoning models for easy tasks, and for a single very high-volume task, consider fine-tuning or distilling a small model.
Quotas, rate limits and fallback ladders
Model providers enforce rate limits: requests per minute, input and output tokens per minute, concurrent requests and sometimes daily caps, signalled by HTTP 429 responses, usually with a Retry-After header. Your own gateway should enforce quotas too, per user, per tenant and per feature, both to share capacity fairly and to defend against the unbounded consumption risk of section 12.6. The resilience patterns of section 9.4 carry over: timeouts on every call, retries with exponential back-off and jitter only for retryable errors, circuit breakers, bulkheads that stop one noisy feature exhausting the shared quota, and graceful degradation (a canned answer and a link to human support beats a spinner).
A fallback ladder lists alternative models and providers to try in order when the first choice fails, is rate-limited or returns an invalid result. Good ladders have a total time budget so that the user is not kept waiting through every rung, cool a rung down for as long as the provider asks after a 429 instead of hammering it, treat an unparseable or schema-invalid reply as a failure that moves to the next rung, and keep prompts portable between models. Every rung must pass the evaluation suite: an untested fallback model is a silent quality drop exactly when the system is under stress. This course's own AI features work this way. ArchitectBot and the test marker try a ladder of hosted open-weight models with a timeout per model and an overall time budget, pause a model after a rate-limit response for the time the provider asks, and fall back to a second provider as a last resort; web searches have daily and monthly caps, and visitors are rate-limited.
LLMOps: versioning, tracing and cost monitoring
LLMOps is the set of practices for building, releasing and operating applications built on large language models, adapting MLOps and DevOps to components whose behaviour is defined by prompts, models and data as much as by code. Its first rule is that everything that shapes behaviour is a versioned artefact: prompt templates (kept in the repository or in a prompt registry with immutable version identifiers), model identifiers pinned to dated versions rather than floating aliases, tool schemas, retrieval settings, the embedding model and index version (changing the embedding model means re-embedding the whole corpus), guardrail rules and the evaluation datasets. A release is a specific combination of these, deployed through the same pipeline, feature flags and canaries as code (section 10.5), with its evaluation results attached.
The second rule is that every model call is traced. Each call becomes a span in the distributed trace of the user's request (section 9.6) carrying the model, the prompt version, input and output token counts, latency, TTFT, cost and outcome, with child spans for retrieval and tool calls, so that a slow or wrong answer can be followed step by step. OpenTelemetry's semantic conventions for generative AI standardise the names, such as gen_ai.operation.name, gen_ai.provider.name, gen_ai.request.model and gen_ai.usage.input_tokens, together with metrics for operation duration and token usage. As of October 2026 these conventions still have Development status and have recently moved to their own repository; names have changed between versions (gen_ai.system became gen_ai.provider.name, for example, and the token metrics are being reorganised), so pin the version your instrumentation emits. Recording the text of prompts and completions is opt-in in the conventions, for good reason: it captures personal data, so it needs the retention and access controls of section 12.8.
The third rule is that cost is monitored like latency. Attribute token spend to feature, tenant, model and prompt version; set budgets with alerts on both absolute spend and unit cost (cost per conversation); and watch for the signatures of trouble: a prompt change that doubled input tokens, an agent stuck in a tool loop, a cache hit rate that collapsed after a deployment, or one account generating a tenth of all traffic. Finally, evaluation runs in the pipeline (section 12.5), so that cost, latency and quality are judged together for every release.
from opentelemetry import trace
tracer = trace.get_tracer("support-assistant")
def ask_model(client, messages, model="medium-2026-05", prompt_version="refund-v14"):
with tracer.start_as_current_span(f"chat {model}") as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.provider.name", "example-provider")
span.set_attribute("gen_ai.request.model", model)
span.set_attribute("app.prompt.version", prompt_version) # our own attribute
reply = client.chat(model=model, messages=messages, max_tokens=300)
span.set_attribute("gen_ai.usage.input_tokens", reply.usage.input_tokens)
span.set_attribute("gen_ai.usage.output_tokens", reply.usage.output_tokens)
return replyWorked example
Worked example: cost and latency per conversation for the support assistant
A typical conversation has 4 turns. Each call sends a 3,000-token static prefix (system prompt, tool definitions, policy extracts), 1,500 tokens of retrieved context, the history so far (250 tokens per earlier turn) and a 50-token message, and generates 200 tokens. Volume: about 40,000 conversations a day (1.2 million a month), as in section 12.2. Prices are the illustrative tiers above.
| Tokens per conversation | Input per turn: 4,550, 4,800, 5,050 and 5,300 tokens (history grows) = 19,700 input tokens; output 4 × 200 = 800 tokens. |
|---|---|
| Baseline: large model, no caching | 19,700 × $3/M + 800 × $15/M = $0.059 + $0.012 = 7.1 cents; × 1.2 million conversations a month = about $85,300. |
| Latency per turn (baseline) | TTFT about 0.9 s + 200 tokens at 60 tokens/s (3.3 s) = about 4.2 s; with streaming, first words after 0.9 s. |
| Step 1: prompt caching | The 3,000-token prefix is identical across all conversations, so it is a cache hit on almost every call: 12,000 tokens at $0.30/M + 7,700 at $3/M + output $0.012 = 3.9 cents (minus 46%), about $46,400 a month. TTFT falls to about 0.6 s. |
| Step 2: cascade | A small router classifies each turn (400 tokens in, 5 out: 0.03 cents per conversation). 70% of conversations are handled by the small model with caching (0.24 cents); 30% escalate after one failed small-model turn (0.05 cents wasted) and continue on the large model (3.9 cents). |
| Expected cost with both | 0.7 × 0.24 + 0.3 × (3.9 + 0.05) + 0.03 ≈ 1.4 cents per conversation (minus 81%), about $16,600 a month. |
| Latency with both | Small-model turns: about 0.3 s + 200 tokens at 150 tokens/s = 1.6 s. But the first turn of an escalated conversation pays both attempts: 1.6 + 3.9 = about 5.6 s, slower than the baseline. The average improves while p95 can get worse. |
| Conditions | The savings hold only if the small model passes the evaluation suite on the 70% it handles and the escalation rate stays near 30%. At 60% escalation the expected cost rises to about 2.5 cents. |
Caching a long static prefix is nearly free and roughly halves the bill; it depends on prompt layout, not on any change in behaviour.
Cascades cut cost most but trade tail latency and quality risk for it, so they need evaluation per slice and monitoring of the escalation rate.
Check your understanding
Why does the cost of a chat conversation grow faster than linearly with the number of turns?
Because the whole history is normally re-sent as input on every turn, so each turn's input is larger than the last and the total grows roughly with the square of the number of turns.
A model has a TTFT of 0.5 s and generates 50 tokens per second. Roughly how long does a 300-token answer take, and when does a streaming user see the first words?
About 0.5 + 300/50 = 6.5 seconds in total; with streaming the first words appear after about 0.5 seconds.
Why can putting the current date at the start of the system prompt increase costs?
Prompt caching only matches an identical prefix; a value that changes at the start makes every prompt different, so nothing after it can be served from the cache.
What must be true of every model in a fallback ladder?
It must have passed the same evaluation suite as the primary model for the tasks it may serve, otherwise failover silently lowers quality.
Sources and further reading
Have a question about this section? ArchitectBot, the course’s AI study assistant, answers from the course first.
Ask: “Our support assistant costs too much per conversation. Where should I look first, and what are the risks of adding a cheaper model in front of the expensive one?”