Claude Certified Developer · प्रोफेसनल

Module 3: Observability: drift, regressions and cost spikes

Study notes written by Sanjay Shah. Not official Anthropic material. Facts marked "check before relying on it" may have changed.

Practice this module

On this page

Study notes, not official course material. Our take on official course 3 (instrumentation; regressions, drift and cost anomalies). Facts checked 2026-11-25.

The video opens on a cost-per-ticket chart that runs flat and then jumps straight up, with a red "2×" on it. Every request in that period returned 200 OK. The logs said everything was fine. This module is about seeing what normal app monitoring can't: an answer can be successful and wrong, and a request can be successful and twice as expensive as yesterday.

What you'll be able to do

  • Explain why HTTP status, error rate and CPU miss most LLM failures.

  • Instrument a run as a trace: run → agent step → model call → tool call, with the few attributes that matter.

  • Read token usage correctly, and avoid the classic double count between the API response and OpenTelemetry spans.

  • Keep PII and secrets out of telemetry while still being able to debug a bad answer.

  • Split dashboards by tenant, prompt version and model, and roll back a bad prompt with a flag.

  • Write three alerts that matter: a cost-per-unit regression, a quality drift proxy and a runaway-agent cap.

1. Why normal monitoring misses LLM problems

A web API is "healthy" when it returns 2xx quickly. An LLM feature can do that and still be broken in ways that only show up as changes in what it returns:

ProblemHTTP statusLatencyWhat actually shows it
Answers become wrong after a doc change200normalEscalation rate, thumbs-down, judge score
A prompt edit makes answers twice as long200higher p95Output tokens per ticket, cost per ticket
The model starts refusing a category of ticket200normalstop_reason: "refusal" rate
An agent loops 40 times on one ticket200 (each call)very high for that runTurns per run, tool calls per run
Answers get cut off200normalstop_reason: "max_tokens" rate
Cache stops hitting200higher time to first tokenCache-read tokens share (Module 8)

Two more differences from normal APIs: cost per request varies widely (one ticket might use 2,000 tokens and another 60,000), and the same input can give different outputs, so one bad example isn't a trend. You need rates over many runs, split along the dimensions that cause change.

2. The trace: one run, many spans

OpenTelemetry (OTel) gives you traces made of spans. Each span has a name, a start and end time (so latency comes free), a parent, and attributes. For an agent system, the shape is:

Text
run  helpdesk.run                      run_id, tenant, ticket_id(hashed), outcome, turns
├─ step  agent.triage                  agent, step
│  └─ chat claude-haiku-5-5            model, tokens, stop_reason, prompt_version
├─ step  agent.billing
│  ├─ chat claude-opus-5-5
│  ├─ tool get_order                   tool name, outcome, latency
│  ├─ chat claude-opus-5-5
│  └─ tool issue_refund                idempotency_key, outcome
└─ step  agent.reviewer
   └─ chat claude-sonnet-5-5

Model-call spans follow the OpenTelemetry GenAI semantic conventions: attributes named gen_ai.*, such as gen_ai.request.model, gen_ai.usage.input_tokens and gen_ai.usage.output_tokens. Backends that understand these conventions can chart them with no mapping.

The attributes that matter

