RBRunbook
Study

Domains · Domain 3 · 12% of scored questions

Observability and Production Monitoring

About 7 of the 60 scored questions come from this domain. It has 3 skills:

Lessons

Skill

Telemetry and Instrumentation

Telemetry and instrumentation: what to record, and what not to

Instrumentation for a Claude system has two jobs that pull against each other. It must let an engineer reconstruct what an agent did, and it must not copy sensitive content into a backend that was never approved to hold it.

The three signals
SignalUse it forTypical content
TracesOne request end to end: each turn of the agent loop, each model request, each tool callSpans with timing, model, token counts, stop reason, status
MetricsRates and totals over time: tokens, cost, sessionsCounters with a small set of attributes
Log eventsDiscrete facts you want to search or audit: a tool decision, an API error, a refusalStructured records with correlation IDs

The Agent SDK and Claude Code export all three, each with its own switch. In the Agent SDK the spans form a tree: an interaction span per turn, with model-request and tool spans beneath it, and a subagent's spans nested under the parent's tool span. The Claude API offers SDK tracing (client spans, your own tools) and API tracing (server spans, each model run, server tools).

Link the agent to the request that caused it

A trace is only useful if it joins the rest of your system. Trace context travels in the W3C traceparent header or, for the Agent SDK's child process, an environment variable. The SDK passes it on automatically, but only when a span is active at the moment you call it. If agent spans show up as separate root traces, look for the place where the context was lost: a queue, a background worker, a thread with no active span.

Identity needs the same care. Telemetry attributes describe the credential that called Anthropic. In a multi-tenant service that is your service account, not the person. Attach an opaque end-user ID and tenant ID to each call (resource attributes for the Agent SDK, baggage for the Claude API) so tool activity can be attributed later.

Token, cost, and cache numbers
  • Input tokens are split three ways in the API usage block: uncached input, cache read, and cache creation. The uncached figure alone looks tiny once caching works. Total input is the sum of the three. The GenAI convention's input-token attribute already includes cache tokens, so do not add them twice.
  • Count each token once. With SDK and API tracing both on, one request has a client span and a server span carrying the same usage. Sum one source.
  • Client-side cost is an estimate. Cost metrics and SDK cost fields are computed locally from a price table. Use them for alerts and trends; use billing data for money decisions.
  • Cache diagnosis needs two facts: did the request prefix change, and did the cache hit. Cache diagnostics reports the first; cache-read tokens report the second. Matching requests with no cache read means the entry expired or the prompt was too short, not that the prompt varies.
Content capture under privacy constraints

Telemetry is structural by default: durations, model names, tool names, token counts. Content is opt-in, and the switches are graded. In the Agent SDK they run from prompt text, to tool arguments, to tool output, to full API request and response bodies, which include the whole conversation. Turn on the narrowest one that answers the debugging question. In Claude API tracing the choice is metadata only or full content, per destination and per SDK client.

Zero data retention is a statement about what Anthropic stores. It does not cover your observability platform. Content you export is stored there under that platform's own access and retention rules, so review those before enabling content. Some features, such as batch processing, file storage, and Managed Agents sessions, are outside a ZDR arrangement, and using one is a choice to step outside it for that data.

Masking one attribute in the collector and assuming the content is gone. The same text often travels on more than one path: two attributes on a log event, and a span attribute once tracing is on. List every path before writing the rule, or do not enable the content switch.
Grounding and reasoning traceability

For retrieval-grounded answers, record which sources were retrieved and which were cited, by ID, on the span for that answer. With the citations feature, cited passages point back to the supplied documents, so the IDs can be logged without storing the document text.

Operational details that bite
  • Export failures are silent by default. Check the collector, not the application.
  • Telemetry is batched. A process killed right after it finishes loses its buffer. Lower the export interval for short jobs.
  • A refusal arrives as a successful response with a refusal stop reason. An error-rate chart will not show it. Record stop reason as a first-class field.

