AI Observability, Latency & Cost Optimization

After completing this chapter you will be able to:
- Define and instrument the core latency metrics that govern user experience in LLM systems: TTFT, TPOT/ITL, end-to-end latency, and p50/p95/p99 percentiles.
- Design an observability stack using OpenTelemetry that captures traces, metrics, logs, token usage, and cost attribution for every request.
- Implement semantic caching, prompt caching, and model routing to cut inference cost and latency without sacrificing quality.
- Detect embedding drift and data drift in production RAG and agent pipelines using statistical and semantic methods.
- Apply architectural patterns (batching, quantization, KV-cache sharing, disaggregated prefill/decode, autoscaling) that keep high-concurrency LLM services reliable and cost-effective.
- Build dashboards, alerts, and SLOs that experienced teams at scale actually use.
- Avoid the most common production failure modes that turn promising prototypes into expensive, slow, or unreliable systems.
Prerequisites
Who this is for
- Expats, students, career changers, junior professionals, and self-learners who already know the basics of building an LLM app (calling an API, simple RAG, or an agent loop) and now need to run it in production.
- Engineers who have shipped a prototype and are suddenly facing latency spikes, unpredictable bills, or silent quality degradation.
Required knowledge
- Comfortable reading Python (or equivalent) and REST/gRPC concepts.
- Basic understanding of tokens, embeddings, and what an LLM inference call does.
- Familiarity with containers, HTTP, and simple monitoring (logs or Prometheus-level metrics) is helpful but not required; every concept is introduced from first principles.
Estimated reading time
90–120 minutes for a careful first pass. Plan additional time for the exercises and code experiments.
Difficulty
Intermediate. The material starts from zero on observability and cost concepts, then moves into production architecture. No prior SRE or MLOps experience is assumed.
Why This Matters
LLM applications behave differently from classic web services. A single user request can trigger multiple model calls, retrieval steps, tool invocations, and guardrails. Latency compounds. Cost is metered per token. Quality can silently drift when the distribution of user prompts changes. In high-concurrency environments these effects become first-order product and business risks. community.ibm
Industry teams treat LLM serving with the same rigor Site Reliability Engineering applies to any critical service: they define SLIs (latency, availability, output quality), set SLOs, implement circuit breakers and fallbacks, and pair autoscaling with queue-based load regulation. Observability for LLMs therefore includes p95/p99 latency, token counts per request, cost per call, cache hit rates, and semantic drift monitoring. medium
Companies running production inference at scale—whether using managed APIs or self-hosted stacks such as vLLM—rely on these practices to keep unit economics viable and user experience predictable. Without them, teams discover too late that GPU spend has ballooned, p99 latency has made the product unusable, or embeddings have drifted so far that retrieval quality collapsed. This chapter gives you the mental models, metrics, and patterns that turn those risks into controllable engineering problems.
First Principles
What “observability” means for an LLM application
Observability is the ability to understand the internal state of a system from its external outputs—logs, metrics, and traces. For a classic HTTP API you care about request rate, error rate, and latency. For an LLM application you must also answer:
- How many input and output tokens did this request consume, and what did that cost?
- How long did the user wait before the first token appeared (TTFT)?
- How fast did subsequent tokens arrive (TPOT / ITL)?
- Which stage of the pipeline (retrieval, prompt construction, model inference, tool call, guardrail) dominated latency or cost?
- Has the distribution of incoming prompts or embeddings shifted so that quality is degrading even though the service is “up”?
If you cannot answer these questions per request, per feature, and per model, you do not yet have production observability. 21medien
Why LLM latency is multi-modal
Classic services often report a single latency number. LLM inference has distinct phases with different physics:
- Queue / network time — waiting for a free worker or crossing the network.
- Prefill — the model processes the entire prompt and builds the key-value (KV) cache. This dominates Time to First Token.
- Decode — the model generates one token at a time, each step attending over the growing context. This determines Time per Output Token.
The clean decomposition used across the industry is:
TTFT and TPOT move independently. Optimizing the wrong one wastes effort and money. docs.anyscale
Why cost is a first-class metric
Every token has a price. Input tokens, output tokens, and (when available) cached tokens are billed differently. A single verbose system prompt repeated on every request, or an agent that loops unnecessarily, can multiply cost by 5–10× compared with a carefully engineered path. Cost must therefore be attributed per request, per feature, and per model—exactly like latency. maviklabs
Why drift matters even when the model is frozen
You may freeze the model weights, yet the world changes. User language evolves, product catalogs update, regulations shift. The embeddings of new prompts drift relative to the baseline you used to tune retrieval or routing. Statistical and semantic drift detection tells you when the ground has moved under your feet so you can retrain, re-index, or adjust thresholds before quality collapses. docs.aws.amazon
With these principles in place we can define the concrete metrics and architecture.
Core Concepts
Latency Metrics That Actually Matter
Time to First Token (TTFT)
Explanation. TTFT is the elapsed time from the moment the client sends the request until the first output token is received. It includes network transit, any server-side queueing, and the entire prefill phase. clickhouse
Intuition. In a streaming chat UI, TTFT is the awkward silence before the model “starts talking.” Users notice it immediately.
Real-world example. A support chatbot with a 4 k-token system prompt plus retrieved documents may show TTFT of several seconds on a cold or heavily loaded GPU, even if subsequent tokens stream quickly.
Visual explanation.
Common misconception. “Faster GPUs always fix TTFT.” Prefill scales with prompt length and batch size; queueing and cold starts often dominate. You must measure the components separately. tianpan
Time per Output Token (TPOT) / Inter-Token Latency (ITL)
Explanation. TPOT is the average time between consecutive output tokens after the first. For a single request:
ITL usually refers to the individual gaps; TPOT is their average (request-weighted). handbook.modular
Intuition. TPOT is the “reading speed” of the response. Even with excellent TTFT, a high TPOT makes the stream feel sticky.
Real-world example. Interactive coding assistants target roughly 20–100 tokens/s per request (TPOT ≈ 10–50 ms) so the stream feels faster than a human can read. clickhouse
Common misconception. “Throughput (tokens/s server-wide) is the same as user-perceived speed.” Server throughput can be high while individual requests suffer from large batching delays. Always report per-request TPOT percentiles. digitalocean
End-to-End Latency and Percentiles
Explanation. End-to-end (E2E) latency is wall-clock time from request sent to final token received. Always track p50, p95, and p99. A healthy p50 with a large p99 gap signals tail latency caused by queueing, stragglers, or occasional long prompts. 21medien
When to use which metric
| Metric | Primary UX / ops signal | Optimize when… |
|---|---|---|
| TTFT | Perceived responsiveness of streaming UI | Interactive chat, short prompts, low queue depth desired |
| TPOT / ITL | Smoothness of the stream | Long generations, real-time reading experience |
| E2E p95/p99 | Contractual SLOs, worst-case experience | Any production SLA |
| Tokens/s (server) | Capacity planning | Sizing GPU fleet |
Throughput, Concurrency, and Goodput
Throughput is usually measured as tokens generated per second across the whole serving fleet, or requests per second. Concurrency is the number of in-flight requests. Because decode is memory-bandwidth bound and prefill is compute bound, raising concurrency past a point increases throughput but also raises TTFT and TPOT for every request—the classic latency-throughput tradeoff. medium
Goodput is the fraction of requests that meet your latency SLOs. Maximizing raw tokens/s while goodput collapses is a common production mistake. Watch the saturation curve: as load rises, TTFT and TPOT percentiles climb; goodput eventually falls. Capacity planning uses that curve. learnaivisually
Token Usage and Cost Attribution
Every successful observability pipeline records, per request:
- Input tokens
- Output tokens
- Cached tokens (when the provider supports prompt caching)
- Model identifier and provider
- Feature / route / tenant tags
- Estimated cost (using the provider’s current price table)
Counters and histograms of these values feed cost dashboards and budget alerts. Without per-feature attribution you cannot answer “which product surface is burning the budget?” jobsbyculture
Semantic Caching vs Exact / Prompt Caching
Exact caching returns a stored response only when the prompt string matches exactly. Natural language almost never repeats verbatim, so hit rates stay low.
Prompt caching (offered by several major providers) caches the computation of a long, stable prefix (system prompt + tools + few-shot examples). Subsequent requests that share the same prefix pay a reduced rate for those tokens. Typical savings on agent and chat workloads: 60–80% of the prefix cost. aisuperior
Semantic caching embeds the incoming query, compares it (usually by cosine similarity) to embeddings of previously answered queries, and, if similarity exceeds a threshold, returns the cached answer without calling the LLM. Hit rates of 30–60% (and higher on repetitive workloads) are common when the threshold is tuned carefully. dev
Intuition. Exact cache = “same string.” Prompt cache = “same expensive prefix.” Semantic cache = “same meaning.”
Common misconception. “Semantic cache is always safe.” If the threshold is too low you serve wrong answers. Start around 0.8 cosine similarity, raise it for precision-sensitive domains, and always monitor quality alongside hit rate. dev
Embedding Drift and Data Drift
Data drift is a change in the distribution of inputs. Embedding drift is the same phenomenon observed in the high-dimensional vector space produced by your embedding model.
Detection workflow used in production:
- Establish a baseline distribution of prompt (or document) embeddings from a stable period.
- Continuously sample production embeddings.
- Compare distributions with a metric suited to high dimensions (Wasserstein distance, centroid shift, classifier AUC, etc.).
- Alert when the distance exceeds a threshold; then sample the drifted prompts and optionally use an LLM-as-judge for semantic classification of the change. apxml
Without this loop, retrieval quality and routing decisions degrade silently.
Observability Pillars Applied to LLMs
| Pillar | LLM-specific content |
|---|---|
| Metrics | Request rate, TTFT/TPOT/E2E histograms, token counters, cost gauges, cache hit rate, queue depth, error codes (timeouts, content filters) |
| Traces | One root span per user request; child spans for retrieval, prompt assembly, each LLM call, tool calls, guardrails; GenAI semantic attributes (gen_ai.system, gen_ai.usage.input_tokens, \ldots) |
| Logs | Structured JSON with request ID, model, token counts, truncated/redacted prompts and completions, latency breakdown |
| Continuous eval | LLM-as-judge or cheaper classifiers on a sample of production traffic, attached as span attributes |
OpenTelemetry has become the vendor-neutral standard for this instrumentation. medium
Deep Dive
Anatomy of a Production LLM Request Path
A realistic high-concurrency path looks like this:
Every box must emit metrics and spans. The gateway is also the natural place for fallbacks, load balancing across providers, and cost budgets. truefoundry
Prefill vs Decode and Disaggregation
Prefill is compute-heavy and benefits from high FLOPS; decode is memory-bandwidth heavy and benefits from high HBM bandwidth and efficient KV-cache management. Modern serving systems (vLLM and derivatives, production stacks with LMCache, etc.) therefore:
- Use PagedAttention / continuous batching so that decode steps from many requests share the GPU efficiently.
- Optionally disaggregate prefill and decode onto different pools so that long-prefill jobs do not stall interactive decode traffic.
- Share or offload KV cache across instances (prefix-aware routing) to avoid recomputing common prefixes. youtube
These techniques simultaneously improve TTFT, TPOT, and cost per token.
Quantization, Batching, and Model Tiering
| Technique | Primary benefit | Main tradeoff | Typical use |
|---|---|---|---|
| 8-bit / 4-bit quantization | Lower VRAM, higher tokens/s | Small quality drop on some tasks | Self-hosted inference |
| Structured / continuous batching | Higher GPU utilization | Higher TTFT under load if not tuned | All high-concurrency servers |
| Speculative decoding | Lower TPOT | Extra draft model complexity | Latency-sensitive decode |
| Model tiering / routing | Large cost reduction | Need quality gates and fallback | Mixed workloads |
| Prompt + semantic caching | Avoid repeated work | Stale or wrong cache entries | Repetitive query distributions |
Cost Optimization Playbook (2026)
Experienced teams report that most production bills can be cut 47–80% (sometimes more) without quality loss by applying a short list of high-leverage moves in order: jobsbyculture
- Meter everything first. Per-request cost telemetry tagged by feature and model. Build a “top-10 routes by cost” dashboard.
- Enable prompt caching on every route with a stable prefix longer than ~500–1 k tokens. Savings of 60–90% on the prefix are common.
- Route by difficulty. Send the 60–80% of easy requests to a small/cheap model; escalate only when a quality or confidence signal fails. Savings 50–70% on mixed workloads.
- Batch APIs for any work that is not user-facing and real-time (often ~50% discount).
- Shape outputs. Strict structured outputs, explicit max tokens, and removal of unnecessary verbosity cut output tokens 20–40%.
- Semantic caching for repetitive natural-language queries (30–60%+ when tuned).
- Fine-tune or distill a small specialist model only when volume justifies the MLOps cost (roughly >100 M tokens/month on a stable task).
Never optimize before you can attribute cost. The first dashboard often reveals a single verbose agent loop or an uncached system prompt that dominates spend.
Drift Detection Internals
For embedding drift the following statistics are practical:
- Centroid shift:
- Wasserstein / Earth-Mover distance on the embedding distributions (or on PCA-reduced vectors)
- Classifier two-sample test: train a binary classifier to distinguish baseline vs current embeddings; AUC near 0.5 means no drift, high AUC means separable (drifted) distributions. apxml
When an alert fires, sample the new prompts and run a lightweight LLM-as-judge prompt that classifies the semantic nature of the change (new product names, language shift, adversarial inputs, etc.). That classification drives the remediation playbook (re-index, retrain router, tighten guardrails). docs.aws.amazon
SLIs, SLOs, and Alerting
Define SLIs that map directly to user pain:
- Availability: fraction of requests that return a non-error completion within the timeout.
- Latency: p95 TTFT < X ms, p95 TPOT < Y ms, p99 E2E < Z ms.
- Quality: fraction of sampled outputs that pass an automatic judge or user thumbs-up.
- Cost: cost per successful request or per active user, with budget burn-rate alerts.
Pair each SLO with a multi-window, multi-burn-rate alert (the same pattern used by Google SRE) so that you are paged for fast burns and ticketed for slow burns. Include circuit breakers that shed load or fall back to a cheaper/faster model when error budgets are exhausted. community.ibm
Historical Context (condensed)
Scaling laws (Kaplan et al., 2020) showed that loss improves predictably with model size, data, and compute, driving the race to ever-larger models. Once those models reached production, the bottleneck shifted from training to inference economics and reliability. Systems papers and open-source engines (vLLM, TensorRT-LLM, production stacks with KV-cache sharing) then focused on continuous batching, paged attention, and disaggregation. Observability standards (OpenTelemetry GenAI semantic conventions) and cost-control patterns (prompt caching, semantic caches, intelligent routers) matured between 2024 and 2026 into the toolkit described in this chapter. arxiv
Practical Examples
Beginner — Instrumenting a Single Chat Completion
Goal: record TTFT, TPOT, token counts, and estimated cost for one OpenAI-compatible call.
What you learn. Even a few lines of instrumentation surface the two latency numbers and the dollar cost. In production you would emit these as OpenTelemetry metrics/spans instead of printing.
Intermediate — Semantic Cache in Front of the Model
Operational notes.
- Start with threshold ≈ 0.8–0.85; raise for legal/medical domains. dev
- Record hit/miss as a metric and sample cached answers for quality audits.
- Combine with exact-match cache on normalized queries for free additional hits.
- Set TTLs according to content volatility (minutes for news, hours/days for stable docs).
Advanced — OpenTelemetry Trace for a RAG + LLM Pipeline
Conceptual span hierarchy (Python OpenTelemetry SDK style):
Emit histograms for llm.ttft, llm.tpot, llm.e2e and counters for tokens and cost. Export to a collector that scrapes Prometheus-compatible metrics and forwards traces to your backend (Jaeger, Grafana Tempo, vendor APM, etc.). freecodecamp
Use the OpenTelemetry GenAI semantic conventions so that any compliant backend can display model name, token counts, and latency without custom parsing. mlflow
Code Examples
Production-oriented metric helpers
This pattern is the minimum viable production instrumentation: one function wraps every LLM call, records the four critical signals, and stays vendor-neutral via OpenTelemetry. medium
Simple difficulty router (cost control)
Pair with an eval set of a few hundred examples so you know the small model’s pass rate before you turn the router on in production. jobsbyculture
Diagrams
Decision tree: which latency knob to turn
Cost-control control loop
Tables
Latency metrics cheat comparison
| Metric | Formula / definition | Dominated by | Typical interactive target |
|---|---|---|---|
| TTFT | t_first_token − t_request | Prefill + queue + network | < 1 s for short prompts |
| TPOT | (t_last − t_first) / (n_out − 1) | Decode step, batch size, memory BW | 10–50 ms |
| E2E | t_last − t_request | TTFT + decode | SLO-dependent |
| Server tokens/s | total output tokens / wall time | Batching efficiency, hardware | Capacity metric |
Caching strategies
| Strategy | Match key | Savings range (reported) | Risk |
|---|---|---|---|
| Exact string | Full prompt hash | Low on natural language | Stale answers |
| Prompt / prefix | Stable prefix tokens | 60–90% of prefix cost | Provider-specific |
| Semantic | Embedding similarity | 30–60%+ of calls | Wrong answer if threshold low |
Cost levers ranked by typical impact
| Lever | Typical savings | Effort | Quality risk |
|---|---|---|---|
| Prompt caching | 60–80% on prefix-heavy traffic | Low | Low |
| Model routing | 50–70% on mixed workloads | Medium | Medium (needs eval) |
| Batch API | ~50% on async | Low | None (latency trade) |
| Output shaping | 20–40% output tokens | Low–medium | Low |
| Semantic cache | 30–60% calls | Medium | Medium |
| Fine-tune small model | High at large volume | High | Medium |
Common Mistakes
1. Tracking only average latency
Why it happens: averages hide tails.
How to avoid: always export p50/p95/p99 for TTFT, TPOT, and E2E. Alert on the percentiles that appear in your SLO. tianpan
2. Optimizing tokens/s while goodput collapses
Why it happens: bigger batches look great on GPU utilization dashboards.
How to avoid: plot the saturation curve; define goodput as “requests meeting TTFT/TPOT SLOs” and maximize that. learnaivisually
3. No cost attribution
Why it happens: the bill arrives as one line item from the provider.
How to avoid: tag every call with feature/tenant/model and maintain a price table; build a top-N cost dashboard before any other optimization. jobsbyculture
4. Semantic cache with an untested threshold
Why it happens: teams chase hit rate.
How to avoid: start conservative (≈0.85), measure answer correctness on a held-out set, and monitor cached vs fresh quality in production. dev
5. Ignoring embedding drift
Why it happens: the model weights are frozen, so “nothing can change.”
How to avoid: baseline embeddings, compute a high-dimensional drift statistic on a schedule, and alert + sample when it moves. docs.aws.amazon
6. One giant model for every request
Why it happens: simplest integration.
How to avoid: classify difficulty or use a cheap model first with confidence-based escalation. maviklabs
7. Logging full prompts and completions without redaction
Why it happens: debugging convenience.
How to avoid: scrub PII and secrets in the instrumentation layer before export; sample rather than store 100% of traffic when volumes are high. mlflow
8. No fallback or circuit breaker
Why it happens: happy-path demos.
How to avoid: timeouts, retries with jitter, fallback to a smaller model or cached answer, and load shedding when error budgets burn. community.ibm
Real Industry Examples
SRE-style LLM serving. Production guidance for scaling LLMs explicitly re-uses classic SRE practices: SLIs/SLOs for latency and quality, circuit breakers, queue-based load regulation, and monitoring of the full path including vector databases and embedding services. community.ibm
vLLM Production Stack. The open-source vLLM ecosystem has been extended with KV-cache sharing (LMCache), prefix-aware routing, and first-class observability so organizations can run multi-instance deployments on Kubernetes with higher hit rates on shared prefixes and clearer autoscaling signals. youtube
Enterprise observability stacks. Teams instrument every LLM call with OpenTelemetry, export to Prometheus/Grafana (or equivalent), and track exactly the metrics listed in this chapter—p95/p99 latency, token counts, cost per feature, cache hit rates, and queue depth—then add continuous evaluation on a sample of traffic. 21medien
Cost reduction case patterns (2025–2026 literature). Multiple independent engineering write-ups report 47–80%+ cost reductions from the combination of prompt caching, difficulty-based routing, batch APIs, output-token discipline, and semantic caching, provided metering and quality gates are in place first. aisuperior
Drift monitoring in generative applications. Production ML platforms document the baseline → monitor → Wasserstein/centroid/classifier comparison → LLM-as-judge classification loop for prompt and embedding drift. apxml
(These examples are drawn from public engineering material and research; specific internal numbers at Google, Meta, etc., are rarely published in full and are not invented here.)
Best Practices
-
Instrument before you optimize. Ship OpenTelemetry (or equivalent) spans and metrics for every LLM and retrieval call on day one. medium
-
Separate TTFT from TPOT in dashboards and SLOs. They fail for different reasons and need different fixes. tianpan
-
Attribute cost per feature and per model. Make the top-10 cost routes visible to the whole team. jobsbyculture
-
Prefer prompt caching + routing + output discipline before fine-tuning. They are cheaper to operate and reverse. jobsbyculture
-
Treat the semantic cache as a product surface. Version it, set TTLs, monitor hit rate and quality, and allow per-request bypass. dev
-
Run continuous, sampled evaluation. Attach judge scores to traces so quality regressions appear beside latency regressions. mlflow
-
Design for graceful degradation. Timeouts, fallbacks to smaller models or cached answers, and explicit budget guards keep the service usable when a provider or GPU pool degrades. community.ibm
-
Revisit quantization and batching under real traffic. Synthetic benchmarks miss the prompt-length distribution and concurrency patterns of production. digitalocean
-
Baseline embeddings and watch drift. Schedule the comparison; do not wait for user complaints. docs.aws.amazon
-
Keep human-readable runbooks. When p99 TTFT spikes, the on-call engineer should know whether to look at queue depth, prompt length, cache hit rate, or provider status—without reverse-engineering the dashboard.
Interview Questions
Beginner
Q1. What is TTFT and why does it matter for chat UIs?
A. Time to First Token—the delay until the first output token arrives. It determines how quickly a streaming interface feels responsive. It is dominated by queueing and the prefill phase. docs.anyscale
Q2. How is TPOT calculated?
A. . It measures average inter-token time during decode. handbook.modular
Q3. Name three metrics you would put on an LLM service dashboard.
A. p95/p99 TTFT and TPOT (or E2E), token usage and estimated cost per request/feature, cache hit rate, error rate. 21medien
Intermediate
Q4. Explain the difference between prompt caching and semantic caching.
A. Prompt caching reuses the computed state of a long stable prefix (provider-side, token-price discount). Semantic caching embeds the query and returns a previous answer when meaning is similar (application-side, avoids the call entirely). jobsbyculture
Q5. How would you detect embedding drift in a RAG system?
A. Store a baseline distribution of embeddings; periodically compare with production embeddings using Wasserstein distance, centroid shift, or a classifier two-sample test; alert and then sample + LLM-judge the change. apxml
Q6. A service has great average latency but users complain. What do you look at?
A. Percentiles (p95/p99), the gap between p50 and p99, queue depth, and whether long prompts or cold starts create a heavy tail. tianpan
Senior
Q7. How do you set an SLO for a streaming LLM API?
A. Separate SLIs for availability, p95/p99 TTFT, p95/p99 TPOT (or E2E), and a quality SLI from sampled judges or user feedback. Use multi-window burn-rate alerts on the error budget. Include fallback behavior when the budget is exhausted. learnaivisually
Q8. Design a cost-reduction plan that must not regress quality more than 2%.
A. (1) Meter cost by route; (2) enable prompt caching; (3) build a 200–500 example eval set; (4) introduce difficulty routing with the small model only when it scores ≥98% of the large model on the eval; (5) add semantic cache with a high threshold and quality monitoring; (6) tighten max output tokens; (7) gate every change on the eval and on online quality metrics. jobsbyculture
Q9. Prefill and decode have different bottlenecks. How does that affect cluster design?
A. Consider disaggregating pools, using continuous batching and paged KV cache, prefix-aware routing / KV sharing, and autoscaling policies that react to queue time (TTFT) vs decode load (TPOT) separately. medium
Exercises
Easy
- Wrap any single LLM API call you already have with timing code that prints TTFT, approximate TPOT, token counts, and cost. Compare two different prompt lengths.
- List every LLM and embedding call in a small app you own. Draw the span tree you would create with OpenTelemetry.
Medium
- Implement a minimal semantic cache (in-memory or Redis + any embedding model) in front of a toy Q&A app. Sweep the similarity threshold from 0.70 to 0.95 and plot hit rate vs a hand-labeled correctness score.
- Create a Grafana (or equivalent) dashboard with histograms for TTFT and TPOT and a counter for cost by feature. Feed it from a local OpenTelemetry collector.
Hard
- Build a two-tier router (small model → large model) with an LLM-as-judge or cheaper classifier as the gate. Measure cost and quality on a 200-example set before and after.
- Collect one week of production (or realistic synthetic) prompt embeddings. Compute daily centroid shift and a classifier AUC against the first-day baseline. Define an alert threshold and a short runbook.
Project
- Production-readiness mini-project. Take an existing RAG chatbot and add: (a) full OpenTelemetry instrumentation, (b) prompt caching where supported, (c) semantic cache with metrics, (d) cost dashboard, (e) p95 TTFT/TPOT SLOs with alerts, (f) a weekly embedding-drift job. Write a one-page design doc that explains the SLOs and the cost budget.
Cheat Sheet
Formulas
| Name | Formula |
|---|---|
| E2E | TTFT + (n_out − 1) × TPOT |
| TPOT | (E2E − TTFT) / (n_out − 1) |
| Rough cost | (in_tok × p_in + out_tok × p_out) / 1000 |
Default starting thresholds
| Item | Starting value | Notes |
|---|---|---|
| Semantic cache cosine | 0.80–0.85 | Raise for high-stakes domains |
| Prompt cache | Enable if prefix ≥ 500–1k tokens | Provider-specific |
| TTFT interactive | < 1 s (short prompts) | Context-length dependent |
| TPOT interactive | 10–50 ms | 20–100 tok/s |
Glossary
| Term | Definition |
|---|---|
| TTFT | Time to First Token — delay until the first output token arrives. |
| TPOT | Time per Output Token — average time between subsequent tokens. |
| ITL | Inter-Token Latency — individual gaps between tokens; TPOT is the average. |
| E2E latency | Wall-clock time from request send to final token. |
| Prefill | Forward pass over the full prompt that builds the KV cache. |
| Decode | Autoregressive generation of one token at a time. |
| KV cache | Stored key/value tensors from attention; avoids recomputation during decode. |
| Goodput | Rate (or fraction) of requests that meet latency/quality SLOs. |
| Semantic cache | Cache that matches queries by embedding similarity rather than exact text. |
| Prompt cache | Provider-side reuse of a stable prompt prefix at reduced token price. |
| Embedding drift | Change in the distribution of embedding vectors relative to a baseline. |
| Data drift | Change in the input data distribution. |
| SLI / SLO | Service Level Indicator / Objective — measurable signal and its target. |
| OpenTelemetry (OTel) | Vendor-neutral standard for traces, metrics, and logs. |
| GenAI semantic conventions | OTel attribute names for model, tokens, etc. |
| Continuous batching | Serving technique that adds/removes requests from a GPU batch at iteration boundaries. |
| Quantization | Reducing weight/activation precision (e.g., 8-bit, 4-bit) to save memory and increase throughput. |
| Model routing / tiering | Sending requests to different models according to difficulty or cost. |
| LLM-as-judge | Using a language model to score or classify outputs for evaluation or drift analysis. |
References
The following sources were used to ground the metrics, formulas, and practices in this chapter. Prefer primary documentation and recent engineering write-ups when you implement.
- LLM latency metrics (TTFT, TPOT, ITL, E2E) and formulas — NVIDIA NIM benchmarking, independent latency decomposition guides, and inference benchmarking references. roeybc
- Production scaling, SRE practices for LLMs, quantization, batching, semantic caching, model tiering — scaling and deployment guides. linkedin
- AI/LLM observability metrics, OpenTelemetry instrumentation patterns, cost attribution — observability engineering articles. youtube
- Semantic caching design and thresholds — production caching write-ups and AWS semantic cache material. youtube
- LLM cost optimization playbooks (prompt caching, routing, batch APIs, output shaping) — 2025–2026 engineering guides. codezilla
- Embedding and data drift detection (Wasserstein, centroid, classifier tests, LLM-as-judge follow-up) — drift monitoring references. docs.aws.amazon
- vLLM production stack, KV-cache sharing, prefix-aware routing — project and conference material. youtube
- Scaling laws background — Kaplan et al., “Scaling Laws for Neural Language Models” (2020). arxiv
- MegaScale and large-scale training systems context (observability at training scale). arxiv
- Additional enterprise deployment and multi-agent observability discussions. medium
Official documentation to keep open while implementing
- OpenTelemetry GenAI semantic conventions and SDK docs
- Your model provider’s prompt-caching and pricing pages (OpenAI, Anthropic, Google, Amazon Bedrock, etc.)
- vLLM / TensorRT-LLM / chosen inference engine metrics documentation
- Prometheus / Grafana histogram and exemplar best practices
- Provider-specific batch API documentation
