7.2 Production LLMOps: Observability, Caching & Cost Control
Operate AI systems in production like a Staff Engineer: instrument OpenTelemetry GenAI traces, avoid dangerous cross-tenant Semantic Cache leaks, enforce per-tenant token budgets, and run zero-downtime model migrations.
1. Traditional APM Isn't Enough (HTTP 200 OK Can Still Be a Total Failure!)
In classical REST microservices, HTTP 200 OK in 190 ms means everything worked! In AI systems, an endpoint can return HTTP 200 OK in 600 ms while:
- Emitting
"INSUFFICIENT_CONTEXT"on 60% of queries because an upstream Confluence token expired and wiped your RAG index! - Silently burning
$0.42on a single turn because KV Prefix Caching dropped from92%to0%after a prompt commit! - Hallucinating because a provider deprecated a model snapshot!
The 6 Golden Metrics of LLMOps Observability
Instrument every LLM, Embedding, Reranker, and Tool call as nested OpenTelemetry (OTel GenAI) spans capturing:
- Latency Split:
TTFT(P50 / P95) +TPOT+ Retrieval / Tool duration - Token & Cache Economics:
input_tokens,cached_tokens(Cache Hit %!),output_tokens,reasoning_tokens,cost_usd - Quality Proxy Signals: Abstention rate (
found_in_sources == False), user thumbs-up/down, copy-button clicks, regeneration clicks, and async 5% sampled LLM-Judge scores! - Prompt & Model Lineage:
prompt_version("sql-reviewer@v4"), exactmodelsnapshot,temperature - Tenant Attribution:
org_id/user_idfor per-tenant cost caps & noisy-neighbor alerts - Guardrail Triggers: Injection flags,
finish_reason == "length",429failovers, circuit-breaker trips
2. Caching Layers: Prefix KV Cache vs. Exact Hash Cache vs. Semantic Cache
Not all "AI caches" are safe! Understand the exact tradeoffs across the three caching layers:
| Cache Layer | How It Matches | Hit Discount | Safety Risk | Verdict |
|---|---|---|---|---|
| 1. Provider KV Prefix Cache (Lesson 1.2) | Exact static prefix (System + Tools + Docs) | 50%–90% input off | ✅ Zero stale-answer risk (still runs fresh query!) | 🏆 Enable Everywhere! |
| 2. Exact Deterministic Response Cache (Redis) | SHA-256(model + prompt_ver + tenant_id + normalized_input) | 100% free · 2 ms! | ✅ Safe when scoped by tenant_id + doc_index_version | 🏆 Great for deterministic classifiers & tool lookups! |
3. Vector Semantic Cache (Cosine > 0.96) | Returns cached answer if new query vector is "close" | 100% free | 🚨 HIGH RISK! "Delete staging DB?" ≈ "Delete prod DB?" (cos = 0.97!), plus cross-user data leaks! | ⚠️ Public read-only FAQs ONLY! |
Critical Security Warning on Semantic Caches: Never enable a global Vector Semantic Cache on authenticated, personalized, or parameter-sensitive queries ("What is order #104's status?" vs "What is order #105's status?" have 0.992 cosine similarity!). Always scope any response cache by
tenant_id/acl_scope.
3. Wire-Level Trace: Safe Model Migration (Shadow → Canary → Cutover)
When a new model drops (Gemini 2.5 Flash or GPT-4.1-mini at half the cost), how do you migrate without breaking production? Run this 4-step Zero-Regression Cutover:
Baseline (Old Model): 94.0% accuracy | P95 = 920ms | $1.80/1k req Candidate (New Flash): 95.5% accuracy | P95 = 410ms | $0.24/1k req!
4. Production Code: Telemetry Wrapper, PII Scrubber & Per-Tenant Token Quota
import re, time
from dataclasses import dataclass
from openai import OpenAI
client = OpenAI()
# Redact emails, phone numbers & API keys BEFORE logging traces or sending to external LLMs!
PII_PATTERNS = [
(re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"), "[REDACTED_EMAIL]"),
(re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b"), "[REDACTED_API_KEY]"),
]
def scrub_pii(text: str) -> str:
for pat, repl in PII_PATTERNS:
text = pat.sub(repl, text)
return text
@dataclass
class LlmSpan:
tenant_id: str; model: str; prompt_ver: str
in_tok: int; cached_tok: int; out_tok: int; latency_ms: float; cost_usd: float
def traced_call(tenant_id: str, prompt: str, prompt_ver: str = "v3") -> tuple[str, LlmSpan]:
safe_prompt = scrub_pii(prompt)
t0 = time.perf_counter()
resp = client.responses.create(model="gpt-4o-mini", input=safe_prompt, max_output_tokens=500)
ms = round((time.perf_counter() - t0) * 1000, 1)
in_t = resp.usage.input_tokens
cached_t = resp.usage.input_tokens_details.cached_tokens
out_t = resp.usage.output_tokens
cost = ((in_t - cached_t) * 0.15 + cached_t * 0.075 + out_t * 0.60) / 1_000_000
span = LlmSpan(tenant_id, "gpt-4o-mini", prompt_ver, in_t, cached_t, out_t, ms, round(cost, 6))
return resp.output_text, span5. What Breaks in Production (War Stories)
- Logging Raw Customer Prompts Into Unsecured Log Aggregators: Developers
console.log(messages)during debugging and accidentally ship raw SSNs, medical notes, and pasted.envkeys into Datadog/CloudWatch forever! Scrub PII/secrets at the telemetry boundary and enable Zero Data Retention (ZDR) agreements on enterprise LLM accounts. - No Per-User / Per-Tenant Token Rate Limiter: Standard IP rate-limiting (
60 req/min) won't save you if 1 free-tier account sends 60 requests/min that each trigger an 8-step agent loop ($40/hour!). Rate-limit by cumulative daily token/dollar budget per user tier. - Ignoring Cache-Hit-Rate Alerts: Add a Grafana/Prometheus alert whenever
cached_tokens / input_tokensdrops by> 25%after a deploy — catching accidental dynamic-prefix regressions within 5 minutes instead of on next month's invoice!
Module 7.2 Mastery Check — Production LLMOps & Cost Control
Keep Exploring: Related Lessons & Tools
All Courses →Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.
Compute MD5, SHA-1, SHA-256, SHA-384, and SHA-512 hashes or keyed HMAC signatures directly in your browser using Web Crypto.