Mental model
A raw vendor request_id shows only one isolated LLM hop cleanly, hiding upstream query rewrites, ACL vector lookup latency, tool failures, retries, and post-generation guardrails. AI tracing (OpenTelemetry GenAI conventions) treats every user request as a unified distributed causal tree of linked parent/child spans—measuring timing, tokens, costs, error taxonomies, and exact immutable version identifiers (model, prompt, index, policy) cleanly end-to-end without leaking raw PII payloads into observability lakes.
Learning outcomes
- Propagate W3C Trace Context (
trace_id,span_id,links) across synchronous web gateways, streaming SSE responses, async background queues, and parallel tool fan-outs cleanly. - Instrument required OpenTelemetry GenAI semantic attributes (
gen_ai.system,gen_ai.request.model, token counts, prompt hash, index version, error class) enabling rapid root-cause isolation cleanly. - Enforce privacy-safe observability via payload hashing/redaction alongside tail-based / risk-based sampling (
keeping 100% of errors, high-latency tails, and risky write turns cleanly).
Theory
Observability platforms combine three orthogonal telemetry primitives anchored identically onto one shared trace_id: metrics (low-cardinality counters/histograms for P95 alerts cleanly), structured logs (discrete security audit receipts), and distributed traces (exact causal critical-path waterfalls explaining why single requests failed or stalled cleanly!). Crucial attributes separate reproducible configuration metadata from sensitive customer payloads:
| Telemetry Span Layer | Key Attributes Captured | Sensitive Payload Handling | Diagnostic Question Answered |
|---|---|---|---|
| Edge Ingress Root Span | tenant_tier, route, total_duration_ms, outcome_status | Never inject user_id or prompt prose into metric labels | Which endpoints blew latency budgets today? |
| Retrieval & Rerank Span | index_version, rewritten_count, acl_filter_ms, top_k_chunk_ids[], rerank_model | Store chunk IDs & score histograms (never full restricted paragraphs) | Did latency come from slow SQL ACLs or missed candidate IDs? |
LLM Inference (gen_ai.*) | gen_ai.request.model, gen_ai.response.model, prompt_sha, cached_tokens, ttft_ms, tpot_ms, finish_reason | Store sha256(prompt) + token counts cleanly; mask raw bodies unless opt-in debug | Did vendor snapshot silently shift verbosity (+40% output) or drop cache hits? |
| Tool Execution & Policy Span | tool_name, duration_ms, error_kind, approval_bound, policy_decision | Scrub auth tokens/secrets BEFORE telemetry export cleanly | Which flaky downstream API caused 3 agent retries? |
pythonfrom dataclasses import dataclass, fieldimport hashlibimport time@dataclassclass OTelGenAISpan:trace_id: strspan_name: strstart_ns: int = field(default_factory=time.time_ns)attributes: dict[str, object] = field(default_factory=dict)def record_inference_metadata(self,model_snapshot: str,prompt_text: str,prompt_version: str,input_tokens: int,cached_tokens: int,output_tokens: int,ttft_ms: float,) -> None:"""Capture full reproducibility & cache efficiency metadata cleanly without raw PII leaks."""prompt_digest = hashlib.sha256(prompt_text.encode("utf-8")).hexdigest()[:16]self.attributes.update({"gen_ai.request.model": model_snapshot,"fsai.prompt.version": prompt_version,"fsai.prompt.sha256": prompt_digest,"gen_ai.usage.input_tokens": input_tokens,"gen_ai.usage.cache_read_tokens": cached_tokens,"gen_ai.usage.output_tokens": output_tokens,"gen_ai.server.time_to_first_token_ms": round(ttft_ms, 2),})
Trade-offs
Full 100% trace retention with raw prompt payloads catches obscure domain hallucinations rapidly cleanly during initial prototyping, yet explodes observability vendor bills cleanly at production traffic volumes while duplicating PII privacy liability across logging backends. Switching production onto privacy-preserving digest attributes + tail/risk-based sampling (1–5% baseline healthy traffic, 100% retention on errors, timeouts, high latency, tool mutations, and user thumbs-down flags linked straight to eval suites cleanly) keeps costs bounded while surfacing nearly every real defect cleanly.
Failure modes and misconceptions
- Logging Raw Complete User Prompts by Default: Forwarding raw financial, healthcare, or auth credentials straight into third-party tracing dashboards turns telemetry into an immediate compliance hazard.
- High-Cardinality Metric Labels (
trace_idorqueryinside Prometheus): Injecting unique user/query strings directly into metric time-series tags crashes monitoring TSDB RAM quickly; high-cardinality details belong strictly cleanly on spans/logs! - Confusing Provider
x-request-idWith System Traces: Only logging LLM vendor request IDs hides whether3.8slatency happened inside broken query rewriting, Postgres lock contention, or external webhooks cleanly. - Spans Without Version Metadata: Recording timing numbers cleanly without pinning
prompt_version,index_rev, andmodel_snapshotmakes A/B regressions indistinguishable cleanly.
Decision scenario
A multi-stage RAG support service reports random 6-second completion stalls and intermittent broken citations across enterprise accounts, yet engineers currently log only vendor HTTP status codes and raw message dumps cleanly. Instrument end-to-end OpenTelemetry GenAI trace propagation cleanly across rewrite, index_version, candidate chunk IDs, cached_tokens, citation allowlists, and thumbs_down eval links using hashed payload digests and tail sampling cleanly.
Which span attributes let engineering teams pinpoint and reproduce an AI quality or latency regression cleanly without storing sensitive raw customer text inside observability traces?