Sources
Agent SDK: Observability with OpenTelemetry
Claude Code: Monitoring
OpenTelemetry tracing for the Claude API
Prompt caching
Cache diagnostics
API and data retention
Citations
Agent SDK: Track cost and usage

Skill

Production Monitoring and Alerting

Production monitoring and alerting: SLIs, burn rates, and drift

An LLM-backed service can return HTTP 200 on every request and still fail its users. Monitoring for these systems starts from that fact: define what a good response is, measure the share of responses that are good, and alert when that share is falling fast enough to matter.

Choose indicators that match the user's experience

The Google SRE workbook recommends writing a service level indicator (SLI) as a ratio: good events divided by total events. For a Claude service, decide what makes an event good:

  • Availability: the request returned a usable answer. A response cut off by the output limit, or a refusal of an ordinary request, is not good even though the status code is 200.
  • Latency: the request finished under a threshold. Use a percentile or a share-under-threshold, not a mean. A mean hides a slow tail, and agent workloads have long tails.
  • Quality: a sampled, graded share of answers judged acceptable, or a task-outcome rate such as resolution without human handoff.

The service level objective (SLO) is the target for the ratio over a window, and the error budget is what is left: 100% minus the SLO.

Alert on budget consumption, not on every blip

A fixed threshold over a short window pages for brief spikes that cost almost nothing, and stays noisy during a slow regression until someone mutes it. The workbook's answer is the burn rate: how fast the service is consuming its error budget relative to the SLO. A burn rate of 1 uses exactly the whole budget over the SLO window.

Design choiceWhat it buys
High burn rate over a short windowPages within minutes for a severe outage
Lower burn rate over a long windowCatches a slow regression; usually a ticket, not a page
Add a second, much shorter window to each ruleThe alert stops soon after recovery, so nobody silences it

Low-traffic services break this scheme, because one failure is a large share of an hour's requests. The options are to add synthetic traffic, combine services that fail together, lengthen the window, or accept a lower target. Which one applies depends on the constraints: a contractual SLO cannot be lowered, and a service with no siblings cannot be combined.

Page on symptoms, keep causes for diagnosis

Cache hit rate, retry counts, and tool timeouts are causes. They belong on the dashboard an on-call engineer opens after the page, not in the paging rules, unless they predict user harm on their own. If most cause alerts fire with no user impact, move them.

Token and cost telemetry

Two sources exist and they serve different purposes.

  • Your own telemetry (the usage block on each response, or exported token and cost metrics) is immediate but approximate for cost. Use it for rate alerts and runaway detection.
  • The organization's usage and cost reporting is authoritative but arrives hours later. Use it for chargeback, reconciliation, and per-key audits.

Segment before you alert. A fleet-wide token threshold misses a small tenant running at many times its own normal rate. Compare each tenant, key, or agent with its own baseline, and watch ratios such as tokens per session, which separate more usage from a looping agent.

Detect quality drift and behavioural regressions

Error rate and latency do not move when the model starts answering differently. Add signals that do:

  • Behavioural indicators by model and prompt version: stop-reason mix, refusal rate, tool calls per task, output length, handoff rate.
  • A fixed set of reference inputs run on a schedule and scored against the previous baseline.
  • A graded sample of live traffic, with enough volume that a change is not noise.

Tag every span and metric with the versions that can change behaviour: model ID, prompt version, retrieval index version, tool schema version. Without those tags a quality drop cannot be split by cause.

Assuming the model changed underneath you. Claude model IDs are pinned snapshots, so a quality change with an unchanged model ID almost always comes from something you shipped or from a shift in traffic. Check your own deploy history first.

After a deliberate model migration, expect behaviour to shift and watch the behavioural indicators for the first days, split by model, rather than waiting for a manager to notice a business metric.

Sources
SRE Workbook: Implementing SLOs
SRE Workbook: Alerting on SLOs
SRE Book: Service Level Objectives
SRE Book: Monitoring Distributed Systems
Claude Code: Monitoring
Usage and Cost Analytics API
Models overview

Skill

Trace Analysis at Scale