Most of your debugging will come down to a few fields. Put them on every model span (or on the run span, where they're the same for the whole run):

AttributeWhy
tenantProblems are often one tenant's docs or traffic
prompt_versionThe most common cause of a regression is a prompt change
modelModel changes alter cost, latency and behaviour
Input, output, cache-read and cache-write tokensCost and caching health
Cost estimateSo you can chart cost per unit of work without a billing export
Latency (span duration)p50/p95 per step
stop_reasonend_turn, tool_use, max_tokens, refusal
Tool name + outcomeWhich tool fails, which is slow
Run outcomeanswered, escalated, "I don't know", failed
Request idTo match one call with Anthropic support or the provider's logs

Instrumenting a model call

The Claude SDKs and the API can now emit OTel spans for Messages API requests themselves (a beta feature, see section 4). Whether you use that or wrap calls yourself, your app still has to add the attributes only it knows: tenant, prompt version, run id. A minimal manual wrapper:

TypeScript
import Anthropic from "@anthropic-ai/sdk";
import { trace, SpanStatusCode } from "@opentelemetry/api";

const client = new Anthropic();
const tracer = trace.getTracer("helpdesk-agent");

type Ctx = { tenant: string; promptVersion: string; runId: string };

export function tracedCreate(params: Anthropic.MessageCreateParamsNonStreaming, ctx: Ctx) {
  return tracer.startActiveSpan(`chat ${params.model}`, async (span) => {
    span.setAttributes({
      "gen_ai.operation.name": "chat",
      "gen_ai.request.model": params.model,
      "app.tenant": ctx.tenant,
      "app.prompt_version": ctx.promptVersion,
      "app.run_id": ctx.runId,
    });
    try {
      const msg = await client.messages.create(params);
      const u = msg.usage;
      const cacheRead = u.cache_read_input_tokens ?? 0;
      const cacheWrite = u.cache_creation_input_tokens ?? 0;
      span.setAttributes({
        "gen_ai.response.model": msg.model,
        "gen_ai.response.finish_reasons": [msg.stop_reason ?? "unknown"],
        // In spans, input tokens INCLUDE cache reads and writes (see section 3).
        "gen_ai.usage.input_tokens": u.input_tokens + cacheRead + cacheWrite,
        "gen_ai.usage.output_tokens": u.output_tokens,
        "gen_ai.usage.cache_read.input_tokens": cacheRead,
        "gen_ai.usage.cache_write.input_tokens": cacheWrite,
        "app.cost_estimate": estimateCost(msg.model, u), // from your own price table
      });
      return msg;
    } catch (err) {
      span.recordException(err as Error);
      span.setStatus({ code: SpanStatusCode.ERROR });
      throw err;
    } finally {
      span.end();
    }
  });
}

estimateCost multiplies each token type by a per-model rate you keep in config, updated from the pricing page. Cache reads and cache writes are priced differently from plain input, so cost them separately. Never hard-code rates in several places.

3. Reading token usage without fooling yourself

This catches people out, and it shows up directly in cost dashboards.

In the Messages API response, usage.input_tokens is only the uncached remainder. The total prompt size is:

Text
total input = usage.input_tokens + usage.cache_creation_input_tokens + usage.cache_read_input_tokens

An agent that ran for an hour can show input_tokens: 4,000 because everything else was read from cache. If you chart input_tokens alone, a caching improvement looks like a traffic drop, and a caching failure looks like a traffic spike.

In OpenTelemetry spans emitted by the SDK or API, gen_ai.usage.input_tokens already includes cache reads and writes, and the cache attributes are reported separately as well. If you add gen_ai.usage.cache_read.input_tokens to it, you count cached tokens twice.

Two more double-count traps:

  • Two sources for one request. If the SDK's OTel export is on and your own wrapper records gen_ai.usage.* for the same call, summing all spans counts every call twice. Pick one source per request for token totals, and put your app attributes on a parent span.

  • Usage on several levels. Some span trees repeat usage at more than one level. Sum only the per-request model spans, not their parents too.

Spans are not a bill. Span export is best effort: a span can be lost and isn't re-sent. For finance-grade numbers (spend per API key, per workspace, monthly), use the Usage and Cost Analytics API (beta at the time of writing), or the invoice. Its data can lag by up to a day, so it's for reconciliation, not live alerts. Spans and your cost estimate are for trends and alerts; the usage reports are the record.

4. The local stack, and Anthropic's OTel export

The course lab runs everything in Docker Compose (docker-compose.obs.yml):

  • The collector receives OTLP from the app, removes or hashes sensitive attributes, samples, and fans out to backends.

  • Jaeger shows one run's trace as a waterfall: which step was slow, which tool failed.

  • Prometheus stores metrics (counters and histograms derived from spans or emitted directly) for dashboards and alerts.

  • Grafana draws dashboards and evaluates alert rules.

Anthropic's own OpenTelemetry export is in beta as of 2026-11-25. The SDKs can emit spans for Messages API requests and tool use, and the API can deliver spans to a destination you configure, so calls show up in whatever OTLP backend you already run. Span names, attributes and options may change during the beta, so pin the SDK version. It has two content modes: one that records metadata (models, tokens, timings) and a full content mode that also records prompts and responses. Full content is what you'd want for debugging, and exactly what you must not send to a shared backend without thinking (next section).

5. Telemetry is data too: PII, secrets and the sampled store

Support tickets contain names, emails, addresses and sometimes card fragments. If full prompts go into span attributes, they're copied into every backend, kept for the backend's retention period and visible to everyone with dashboard access.

The rule: metadata everywhere, content only in a sampled, access-controlled store.

TypeScript
import { createHmac } from "node:crypto";

const KEY = process.env.TELEMETRY_HMAC_KEY!; // a secret; rotate it like one

// Stable pseudonym: same user → same value, so you can group by it without exposing it.
export const pseudonym = (id: string) => createHmac("sha256", KEY).update(id).digest("hex").slice(0, 16);

const EMAIL = /[\w.+-]+@[\w-]+\.[\w.-]+/g;
const LONG_DIGITS = /\b\d{12,19}\b/g; // card-like numbers

export const redact = (text: string) => text.replace(EMAIL, "[email]").replace(LONG_DIGITS, "[number]");
  • Use HMAC, not a plain hash, for ids: a plain SHA-256 of an email can be reversed by hashing a list of known emails.

  • Redaction regexes are a safety net, not a guarantee. That's why full prompts don't go to general telemetry at all.

  • The sampled store keeps, say, 1–5% of runs plus every escalated or failed run, with short retention, access limited to on-call engineers and access logged.

  • Never put API keys, OAuth tokens or the Authorization header in a span. Check your HTTP auto-instrumentation: some libraries record headers by default.

6. Sampling: keep the interesting traces

At volume you can't keep every trace. The naive approach, head sampling (decide at the start of a run to keep 5%), drops 95% of your rare failures too, and the rare failures are the ones you need.

Tail-based sampling decides after the run finishes. Keep:

  • every run with an error, a refusal or a max_tokens stop,

  • every escalated run,

  • every run over a latency or cost threshold,

  • plus a small random baseline of normal runs, so you know what "good" looks like.

The OTel Collector can do tail sampling with a processor in its contrib distribution. Metrics are a separate path and aren't sampled: counters and histograms should count every run, so rates stay accurate.

7. Dashboards: split by what changes

One overall average hides almost every real problem. The course dashboard has a few panels, each split by the dimensions that cause change:

  • Cost per resolved ticket, by prompt_version and by model.

  • Output tokens per ticket, by prompt_version.

  • p50 / p95 time to answer, by step.

  • Escalation rate, "I don't know" rate and refusal rate, by tenant.

  • Turns per run (histogram) and tool error rate, by tool.

  • Cache-read share of input tokens (Module 8).

Labels and cardinality

Metrics systems like Prometheus store one time series per unique combination of label values. A label like ticket_id or user_id creates a new series per ticket or user, and memory grows without limit. Keep metric labels low-cardinality: tenant (when the number of tenants is bounded), prompt version, model, outcome, tool name. Put high-cardinality ids on traces and logs, where every record is meant to be unique. Hashing an id doesn't help here; a hashed user_id is just as many series.

8. Worked example: the "small" prompt edit that doubled cost

The planted problem in the lab. Prompt v7 changes one line in the answer prompt: "Give detailed, thorough answers." Nothing else changes.

  1. The alert fires. Cost per resolved ticket has been above 1.5× the 7-day baseline for 15 minutes.

  2. Split by prompt_version. v6 traffic is flat; v7 traffic (rolled out to 100% an hour ago) shows output tokens per ticket up about 2.3× and p95 latency up as well.

  3. Contain. Prompt version is a deployable value read from a feature flag, not text pasted into the code. Flip the flag back to v6. Cost returns to baseline within minutes, and the dashboard proves it.

  4. Fix forward. If v7's goal was better answers, it goes back through the eval gate (Module 4) with a length budget in the prompt and a cost check in the gate.

What made this a five-minute fix instead of a day: every span carried prompt_version, and the version could be switched without a deploy.

TypeScript
// Prompts live in the repo as versioned files; the flag picks one; every span records it.
const version = flags.get("answer_prompt_version", { tenant }) ?? "v6";
const system = await readFile(`prompts/answer/${version}.md`, "utf8");

Failure case: a team stored prompts in a database table that support leads edited directly in production, with no version column. The cost spike was visible, but nobody could tell which edit caused it or put the old text back. Prompts are code: versioned, reviewed, deployed, and rolled back like code.

9. Alerts that matter

Three alerts cover most LLM-specific production problems. Everything else (error rate, availability) you'd have anyway.

Cost per unit against a baseline

Alert on cost per unit of work (per resolved ticket), not on total spend (traffic growth is good news) and not on single expensive requests (some tickets are just long). Compare with the same system's own recent baseline, and require it to stay high for a while:

YAML
groups:
  - name: helpdesk-llm
    rules:
      - alert: CostPerTicketAboveBaseline
        expr: |
          (sum(rate(helpdesk_llm_cost_estimate_total[15m]))
            / sum(rate(helpdesk_tickets_resolved_total[15m])))
          >
          1.5 * (sum(rate(helpdesk_llm_cost_estimate_total[7d] offset 1d))
            / sum(rate(helpdesk_tickets_resolved_total[7d] offset 1d)))
          and sum(rate(helpdesk_tickets_resolved_total[15m])) > 0.05
        for: 15m
        labels: { severity: page }
        annotations:
          summary: "Cost per resolved ticket is above 1.5x the 7-day baseline"

The last line is a minimum-volume guard: at 3 a.m., two expensive tickets aren't a trend.

A quality drift proxy

You rarely have ground-truth labels in production, but you have proxies: escalation rate, "I don't know" rate, thumbs-down rate, refusal rate. Each moves when quality moves. In the lab's synthetic week, cedar's escalation rate creeps up a little each day after cedar reorganises its help centre. The index still has chunks for pages that moved, and retrieval now often falls below the relevance threshold (Module 1).

Watch proxies per tenant against that tenant's own baseline, with a minimum volume, and correlate with change events (doc re-indexes, prompt versions, model changes). Then confirm with a small daily judge score: sample, say, 50 answered tickets per tenant, have a calibrated LLM judge grade them against the rubric (Module 4), and chart the pass rate. Proxies tell you something changed; the judge tells you whether quality changed.

Runaway agents

One run in the lab makes 40 tool calls, calling get_order again and again with the same arguments. Per-call metrics all look fine; the run is the problem.

  • Record turns per run and tool calls per run as histograms.

  • Alert when the high percentiles jump (for example p99 turns above twice the usual).

  • Enforce a hard cap in code (Module 2): the loop stops and escalates at the limit. An alert tells you; the cap protects you.

  • A cheap extra: if the same tool is called with identical arguments three times in a row, stop early and escalate.

10. Request ids and support

When a single call misbehaves and you need help from Anthropic, you need its request id. API error bodies include a request_id field, and the SDKs expose the id of successful responses too. Record it on the model span (and in the access-controlled store for sampled runs). A trace that can't be matched to the provider's records leads to a long support thread.

Trade-offs

  • Metadata vs full content. Metadata is safe to send anywhere but can't explain a wrong answer. Full content explains it but is sensitive data. Use both: metadata everywhere, full content sampled and locked down.

  • Head vs tail sampling. Head sampling is simple and cheap but loses rare failures. Tail sampling keeps what matters but needs a collector that buffers whole traces.

  • Own wrappers vs SDK export. The SDK's export is standard and needs little code, but it's beta and may change. Your own wrapper is stable and fully under your control, but you maintain it. Either way, one source per request for token totals.

  • Proxies vs judges. Proxies are free and real-time but indirect. Judges are direct but cost money and need calibration. Alert on proxies, confirm with a daily judge sample.

  • Alert sensitivity. A short window and a low threshold catch problems early and page people for noise. A sustained window with a volume guard pages less often and a little later.

Common mistakes

  • Treating 200 OK and low error rate as "healthy".

  • Charting usage.input_tokens from the API response as total input, or adding cache attributes to span gen_ai.usage.input_tokens (double counting).

  • Recording usage from both the SDK's spans and your own wrapper, then summing everything.

  • Using spans as the billing record.

  • Sending full prompts and responses to a shared observability vendor; plain-hashing emails; logging Authorization headers.

  • Head-sampling 5% and wondering where the failures went.

  • ticket_id or user_id as metric labels.

  • Prompts edited in production with no version, or the version not recorded on spans.

  • Alerting on total spend or single requests instead of cost per unit against a baseline.

  • An alert for runaway agents with no hard cap in code.

Remember

  • A 200 OK can be a wrong answer. Watch outcomes, not only status codes.

  • One trace per run; spans for every model and tool call; tenant, prompt version, model, tokens, cost, stop reason and outcome on them.

  • API usage.input_tokens excludes cache; span gen_ai.usage.input_tokens includes it. One source per request.

  • Spans are for trends and alerts. Usage reports and invoices are the bill.

  • Metadata everywhere; full content only in a sampled, access-controlled store. HMAC ids, never plain hashes.

  • Keep metric labels low-cardinality. Put ids in traces.

  • Prompt version is a flag you can roll back, and it's on every span.

  • Three alerts: cost per unit against a baseline, a quality proxy per tenant, turns per run, plus a hard cap in code.

Check before relying on it

  • Anthropic's OpenTelemetry export (SDK and API spans, content modes, destinations) is beta as of 2026-11-25; span names, attributes and options may change, so pin the SDK version.

  • The GenAI semantic conventions are still evolving upstream; attribute names such as gen_ai.provider.name and the cache attributes have changed before. Check the current convention version your backend expects.

  • gen_ai.usage.input_tokens including cache tokens is how Anthropic's spans defined it on 2026-11-25; other instrumentations may differ.

  • The Usage and Cost Analytics API is beta, and its data can lag by up to 24 hours.

  • How the TypeScript SDK exposes the request id on successful responses (property name) can vary by version; error bodies carry request_id.

  • Tail sampling in the OTel Collector is a contrib-distribution processor; check that your collector build includes it.

↑ ↓ सार्नुहोस् · ↵ छान्नुहोस् · esc बन्द