Course
AI · Module 07: Evals, Production LLMOps & CapstoneTutorial 20 of 21
AI Course·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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.42 on a single turn because KV Prefix Caching dropped from 92% to 0% 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:

  1. Latency Split: TTFT (P50 / P95) + TPOT + Retrieval / Tool duration
  2. Token & Cache Economics: input_tokens, cached_tokens (Cache Hit %!), output_tokens, reasoning_tokens, cost_usd
  3. 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!
  4. Prompt & Model Lineage: prompt_version ("sql-reviewer@v4"), exact model snapshot, temperature
  5. Tenant Attribution: org_id / user_id for per-tenant cost caps & noisy-neighbor alerts
  6. Guardrail Triggers: Injection flags, finish_reason == "length", 429 failovers, 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 LayerHow It MatchesHit DiscountSafety RiskVerdict
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:

Tracing Zero-Downtime Model Migration (Offline Eval -> Shadow -> Canary)
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Offline Golden Dataset Gate Clears First)
Wire Telemetry:cost=$0.08
1→# Step 1: Offline Golden Eval Gate (50–200 curated cases in CI)
2→assert run_eval_suite(candidate="new-flash-model") >= baseline_score
3# Step 2: 5% Async Shadow Traffic (User still sees v1; v2 runs in background!)
4if random() < 0.05: asyncio.create_task(shadow_compare(req, v1_reply))
5# Step 3: 10% -> 50% -> 100% Canary Rollout watching thumbs-up & latency
CI Benchmark ComparisonOFFLINE PASS
Baseline (Old Model): 94.0% accuracy | P95 = 920ms | $1.80/1k req
Candidate (New Flash): 95.5% accuracy | P95 = 410ms | $0.24/1k req!
What's Happening: For $0.08 of eval tokens, you verify schema compliance, injection defense, and faithfulness before a single live user sees the new model!

4. Production Code: Telemetry Wrapper, PII Scrubber & Per-Tenant Token Quota

SDK:
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, span

5. What Breaks in Production (War Stories)

  1. Logging Raw Customer Prompts Into Unsecured Log Aggregators: Developers console.log(messages) during debugging and accidentally ship raw SSNs, medical notes, and pasted .env keys into Datadog/CloudWatch forever! Scrub PII/secrets at the telemetry boundary and enable Zero Data Retention (ZDR) agreements on enterprise LLM accounts.
  2. 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.
  3. Ignoring Cache-Hit-Rate Alerts: Add a Grafana/Prometheus alert whenever cached_tokens / input_tokens drops 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

Q1.Why is enabling a global Vector Semantic Cache (`cosine > 0.96`) dangerous on authenticated customer-support queries like `'Where is order #1042?'`?
Q2.Why should your observability dashboard alert on sudden drops in `cached_tokens / input_tokens` after a deployment?
Q3.What is 'Shadow Traffic' testing when migrating from an expensive model to a new faster model?
Q4.Why is request-per-minute (`RPM`) rate limiting alone insufficient to prevent runaway LLM API bills?

Keep Exploring: Related Lessons & Tools

All Courses →