Trace analysis at scale: sampling, aggregation, and failure cohorts

One trace tells you what happened once. A systemic problem shows up only when you look across thousands: a tool that fails for one tenant, a small group of interactions that loop, a retry rate that climbs in one region. This skill is about keeping the right traces and asking the right aggregate questions of them.

Sampling: decide what to keep
Head samplingTail sampling
When the decision is madeAt the start of the traceAfter the trace completes
What it can seeTrace ID and start-time attributesThe whole trace: errors, latency, any span attribute
StrengthSimple, cheap, works anywhere in the pipelineCan keep every error or slow trace
CostCannot favour rare failuresStateful collectors that buffer traces and need capacity and monitoring

The OpenTelemetry guidance is direct: with head sampling alone you cannot make sure every trace containing an error is kept. If the failure you are chasing is rare, a 1% random sample keeps 1% of it, and doubling the rate still leaves you with almost nothing. Use tail sampling to keep all errors and slow traces plus a small random share of healthy ones.

At very high volume the two are combined: head sampling by trace ID first, to protect the pipeline, then tail sampling on what remains. Head sampling by trace ID keeps whole traces. Sampling individual spans at random does not, and leaves broken traces.

Computing rates from a biased trace store. If the store keeps every error and 2% of successes, the error share in the store is meaningless. Take rates from metrics counted before sampling, or weight each trace by the inverse of the probability with which it was kept. Use traces to explain a number, not to produce it.

Sampling upstream also affects what others emit. If your application marks a request as not sampled in its trace context header, the Claude API emits no span for it. Exported spans are delivered on a best-effort basis and can be lost, so they are not a complete usage record. For complete per-key usage, use the organization's usage reporting.

Aggregation: get the unit right
  • Pick the grouping key that matches the question. A trace is not always a session. A Managed Agents session can span several traces and several threads; group by the session ID attribute for the whole session and by the conversation ID for one thread.
  • Remove duplicates first. Span delivery can repeat when an export is retried. Count distinct trace ID and span ID pairs.
  • Look at distributions. A mean of six model requests per interaction can hide a tail at eighty. Chart percentiles of requests, tokens, and duration per interaction and look at the top.
  • Use events as terminal signals correctly. A client that retries internally may log one error only after it gives up. To tell a recovered session from a stalled one, group by session and check whether a later successful request exists.
Failure-cohort analysis

When engineers read forty failed traces and list nine causes, reading more traces rarely helps. Switch to cohorts:

  1. Define the failure outcome precisely so it can be counted.
  2. For each attribute (tenant, model, prompt version, tool, input size, region), compute the failure rate per value.
  3. Compare each rate with the overall rate. A segment whose failure rate is many times the baseline is a lead.
  4. Quantify it: what share of all failures does the segment explain, and what share of traffic is it?
  5. Only then open individual traces from that segment to find the mechanism.

The comparison with the baseline matters. A tool that appears in 62% of failed traces is not suspicious if it appears in 64% of all traces. A tool that appears in 24% of failures and 3% of traffic is enriched eightfold, and that is where to look.

What to carry on every span

Cohort analysis is only possible on attributes you recorded. Carry the dimensions you will want to group by: model, prompt version, tool name, tenant, outcome, stop reason, attempt count. Keep them bounded. An unbounded value such as a raw user string as a metric attribute raises cardinality and cost without helping aggregation; put it on the span or the log event instead.

A working order
  1. Check the metric: is the rate really up, and since when?
  2. Segment the rate by recorded attributes and find the enriched cohort.
  3. Quantify the cohort's share of failures and of traffic.
  4. Read a handful of traces from inside the cohort and a handful from outside it.
  5. Fix, then confirm on the same segmented rate.

Sources
OpenTelemetry: Sampling
OpenTelemetry: Traces
OpenTelemetry tracing for the Claude API
Set up API tracing
Claude Code: Monitoring
SRE Book: Service Level Objectives

Sample questions

