Sub topic 10
Managing token cost and latency
Classic MLOps charges you for infrastructure: GPU hours, instances, storage. An LLM application that calls a hosted model charges you per token and makes you wait for each token to be generated. Both cost and latency now depend on what you put in the prompt and how much the model writes back. This chapter assumes you have read the earlier chapters on prompt versioning and tracing, and that you can read Python and basic JSON logs.
Why cost and latency behave differently
In a classic serving setup, cost is mostly fixed. You pay for a running instance whether it handles ten requests or ten thousand, and per-request latency is roughly constant for a given model and input size.
With a hosted LLM, cost scales with usage. Each request is billed as:
- Input tokens (the prompt, retrieved context, and conversation history), at one price.
- Output tokens (what the model generates), usually at a higher price.
Latency scales with size too. The model reads the whole prompt first, then generates the answer one token at a time. A request that returns 400 tokens takes noticeably longer than one that returns 40, even with identical input.
Both numbers move whenever you edit a prompt, change the retrieval depth, or switch models. They are release-relevant quality attributes, not just infrastructure metrics.
Computing cost per request
The tracing wrapper from the previous chapter already logs input_tokens and output_tokens. Multiply them by your provider's prices to get cost. The prices below are placeholders. Use the current figures from your provider.
from dataclasses import dataclass
@dataclass(frozen=True)
class Pricing:
input_per_million: float
output_per_million: float
def request_cost(pricing: Pricing, input_tokens: int, output_tokens: int) -> float:
return (
input_tokens * pricing.input_per_million
+ output_tokens * pricing.output_per_million
) / 1_000_000
example = Pricing(input_per_million=3.0, output_per_million=15.0)
cost = request_cost(example, input_tokens=1800, output_tokens=250)
print(f"${cost:.5f} per request")
print(f"${cost * 100_000:.2f} per 100,000 requests")The request costs $0.00915, or $915 per 100,000 requests. Output is only 12% of the tokens here but 41% of the cost, because it is priced five times higher. Check both sides of the bill before deciding what to optimize.
Where latency comes from
A single request spends time in several places:
- Work before the model call: retrieval, context assembly, input guardrails.
- Network and queueing at the provider.
- Prefill: the model processes the input tokens. This grows with prompt length.
- Decoding: the model generates output tokens one by one. This grows with output length.
- Work after the call: output validation, parsing, any retry.
Two numbers describe the model's part. Time to first token (TTFT) is how long until the first piece of output arrives. Tokens per second is the generation speed after that. Total time is roughly TTFT plus output tokens divided by tokens per second.
Streaming does not shorten total time, but it lets the user see output at TTFT instead of waiting for the full answer. For chat-style interfaces this is usually the largest perceived-latency win. It does not help when you must validate or parse the complete output before using it.
Measuring: use percentiles, group by version
An average hides the slow tail. Report p50 and p95 latency, and compute cost per prompt version so you can see what a change did. The function below works on the log lines produced by the earlier traced_call. It skips failed calls because they have no token counts. In production you should also track failed calls, since they can still be billed.
import json
import math
from collections import defaultdict
def percentile(values, p):
ordered = sorted(values)
rank = math.ceil(p / 100 * len(ordered))
return ordered[max(rank - 1, 0)]
def summarize(lines, input_price, output_price):
"""Prices are dollars per million tokens."""
groups = defaultdict(list)
for line in lines:
rec = json.loads(line)
if rec["status"] == "ok":
groups[rec["prompt_version"]].append(rec)
out = {}
for version, recs in groups.items():
cost = sum(
r["input_tokens"] * input_price + r["output_tokens"] * output_price
for r in recs
) / 1_000_000
latencies = [r["latency_ms"] for r in recs]
out[version] = {
"requests": len(recs),
"avg_cost": round(cost / len(recs), 6),
"p50_ms": percentile(latencies, 50),
"p95_ms": percentile(latencies, 95),
}
return out
sample = [
json.dumps({"prompt_version": "a1b2c3", "latency_ms": ms, "input_tokens": i,
"output_tokens": o, "status": "ok"})
for ms, i, o in [(820, 1800, 240), (910, 1750, 260), (2400, 1900, 700), (850, 1820, 250)]
]
print(summarize(sample, input_price=3.0, output_price=15.0))In the sample, one request produced 700 output tokens and took 2,400 ms. The p95 shows that outlier while the median stays near 850 ms.
Levers for reducing cost and latency
| Lever | Mainly reduces | Main risk |
|---|---|---|
| Shorter prompts and fewer retrieved chunks | Input cost, prefill time | Missing context lowers answer quality |
| Output caps (`max_tokens`, concise-answer instructions) | Output cost, decode time | Truncated answers, broken JSON |
| Smaller model for easy requests (routing) | Cost and latency | Misrouted hard requests get worse answers |
| Response caching | Cost and latency for repeated inputs | Stale or wrongly shared answers |
| Provider prompt caching for a long shared prefix | Input cost and prefill time | Only helps if the prefix is identical and placed first |
| Streaming | Perceived latency | Cannot validate before display |
| Parallel independent calls | Total latency | Same token cost, more rate-limit pressure |
| Batch endpoints for offline jobs | Cost | Results arrive later |
Every lever that changes what the model sees or which model runs can change output quality. Treat each as a release: run the evaluation set from the evaluation chapter and compare pass rates before and after, not just cost.
Trimming input
Context usually dominates input tokens. Cap the number of retrieved chunks, drop duplicates, and cut conversation history to a fixed window or a summary. Put stable content (system instructions, fixed examples) at the start of the prompt and variable content at the end. That ordering is what lets provider-side prompt caching reuse the shared prefix.
Capping output
Set a hard max_tokens limit as a safety net, and also ask for brevity in the prompt. A hard cap alone cuts the answer mid-sentence. Leave headroom for structured output, because a truncated JSON object fails parsing and triggers a retry that costs more than it saved.
Caching your own responses
An exact-match cache returns a stored answer when the same input arrives again. The key must include the prompt version, since the same user text under a new prompt should produce a new answer.
import hashlib
class ResponseCache:
def __init__(self):
self._store = {}
self.hits = 0
self.misses = 0
def _key(self, version_id: str, user_input: str) -> str:
raw = f"{version_id}|{user_input}"
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def get_or_call(self, version_id, user_input, call):
key = self._key(version_id, user_input)
if key in self._store:
self.hits += 1
return self._store[key]
self.misses += 1
value = call(user_input)
self._store[key] = value
return value
cache = ResponseCache()
fake_model = lambda text: f"summary of: {text}"
cache.get_or_call("a1b2c3", "duplicate charge", fake_model)
cache.get_or_call("a1b2c3", "duplicate charge", fake_model)
cache.get_or_call("d4e5f6", "duplicate charge", fake_model)
print(cache.hits, cache.misses)This prints 1 2: the repeat under the same version hits, and the new version misses. A real cache needs an expiry time and a size limit.
Routing between models
A router sends easy requests (short, well-structured, low stakes) to a cheaper model and hard ones to a larger model. Start with simple rules such as input length or request type. Log the route taken in each trace, and evaluate each route separately, because an average pass rate can hide a failing route.
Common errors
- Optimizing the mean. Users feel the slow tail. Set alerts on p95 latency and on cost per request, not just on averages.
- Ignoring retries. A retry repeats the whole request, input tokens included. A 10% retry rate adds roughly 10% to the bill. Use a bounded number of retries with backoff, and log each attempt.
- Forgetting growing history. In multi-turn chat, every turn resends earlier turns. Cost per turn rises as the conversation grows, so cap or summarize history.
- Cutting cost without re-evaluating. A cheaper model or shorter context may save 60% and quietly drop the pass rate. Gate these changes the same way you gate prompt edits.
- No budget. Set per-request token limits and a daily spend alert. A loop or a long-input bug can otherwise run up a bill before anyone notices. Agent loops are especially exposed, which a later chapter covers.
Exercise
A support-summary feature averages 2,000 input tokens and 150 output tokens per request. Prices are $2 per million input tokens and $10 per million output tokens. Traffic is 50,000 requests per day. (a) What is the daily cost? (b) A teammate proposes cutting retrieved context so input drops to 1,200 tokens. What is the new daily cost, and what must you check before shipping it?
Show answer
(a) Per request: 2,000 × 2 = 4,000 and 150 × 10 = 1,500, totalling 5,500 per million, which is $0.0055. Times 50,000 gives $275 per day. (b) With 1,200 input tokens: 2,400 + 1,500 = 3,900 per million, $0.0039 per request, or $195 per day, a saving of $80 per day. Before shipping, run the golden evaluation set against the shorter-context version and compare pass rates with the current version, since less context may drop information the summaries need.
Exercise
Your p50 latency is 900 ms but users complain about slowness. The trace logs show p95 at 6,500 ms, and the slow requests all have output_tokens above 800. Name two likely causes and one change for each.
Show answer
Cause 1: long generations, because decode time grows with output length. Change: add a concise-answer instruction and a sensible max_tokens cap, then re-run evaluations to confirm answers stay complete. Cause 2: retries or large assembled context on some requests, which add time before and after the model call. Change: log each attempt and the context token count, bound retries, and cap retrieved chunks. Streaming can also improve perceived latency for the long answers.