Observability and Production Monitoring
OpenTelemetry traces for agent loops and tool calls, counting tokens/cost without double counting, prompt cache diagnostics, content-capture configuration under privacy constraints (ZDR, HIPAA), SLI/SLO design and alerting against drift after model updates, and large-scale trace analysis with sampling, aggregation, and failure-cohort analysis.
- Telemetry and Instrumentation: distributed traces for agent loops and tool calls, token and cost metrics, cache diagnostics, structured logs, content capture under ZDR
- Production Monitoring and Alerting: SLIs/SLOs, dashboards, quality drift, regressions after model updates, anomalous usage
- Trace Analysis at Scale: sampling, aggregation, failure-cohort analysis
Domain overview
Domain 3 accounts for 12% of the CCDV-P exam (about 7 of the 60 scored items) and covers three skills: Telemetry and Instrumentation, Production Monitoring and Alerting, and Trace Analysis at Scale. A common item type presents a metrics table, a snippet of spans/logs, or a compliance requirement, and then asks which conclusion or configuration is correct.
| Skill | What items often test | Keywords to react to |
|---|---|---|
| Telemetry & instrumentation | Span tree, correct token counting, cache diagnostics, content mode | anthropic.model_request, claude_code.interaction, gen_ai.usage.*, metadata_only, OTEL_LOG_* |
| Monitoring & alerting | Choosing SLIs, alert thresholds, drift after model updates | TTFT, refusal rate, cost per task, control band, 2σ/3σ |
| Trace analysis at scale | Sampling, grouping by attribute, failure cohorts | the sampled flag in traceparent, request_id, prompt.id, cohorts by model/prompt version |
The guiding principle: each question needs the right data source. Traces diagnose individual requests, metrics/counters compute rates and trends, and the Usage and Cost API reconciles spend.
Telemetry & instrumentation
Map of telemetry sources
| Source | What it emits | Use when |
|---|---|---|
| Claude SDK | A CLIENT span for each request, tool spans for tools run by the tool runner |
Your app calls the API through the SDK; no admin rights needed |
| Claude API (destination in the Console) | A SERVER span and inner spans: each model run, server tool, compaction, Managed Agents turn; service.name=claude-platform |
You need to see inside the request; requires Admin rights |
| Claude Code / Agent SDK | Metrics, log events, and traces (beta) exported by the CLI | Agents running on the Claude Code harness |
| Usage and Cost API | Tokens and USD by time bucket, grouped by model, workspace, api_key_id |
Reconciling cost, detecting leaked keys |
SDK and API spans follow the OpenTelemetry GenAI semantic conventions (gen_ai.*), so any backend that understands this standard can display models, tokens, and messages without custom mapping.
The span tree for the Messages API and Managed Agents
The SDK attaches a W3C traceparent header to each request; the API makes the SERVER span a child of the CLIENT span, producing a single trace from your handler down to each model run:
weather_question INTERNAL (your span)
└── anthropic.messages.tool_runner INTERNAL (SDK, the whole loop)
├── anthropic.messages.create CLIENT (SDK)
│ └── anthropic.messages.create SERVER (API)
│ ├── anthropic.model_request INTERNAL gen_ai.usage.*
│ ├── anthropic.tool_use web_search INTERNAL (server tool)
│ └── anthropic.model_request INTERNAL stop_reason=tool_use
├── anthropic.custom_tool_use get_weather INTERNAL (your tool, run by the SDK)
└── anthropic.messages.create CLIENT → SERVER → model_request
- Three kinds of tool span:
anthropic.custom_tool_use <name>(tools you define, SDK only),anthropic.mcp_tool_use <name>(MCP tools),anthropic.tool_use <name>(server tools or prebuilt toolsets, API only). gen_ai.tool.call.id(thetoolu_ID) links the tool call in the previous request's output, the tool span, and the tool result in the next request's input. A tool that raises an error → the tool span isERRORwitherror.type=tool_error, and the loop keeps running.- Managed Agents: each turn is an
anthropic.session.turncontaininganthropic.model_requestand tool spans. Group bygen_ai.conversation.idto read one thread; group byanthropic.session.idto see the whole session, even when its spans are spread across several traces. - Production practice: wrap each unit of work (request handler, queue message, cron run) in your own span; export through an OpenTelemetry Collector with a
BatchSpanProcessor.
Claude Code and Agent SDK traces
The Agent SDK does not generate telemetry itself: it runs the Claude Code CLI as a child process and passes configuration through environment variables. There are three independent signals: metrics (OTEL_METRICS_EXPORTER), log events (OTEL_LOGS_EXPORTER), and traces (OTEL_TRACES_EXPORTER plus CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1); all of them require CLAUDE_CODE_ENABLE_TELEMETRY=1.
claude_code.interaction (one turn of the agent loop)
├── claude_code.llm_request model, ttft_ms, input/output/cache tokens, stop_reason
├── claude_code.hook (only when detailed beta tracing is enabled)
└── claude_code.tool
├── claude_code.tool.blocked_on_user waiting for a permission decision
├── claude_code.tool.execution success, error_class
└── (Agent tool) the subagent's llm_request / tool spans nest here
Subagent spans sit under the parent agent's claude_code.tool, so the whole delegation chain is one trace; agent_id and parent_agent_id tell you which agent issued a request. If you call query() while an OpenTelemetry span is active, the SDK automatically injects TRACEPARENT so that claude_code.interaction becomes a child of the application span. Interactive sessions ignore an incoming TRACEPARENT; only the Agent SDK and claude -p use it.
Exam trap
- Don't use the
consoleexporter through the Agent SDK: stdout is the SDK's message channel. - TypeScript:
options.envreplaces the inherited environment (you must spread...process.env); Python:envis merged. - The CLI silently drops telemetry when the endpoint fails; set
CLAUDE_CODE_OTEL_DIAG_STDERR=1to see the errors. Short-lived processes that exit before flushing lose the batch: lowerOTEL_METRIC_EXPORT_INTERVAL,OTEL_LOGS_EXPORT_INTERVAL,OTEL_TRACES_EXPORT_INTERVAL.
Token and cost metrics: count exactly once
The CLIENT span, the SERVER span, and the anthropic.model_request spans beneath it carry the same usage, so summing them all double counts. Rules:
- For each request, sum one source only: if API spans exist, use them; within them, sum the SERVER span or the
anthropic.model_requestspans, not both; addanthropic.compactionif present. Managed Agents: sumanthropic.model_requestandanthropic.session.outcome_evaluation. - Delivery is at-least-once: dedupe by trace ID + span ID.
- Don't bill from spans: delivery is best-effort, a destination can be disabled, and the API emits no spans for traces that are not sampled. Reconcile with the Usage and Cost API.
| Token field | Claude API OTel (gen_ai.usage.input_tokens) |
Claude Code (input_tokens) |
Response usage.input_tokens |
|---|---|---|---|
| Includes cache read/write tokens? | Yes | No (separate cache_read_tokens, cache_creation_tokens) |
No (only tokens after the last breakpoint) |
| Total input | Use it directly; don't add cache | input + cacheRead + cacheCreation |
cache_read + cache_creation + input_tokens |
Reasoning tokens are included in output tokens (broken out separately in gen_ai.usage.reasoning.output_tokens). claude_code.cost.usage is an estimate; to roll up subagent cost, use the counter filtered on query_source="subagent", because the total_tokens of the subagent_completed event covers only the last request.
Key point
A cost view takes one source per request and does not stack it on top of the CLIENT span; reconcile periodically with the Usage and Cost API. That API also counts requests that have no spans, so it is the right tool for detecting a leaked API key (group by api_key_id).
Cache-performance diagnostics
Three usage fields are your diagnostic data: cache_creation_input_tokens (cache writes), cache_read_input_tokens (cache reads), and input_tokens (the uncached part). The cache is a prefix match in the order tools → system → messages; changing any layer invalidates that layer and every layer after it.
| Data pattern | Likely diagnosis | Remedy |
|---|---|---|
| Read and creation are both 0 | The prompt is below the minimum cacheable length (no error is raised) | Expand the static part to reach the model's threshold |
| Large creation on every request, read ≈ 0 | The prefix changes every time: a timestamp in the system prompt, nondeterministic tool order, shuffled JSON keys | Move the dynamic parts after the last breakpoint |
| Reads are good, then drop mid-conversation | Changing tool_choice, thinking configuration, effort, adding/removing tools, switching models |
Keep parameters stable; use defer_loading instead of changing the tools array |
| Reads drop after an idle gap | TTL expired (default 5 minutes) | Consider the 1-hour TTL |
The Claude Code team alerts on cache breaks and declares a SEV when the hit rate is low. The April postmortem shows the consequences: a bug that cleared thinking on every turn caused continuous cache misses, which made usage limits run out abnormally fast. The API also offers cache diagnostics that compare consecutive requests and report where the prefix starts to differ.
Grounding & reasoning traceability
- Citations: set
citations.enabled=trueon documents; each claim comes withcited_textand a location (character range, PDF page, or block index). Citations always point validly into the documents you provided;cited_textdoes not count toward output tokens. Store citations per claim so you can answer the audit question "which source does this sentence rely on?". - Retrieval in the trace: with Full content, tool spans carry
gen_ai.tool.call.arguments(the query) andanthropic.tool_result.content(what was retrieved), which helps separate retrieval failures from answer-generation failures. - Reasoning: in spans, thinking blocks become
{"type": "reasoning"}parts. To review reasoning, use thinking withdisplay: "summarized". - Versions: attach a version through
OTEL_RESOURCE_ATTRIBUTES="service.version=1.4.0,deployment.environment=production"andOTEL_SERVICE_NAMEso that every trace can answer "which version ran?".
Structured log events
Claude Code emits structured events: claude_code.user_prompt, api_request (with cost_usd, tokens, duration_ms), api_error, api_refusal, tool_result, tool_decision, api_retries_exhausted, compaction, subagent_completed... Correlation keys: prompt.id (every event for one prompt), request_id (matches the llm_request span and the request-id header), tool_use_id (matches the tool span and the hook payload). prompt.id is never attached to metrics because it would cause unbounded cardinality.
Control cardinality with OTEL_METRICS_INCLUDE_SESSION_ID, OTEL_METRICS_INCLUDE_ACCOUNT_UUID, and OTEL_METRICS_INCLUDE_RESOURCE_ATTRIBUTES. For an app that serves many end users through one credential, the default identity attributes only identify the service; inject enduser.id and tenant.id (percent-encoded) into OTEL_RESOURCE_ATTRIBUTES for each query() call.
Key point
Normalize the join keys before aggregating: request_id links the claude_code.llm_request span, the api_request/api_error events, and the API's request-id header; tool_use_id links the tool span, tool events, and the hook payload; prompt.id groups every event for one prompt but never goes into metrics.
Content capture under privacy constraints
By default, every source exports only structure: IDs, timing, status, tokens, tool names. Content is opt-in, and once exported it falls under the retention policy of your backend.
| Constraint / setting | Claude API & SDK | Claude Code / Agent SDK |
|---|---|---|
| Default | metadata_only |
Prompts, responses, and tool input/output are all redacted |
| Enabling content | SDK: ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE=content; destination: Full content (independent of the SDK) |
OTEL_LOG_USER_PROMPTS, OTEL_LOG_ASSISTANT_RESPONSES, OTEL_LOG_TOOL_DETAILS, OTEL_LOG_TOOL_CONTENT, OTEL_LOG_RAW_API_BODIES |
| Limits | 750,000 bytes/span (SDK); beyond that, the system prompt and the earliest messages are dropped and anthropic.content.truncated=true is set |
60 KB per attribute (CLAUDE_CODE_OTEL_CONTENT_MAX_LENGTH) |
| Zero data retention | Full content is still available; with the Messages API, content is held only in memory until delivered | Data goes only to the endpoint you configure |
| HIPAA / FERPA / K-12 | The destination exports metadata only regardless of content mode; SDK spans are unaffected | Filter/redact in the collector |
- Claude Managed Agents is not ZDR-eligible; enabling OpenTelemetry does not change its data retention.
conversation_id(which becomesgen_ai.conversation.id) is exported even in metadata only mode: don't put user data into the ID.- If
OTEL_LOG_ASSISTANT_RESPONSESis unset, it followsOTEL_LOG_USER_PROMPTS; to log prompts without logging responses, set it=0. OTEL_LOG_RAW_API_BODIEScontains the entire conversation history, so it implicitly consents to everything the otherOTEL_LOG_*flags would expose.- Claude Code ignores exporter variables in a repository's
.claude/settings.json: a repo cannot enable telemetry, change the destination, or turn on content capture. Lock the OTLP destination with managed settings: Claude Code then removes any endpoint the developer set themselves. - Prompts appear in two attributes,
promptandprompt_text; a deletion rule in the Collector must name both.
Exam trap
"With ZDR you cannot export prompt content" is wrong for the Messages API: Full content is still available. The real constraints: (1) for organizations with HIPAA/FERPA/K-12 restrictions, the destination exports metadata only; (2) exported content is subject to the access and retention rules of the backend you choose.
Scenario example
A healthcare support agent (in an organization with HIPAA restrictions) needs to debug tool failures. The team sets the destination to Full content but sees no prompts in the API spans: this is the correct behavior. Approach: use metadata (IDs, timing, stop_reason, tokens, tool names) to narrow down the problem, and enable content in SDK spans only once your backend is approved to store PHI. The lesson from Anthropic's multi-agent research system is the same: monitor the agents' decision patterns without reading conversation content.
(Sources: Claude Docs: OpenTelemetry tracing for the Claude API; Claude Code Docs: Monitoring; Claude Code Docs: Observability with OpenTelemetry; Claude Cookbooks: Observability)
Production monitoring & alerting
SLIs/SLOs for LLM services
| SLI | Signal | Notes |
|---|---|---|
| Latency p50/p95 | Duration of your root span or of anthropic.messages.tool_runner |
A streaming span ends when the stream has been fully read |
| TTFT | gen_ai.response.time_to_first_chunk (SDK, streaming), ttft_ms (Claude Code) |
With extended thinking, the first delta is a thinking delta |
| Error rate | ERROR spans + error.type (rate_limit_error, overloaded_error...); api_error events |
A streaming span that ends UNSET is normal; alert only on ERROR |
| Refusal rate | stop_reason="refusal", the claude_code.api_refusal event |
Refusals arrive on a 200 response and do not raise the error rate |
| Truncation rate | stop_reason="max_tokens" |
The cookbook recommends alerting on it to catch truncated answers |
| Cost per task | Total usage of all requests under one root span | One token source per request |
| Cache hit rate | cache_read / total input |
A few points of cache misses are enough to shift cost and latency sharply |
| Quality score | An LLM judge scores a sample of real traffic | The judge needs periodic human review |
Choose SLIs according to the real user experience: streaming chat cares about TTFT; batch pipelines care about total time and cost; customer-facing agents care about consistency (pass^k) more than "succeeded at least once".
Dashboards and alerts for tokens/cost
The Claude Code documentation suggests alerting on cost spikes, unusual token volumes, and unusually high session counts from a few users; metrics can be segmented by model, query_source, and team (via OTEL_RESOURCE_ATTRIBUTES). To keep alerts from being noisy, the AI-native SDLC course uses a control band:
- The baseline is the 30-day mean of hourly readings. With 720 readings per month, randomness alone produces about 4 readings per day beyond 1σ, 16 per month beyond 2σ, and 1 per month beyond 3σ.
- Tiered response: at 1σ, only log; at 2σ, call Claude read-only to diagnose; at 3σ, act through a gated route (a PR into a review gate, or a pre-approved runbook).
- Western Electric rules catch slow drift that never reaches 3σ: 4 of the last 5 readings above 1σ, or 8 consecutive readings above the mean; treat these like the 2σ tier.
Exam tip
"Cost per task has crept up for weeks but hasn't crossed the threshold" → a drift rule, not lowering the 3σ threshold (which causes a storm of false positives). "Suspected leaked API key" → the Usage and Cost API grouped by api_key_id, not counting spans.
Quality drift and regressions after model updates
The team's prompt edits and the real input distribution keep changing; CI only knows the cases it already has. The process from the Introduction to Evals course:
- Sample 1–5% of real traffic every night.
- Score it with an LLM judge against a rubric (real traffic has no reference answers).
- Alert when a night's score falls more than 2 standard deviations below the rolling baseline.
- Every item the judge scores incorrectly becomes a new case in the suite.
After a model update, split cohorts by the model that actually served the request: gen_ai.response.model differs from gen_ai.request.model when you use an alias or when a fallback model answers; analytics based on the requested model will be wrong when fallbacks occur (use usage.iterations). Some regressions live in the harness: the way Unicode and the / character are escaped in JSON tool input differs between model versions, which breaks raw string comparisons.
Scenario example
The "three recent issues" postmortem: a context-window routing bug initially affected 0.8% of Sonnet 4 requests, and then a load-balancing change on August 29 pushed that to 16% in the worst hour. Regular evals did not catch it, partly because Claude often recovers on its own from isolated errors. Lessons: evals must be sensitive enough to tell a correct deployment from a broken one, run continuously on the real production system, and user feedback (/bug, thumbs down) is a monitoring channel.
Key point
No single monitoring layer catches every failure (the Swiss Cheese model): automated evals give a fast loop, production monitoring gives ground truth, A/B tests cover major changes, and user feedback plus transcript reading fill the gaps.
Trace analysis at scale
Sampling
- Decide at the root and propagate: if the sampler drops a trace, the sampled flag in
traceparentis off and the API emits no spans for that request; the decision is consistent across the whole trace. - Multi-turn conversations: sample whole conversations, not individual requests, or the transcripts end up full of holes.
- Sampling is for diagnosis only. Compute error rates, cost, and SLOs from counters or the Usage and Cost API.
- General practice: keep a high rate for traces with errors, refusals, or
max_tokensso rare cohorts don't disappear; sample successful traces sparsely.
Aggregation and failure-cohort analysis
Systemic failures are often invisible in individual traces: each transcript looks like "the model is a bit worse". Process:
- Normalize the join keys:
request_id/anthropic.request.id,tool_use_id/gen_ai.tool.call.id,prompt.id,session.id,gen_ai.conversation.id. - Attach analysis dimensions: serving model, prompt/tool version, platform, tenant,
stop_reason,error_class,query_source, effort. - Compute each cohort's failure rate against the baseline, plotted on a timeline of each change.
| Cohort (24h) | Requests | Quality failure rate | Vs. 1.4% baseline |
|---|---|---|---|
| Whole system | 1,200,000 | 2.1% | +0.7 points |
| prompt v41 / model A | 900,000 | 1.4% | same |
| prompt v42 / model A | 280,000 | 4.0% | ~3× |
| prompt v42 / model B | 20,000 | 1.5% | same |
The failures are concentrated in the prompt v42 + model A combination; it is not that "the model got worse". Claude Code's April postmortem describes the opposite effect: three changes, each touching a different slice of traffic on a different schedule, which together looked like a broad, erratic degradation. "Sticky" routing made some users far more affected than others, so you need to look at the per-user distribution, not just the average.
Retry exhaustion in Claude Code: api_error is emitted only after retries run out (CLAUDE_CODE_MAX_RETRIES defaults to 10, so attempt goes up to 11). Group by session.id and check for any api_request after the error to distinguish sessions that recovered on their own from sessions that got stuck.
Exam trap
Don't draw conclusions from a global average or a handful of individual traces. The correct answer is usually "split cohorts by version/attribute and compare with the baseline"; "read a few more transcripts" or "raise sampling across the board" does not quantify the problem.
(Sources: CCDV-P Exam Guide, Domain 3; Anthropic Academy: The AI-native SDLC playbook — Closing the loop on metrics; Anthropic Academy: Introduction to evals — Evals in production: CI, batch, and drift; Anthropic Engineering: A postmortem of three recent issues; Claude Blog: Lessons from building Claude Code: Prompt caching is everything)
Quick summary
- The
CLIENT(SDK) andSERVER(API) spans are linked bytraceparent; each model run is ananthropic.model_request. - Count tokens for each request from one source (the SERVER span or the
anthropic.model_requestspans), addanthropic.compaction; dedupe by trace ID + span ID. gen_ai.usage.input_tokens(API OTel) already includes cache tokens; Claude Code'sinput_tokensand the responseusagefield do not.- Don't bill from spans; use the Usage and Cost API (it also counts requests with no spans; group by
api_key_id). - Cache read and creation both 0 → the prompt has not reached the minimum length; high creation on every request → the prefix keeps changing.
- Claude Code traces need
CLAUDE_CODE_ENABLE_TELEMETRY=1+CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1+OTEL_TRACES_EXPORTER; subagent spans sit under the parent agent'sclaude_code.tool. - The Agent SDK does not emit telemetry itself; don't use the
consoleexporter; export errors are silent unless you setCLAUDE_CODE_OTEL_DIAG_STDERR=1. - Metadata only by default; ZDR still allows Full content with the Messages API; HIPAA/FERPA/K-12 → the destination exports metadata only; Managed Agents is not ZDR-eligible.
- A repo cannot enable content capture or change Claude Code's telemetry destination; lock it down with managed settings.
- Refusals arrive on HTTP 200, so they need their own SLI; also alert on
stop_reason="max_tokens";UNSETon streams is normal. - Control band: log at 1σ, read-only diagnosis at 2σ, act through a gated route at 3σ; Western Electric rules catch slow drift.
- Drift: sample 1–5% of traffic nightly, score with an LLM judge against a rubric, alert when the score falls more than 2σ below the baseline.
- After a model update, analyze by the serving model (
gen_ai.response.model,usage.iterations). - Sampling is decided at the root, per whole conversation; systemic failures surface through failure-cohort analysis, not global averages.