Sample question
A legal-research assistant runs on the Claude Agent SDK and exports OpenTelemetry traces and log events to the firm's backend. The reliability dashboard charts one failure series: claude_code.api_error events per 1,000 requests, which has stayed under 2 for a month. In that month, paralegals filed 61 tickets about sanctions-case questions that got no usable answer. The model-request span from one ticketed session:
claude_code.llm_request
  success: true
  attempt: 1
  duration_ms: 1840
  output_tokens: 12
  stop_reason: refusal
The other sampled tickets look the same. Which change makes these cases visible on the dashboard?
  • AChart claude_code.api_refusal events per 1,000 requests as a second series
  • BChart claude_code.api_retries_exhausted events per 1,000 requests as a second series
  • CChart claude_code.api_error events whose message mentions a refusal as a second series
  • DChart claude_code.llm_request spans that carry success: false as a second series
Show the answer and explanation

Answer:

  • Chart claude_code.api_refusal events per 1,000 requests as a second series

The span shows a request that succeeded on its first attempt and ended with a refusal stop reason. A refusal arrives on a successful response stream, not as an HTTP error, so no api_error event exists for it, whatever its message filter; Claude Code logs a separate api_refusal event for exactly this case. The retries-exhausted event accompanies a final error after several attempts, and this request made one attempt and succeeded. Filtering spans on success: false misses it for the same reason: the span reports success.

Sample question
A platform team exports Claude Code OpenTelemetry metrics for 900 engineers, including claude_code.cost.usage with a team attribute. Two consumers want cost data. The on-call rotation wants a page within 15 minutes when a team's spend rate jumps. Finance wants a monthly chargeback for each team that reconciles with the invoice. The team can also query the organization's Usage and Cost Analytics API, grouped by workspace, and each team has its own workspace. Which assignment of sources fits both consumers?
  • AUse the Analytics API for both, queried every minute with one-minute time buckets
  • BPage from the exported cost metric and build the chargeback from the Analytics API
  • CPage from the Analytics API and build the chargeback from the exported cost metric
  • DUse the exported cost metric for both, corrected by a factor from last month's invoice
Show the answer and explanation

Answer:

  • Page from the exported cost metric and build the chargeback from the Analytics API

The exported cost metric is computed on the client and documented as an approximation, so it suits a fast spend-rate page but will not reconcile with an invoice. The Analytics API reports the organization's recorded usage and cost, but its data typically refreshes hours after the usage, so it suits a monthly chargeback and cannot page within 15 minutes. Swapping the two gives a late page and an inexact chargeback. A correction factor assumes last month's gap is constant. One-minute buckets set the granularity of the rows, not how soon the data arrives.

Sample question
An insurance-claims agent handles 120,000 interactions a week. Weekly model spend rose 31% while traffic stayed flat. The fleet dashboard shows mean model requests per interaction at 6.2, against 6.0 a month ago. The five traces an engineer opened at random each showed 5 to 7 model requests, a correct result, and tokens per request in line with last month's. Daily spend climbed gradually, with no step on any day. The trace store holds the span count and token totals of every interaction. What should the team examine first?
  • AThe per-interaction distribution of model requests and tokens, at its upper percentiles
  • BA further random sample of fifty traces, with each one read from its first span to its last
  • CThe fleet-wide total of input tokens for the week, broken down by day and by hour of the day
  • DThe five opened traces again, with their prompts compared against last month's prompt versions
Show the answer and explanation

Answer:

  • The per-interaction distribution of model requests and tokens, at its upper percentiles

Typical interactions look unchanged in request count and in tokens per request, and there is no step that would mark a deploy, yet spend is up by a third. That pattern fits a small, growing group of very long interactions: context grows with every loop turn, so a fraction of a percent of interactions can carry most of the extra tokens while barely moving the mean. The upper percentiles of the per-interaction distribution show whether that group exists and how large it is. Fifty more random traces will almost all be typical. A total by day and hour repeats the gradual climb already known. Re-reading five healthy traces cannot reveal a group they do not belong to.

↑↓ move↵ openesc close