Architecture
Production AI observability instruments every execution hop from gateway authentication through query rewriting, retrieval index lookup, LLM inference, and tool side effects under one correlated OpenTelemetry trace (gen_ai.*), allowing incident responders to pinpoint silent semantic regressions, cache poisoning, and cost anomalies without exporting sensitive customer PII into plaintext logs.
Traditional microservices alert loudly on HTTP 5xx error rates or pod crashes; generative AI applications silently degrade while continuously emitting HTTP 200 OK. An unnoticed chunking change drops retrieval hit rates 25%, a silent vendor checkpoint swap begins truncating JSON tool schemas on non-English queries, or a misconfigured agent loop triples retry spending overnight—all while standard Kubernetes liveness probes report completely green. Defending production reliability demands end-to-end version provenance across every trace span paired with non-destructive incident snapshot containment before rolling back.
1. Correlated GenAI Span Topology & Privacy Hygiene
Every user turn emits a single W3C traceparent hierarchy tying deterministic software spans together with probabilistic generation telemetry (OpenTelemetry Semantic Conventions for GenAI):
ingress.gatewaySpan: Authenticatedtenant_idhash, tier quota, prompt hash, and redacted classification label (never raw user passwords or SSNs).retrieval.hybridSpan: Emitscorpus_index_epoch, HNSWef_search, top- chunk IDs + scores, ACL filter latency, and empty-result flags (retrieval_zero_hits).gen_ai.chatSpan: Recordsgen_ai.system,gen_ai.request.model, immutableprompt_template_sha256,input_tokens,cached_read_tokens,output_tokens,ttft_ms,tpot_ms,finish_reason, andschema_retry_count.tool.boundarySpan: Captures tool name, normalized digest, sandbox exit code,idempotency_key, and postcondition check result (allow | deny | rollback).
Forensic Versioning Over Raw Payload Dumping
Exporting raw full-text prompts into general APM stores turns your observability cluster into a shadow PII repository violating GDPR minimization boundaries. Instead, attach immutable content-addressed hashes (prompt_template_sha, retriever_epoch, policy_version, chunk_ids) universally at 100% span volume, while routing anonymized/redacted forensic exemplars selectively onto short-TTL restricted incident buckets whenever error triggers or sampling conditions fire.
2. Incident Taxonomy & Containment Playbook Matrix
| Failure Mode | Fast Telemetry Signal | First Containment Action (< 2m) | Forensic Artifact to Preserve First |
|---|---|---|---|
| Hallucination / Grounding Regression | Groundedness judge drop or user thumb-down spike | Route cohort to strict extractive RAG mode / abstain on low confidence | prompt_sha, retrieved chunk_ids, index_epoch |
| Prompt Injection / Unauthorized Tool | tool.boundary PEP deny spike or unusual egress probe | Flip read_only_tools_only feature kill-switch globally | Input tool/chunk digest & triggering span tree |
| Token Cost / Loop Explosion | Output/input token ratio spikes or retry amplification > 12% | Tighten per-session turn/USD caps; shed speculative retries | Trace loop count + repeated normalized call hashes |
| Provider Quantization / Latency Drift | TPOT P99 > SLO or schema_retry_count jump | Circuit-break failing model route -> warm pinned fallback | Exact gen_ai.response.model checkpoint & finish reason |
Worked Incident Containment Timing (MTTD -> Forensic Save -> Safe Mitigation)
Why order-of-operations matters during a SEV-1 quality incident: if an on-call engineer immediately runs FLUSHDB on Redis semantic caches AND rolls back two Helm releases before exporting trace identifiers, the root-cause trigger vanishes—and teams reintroduce the exact bug next week! Freezing an immutable forensic tuple (trace_id, chunk_ids, index_epoch, model_version) first (~15 seconds), then throwing deterministic kill switches (disable write tools, shift traffic weight -> pinned N-1) restores clean SLA within < 2 minutes while seeding permanent CI regression test cases.
3. PII-Scrubbing OpenTelemetry GenAI Span Helper in Python
pythonimport hashlibimport refrom dataclasses import dataclassSECRET_OR_PII_RE = re.compile(r"(sk-[A-Za-z0-9]{16,}|Bearer\s+[A-Za-z0-9._-]+|\b\d{3}-\d{2}-\d{4}\b|[\w.+-]+@[\w-]+\.[\w.-]+)")@dataclass(frozen=True)class GenAiTelemetryEnvelope:trace_id: strgen_ai_system: strgen_ai_model: strprompt_template_sha: strretrieval_index_epoch: strinput_tokens: intcached_tokens: intoutput_tokens: intttft_ms: floatredacted_error_summary: str | Nonedef scrub_for_observability(raw_text: str, max_len: int = 240) -> str:"""Strip credentials, tokens, SSNs, and emails cleanly before emitting span attributes."""redacted = SECRET_OR_PII_RE.sub("[REDACTED]", raw_text)return redacted[:max_len]def emit_genai_span_attributes(trace_id: str,model_id: str,template_body: str,index_epoch: str,in_tok: int,cached_tok: int,out_tok: int,ttft_ms: float,raw_err: str | None = None,) -> GenAiTelemetryEnvelope:tpl_sha = hashlib.sha256(template_body.encode("utf-8")).hexdigest()[:16]safe_err = scrub_for_observability(raw_err) if raw_err else Nonereturn GenAiTelemetryEnvelope(trace_id=trace_id,gen_ai_system="vllm",gen_ai_model=model_id,prompt_template_sha=tpl_sha,retrieval_index_epoch=index_epoch,input_tokens=in_tok,cached_tokens=cached_tok,output_tokens=out_tok,ttft_ms=round(ttft_ms, 2),redacted_error_summary=safe_err,)
Decisions
| Decision | Required evidence | Review trigger |
|---|---|---|
Enforce mandatory W3C traceparent propagation + immutable prompt_template_sha / retrieval_index_epoch tags across all spans. | Staging span audit showing 100% end-to-end trace stitching | Adding new gateway microservices or proxy hops |
| Scrub all logged spans and debug payloads via regex + NLP redaction before external APM export. | Zero unmasked API keys/PANs in CI fuzz trace fixtures | Any change to debug error logging |
Alternatives and trade-offs
- Full Unsampled Prompt Capture vs. Structured Metadata + Audited Redacted Sampling: Raw logging speeds ad-hoc debugging while leaking customer PII and inflating egress bills; deterministic redaction + tail-based error sampling protects compliance and storage budgets.
Failure modes
- Unscrubbed prompt payloads leaking tenant secrets into observability SaaS logs: Debug tracing left enabled across staging and prod leaks API tokens and HIPAA PII to unauthorized APM viewers.
- Monitoring vendor API status pages as a proxy for product reliability: External endpoints return
HTTP 200while silently swapping quantized backend behavior or rate-limiting one tenant tier. - Correlating latency cleanly without version stamps: Detecting a
TTFTspike or grounding drop without immutableprompt_template_shaandretrieval_index_epochtags makes bisecting deploys slow guesswork. - Destructive blind rollbacks destroying reproduction traces: Wiping caches or rewriting corrupted tables prior to dumping failing
trace_idtuples prevents postmortem root-cause closure.
Operational checklist
- Distributed W3C trace context links gateway, retrieval, model call, tool execution, and eval verdicts cleanly.
- All span error attributes and debug previews pass strict deterministic PII/secret scrubbing before export.
- SLO dashboards alert jointly on latency tails (
TTFT/TPOT), retry ratios, schema drop rates, and sampled quality drift. - Read-only fallback and tool kill switches execute without container redeploys in
< 60seconds. - Every SEV incident produces a new permanent deterministic or golden slice test before incident ticket closure.
Connected Practice
- Labs: /labs/cost-latency-reliability, /labs/evaluation-metric-comparison
- Projects: /projects/system-design-casebook, /projects/evaluation-control-system-project
- System breakdowns: /systems/inside-vllm
Sources
- Observability & reliability primary references:
otel-genai,opentelemetry-traces,sre-book,openai-latency
Step through live KV-cache block paging
Inspect virtual-to-physical VRAM page tables, Copy-on-Write forks, and internal fragmentation in the PagedAttention simulator.
Subscribe to Engineering Briefings
Join AI systems engineers receiving architecture teardowns, benchmark notes, and new simulator releases. Unsubscribe anytime.
