Modules 1 and 2 were about building agents and wiring them to the real world. This module is about knowing what they are doing once real traffic arrives, and about what you do when something goes wrong. The first half covers observability (what to record, what to alert on). The second half covers debugging and incident response (how to find the cause without guessing, and how to limit harm while you do it).
Everything Anthropic-specific below, such as response fields, request ids and streaming events, comes from the official documentation listed under Where to verify. The rest is standard engineering practice for any distributed system, applied to a component that is probabilistic and whose "success" is not an HTTP status.
3.1 One trace id across the whole request
A single user request in a Claude application usually touches many components: an auth check, a retrieval query, one or more model calls, several tool calls, and a post-processing step. When the answer is wrong, you need to see all of those as one story.
Principle. Generate one trace id at the edge (or accept one from the caller), and pass it through every component. Every log line, span and metric exemplar carries it. Model calls and tool calls are child spans of the request span.
Mechanism. Two kinds of identifier matter and they are not the same thing:
| Identifier | Who creates it | What it is for |
|---|---|---|
| Your trace id | Your application | Joining auth, retrieval, model calls, tools and the user-visible outcome |
| The API request id | Anthropic's API | Asking Anthropic support about one specific API call |
Every Claude API response carries a request-id header, and the same value appears as request_id in error response bodies. In the Python and TypeScript SDKs the id of a successful call is exposed as a _request_id property on the response object. Store it next to your trace id so that a trace can be joined to a support ticket. It does not replace your own id, because it only exists for calls that reached the API.
Figure 1. One trace id travels to every hop
How to read this: the edge creates the id once and every hop gets it. The dashed arrows are spans flowing into one store, so a single search returns the whole request.
Picture it: Think of the paper tag an airline clips to your suitcase. The same tag number is scanned at check-in, on the sorting belt, at the plane and at the carousel, so one lookup shows the whole journey. The API request id is more like the airline's number for a single flight leg: useful to its helpdesk, but it only exists once the bag is on that leg. Where it stops matching: nobody scans your trace id for you, your own code has to pass it along at every hop.
If a request is retried, each attempt is a separate API call with its own request id. Record every attempt as its own child span under the same trace, with an attempt number.
Exam angle. A scenario says users report wrong answers "sometimes" and the team only has per-service logs with no shared id. The best answer introduces a propagated trace id and structured spans across retrieval, model and tool steps. Common trap: adding more verbose logging inside the model-calling service only. More logs in one place cannot show you which document retrieval handed to the model or which tool call changed the state.
3.2 What to record on every model call
A model call span should carry a small, fixed set of dimensions. They let you slice every later question: which prompt version, which model, which outcome.
| Dimension | Source | Why it matters |
|---|---|---|
| Model identifier | Request and response model |
Model swaps are releases; compare before and after |
| Prompt version | Your own registry | Rollback and "did the prompt change?" answers |
stop_reason |
Response | Truncation, tool calls, refusals and normal ends look different |
| Token usage | Response usage |
Cost, latency and context-size trends |
| Latency (and time to first token if streaming) | Your clock | User experience and capacity |
| Feature, team or tenant | Your own metadata | Cost attribution and segment analysis |
The documented stop_reason values include end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal and model_context_window_exceeded. A refusal is returned as a normal HTTP 200 response rather than an error, so an HTTP-level dashboard will count it as a success. Only a metric keyed on stop_reason will show it.
Token usage needs care. With prompt caching, input_tokens is only the input that was neither read from nor written to a cache. The documented total is cache_read_input_tokens + cache_creation_input_tokens + input_tokens. If you chart input_tokens alone, a healthy cache looks like a cost collapse and a broken cache looks like normal.
import time
import anthropic
client = anthropic.Anthropic()
def traced_call(trace_id: str, prompt_version: str, feature: str, **params):
started = time.monotonic()
message = client.messages.create(**params)
log_event({ # log_event is your own structured logger
"trace_id": trace_id,
"request_id": message._request_id,
"feature": feature,
"prompt_version": prompt_version,
"model": message.model,
"stop_reason": message.stop_reason,
"input_tokens": message.usage.input_tokens,
"cache_read_tokens": message.usage.cache_read_input_tokens,
"cache_write_tokens": message.usage.cache_creation_input_tokens,
"output_tokens": message.usage.output_tokens,
"latency_ms": round((time.monotonic() - started) * 1000),
})
return message
Cost attribution. Your own per-call logs give per-feature and per-team cost, because you know the feature that made each call. For the organisation-wide view that finance reconciles against, Anthropic provides Admin API usage and cost reports (usage can be grouped by model, workspace and service tier, among others). These need an Admin API credential, the usage data typically arrives about 30 minutes after the request, and the docs mark that API as the legacy one with a newer analytics API recommended for new work. Use provider reports to reconcile, and your own tagged logs to attribute.
Exam angle. A scenario shows a flat HTTP 200 rate while a downstream team complains about missing answers. The answer adds stop_reason and an outcome label to the metrics. Common trap: "add an alert on 5xx errors". The failing responses are successful HTTP responses.
3.3 Infrastructure metrics versus quality metrics
Two different questions need two different families of metric.
| Family | Examples | Question it answers |
|---|---|---|
| Infrastructure | Request rate, error rate by status, latency percentiles, retry count, token throughput | Is the plumbing healthy? |
| Behaviour and quality | Task success rate, refusal rate, truncation rate (max_tokens), groundedness score from a sampled judge, escalation-to-human rate, user thumbs-down |
Is the system doing the job? |
Figure 2. A healthy API can still give bad answers
How to read this: the top path can be green while the bottom path is red. The quality proxies are fast, the judge is slower but deeper.
HTTP success is not task success. A call that returns 200 with a hallucinated policy answer, a refusal or a response cut off by max_tokens is a success to the load balancer and a failure to the user. Define a task-level outcome for every feature (for example, "the refund was created and the customer confirmed") and emit it as a metric.
Picture it: A restaurant kitchen has a dashboard showing every oven at the right temperature, every order leaving on time and no equipment faults. Meanwhile diners are sending plates back because the dish is cold or wrong. Equipment readings and diner reactions answer two different questions, and you need both. Where it stops matching: a bad model answer arrives looking like a successful order, so you have to go looking for it.
Quality metrics are usually computed on a sample, offline or by a calibrated judge (module 5), so they lag. Pair them with fast proxies you can compute on every request: refusal rate, truncation rate, schema-validation failure rate, tool-error rate.
Monday, support desk: Priya looks after the support tooling at Larkspur Insurance. Her dashboard is green: every call in the last hour returned HTTP 200 and latency is normal. Yet agents keep telling her that customers received no answer. She adds stop_reason to the metrics and finds that 120 of the last 1,000 calls ended with refusal, which is 12%. A prompt edit the day before had removed the sentence explaining that the assistant handles policy questions. The plumbing was fine; the feature was not. Invented example.
Exam angle. "Dashboards are green but the support team reports a spike in bad answers." The answer is to add behaviour metrics and sampled quality scoring next to the infrastructure ones. Common trap: scaling out or raising rate limits. Capacity is not the problem if the calls succeed.
3.4 Latency: time to first token versus total time
There are two numbers and they have different causes.
- Time to first token (TTFT): how long until the user sees anything. It is dominated by queueing, network, and processing the input prompt, so it grows with prompt size.
- Total completion time: TTFT plus generation. Generation time grows with the number of output tokens.
Streaming does not make the model finish sooner. It lets you show tokens as they arrive, so it improves perceived latency, not total time. To measure TTFT you must stream, and take the timestamp of the first content event.
Picture it: At a coffee shop, time to first token is how long until the barista looks up and starts your drink. Total time is how long until the cup is in your hand. Streaming is like watching the drink being made through the counter window: you see progress straight away, but the cup still lands in your hand at the same moment. Where it stops matching: streamed tokens are the real answer arriving in pieces, not a progress bar.
The documented event flow is message_start, then for each content block a content_block_start, any number of content_block_delta events and a content_block_stop, then one or more message_delta events and a final message_stop. ping events can appear anywhere. The usage counts in message_delta are cumulative. Errors can also arrive as an error event after the HTTP response has already started with status 200, for example an overloaded_error. With the SDK, the stream ends and your reading code gets an exception instead.
import time
def stream_with_ttft(**params):
started = time.monotonic()
first_token_ms = None
with client.messages.stream(**params) as stream:
for _text in stream.text_stream:
if first_token_ms is None:
first_token_ms = round((time.monotonic() - started) * 1000)
final = stream.get_final_message()
total_ms = round((time.monotonic() - started) * 1000)
return final, first_token_ms, total_ms
A stream that dies mid-way may have already shown partial text to the user. Treat a dropped or errored stream as a failed request in your metrics even though the HTTP status you saw was 200.
Worked example (illustrative numbers). An answer feature has TTFT 0.8 s. It generates 600 output tokens at 50 tokens per second, which is 12 s. Total is about 12.8 s. Halving the prompt might cut TTFT a little, but the large cost is generation. Asking for a shorter answer, or splitting the work, is what moves the total. If the complaint is "it feels frozen", streaming fixes perceived latency without changing the 12.8 s.
Figure 3. Where TTFT and total time are measured (illustrative numbers)
How to read this: the first note is the wait before anything appears, the second is the long middle. Streaming only changes when the reader starts seeing text, not when the last event arrives.
Exam angle. A scenario reports a "slow" feature and gives TTFT and generation figures. Read which part dominates before choosing. Common trap: switching on streaming to fix a total-time SLO. Streaming helps a perceived-latency target only.
3.5 SLOs, alert windows and segments
An SLO is a target for a user-facing indicator over a window. For Claude applications you need three kinds: latency (for example, 95th percentile TTFT), quality (task success or groundedness on the sampled set) and cost (spend per completed task).
Error budgets. A 99.5% success SLO over 30 days allows 0.5% failure. A 30-day month has 43,200 minutes, so the budget is 0.5% of that, or 216 minutes of full outage, or the equivalent in failed requests.
Burn-rate alerts with two windows. Alert on how fast the budget is being spent, using a short and a long window together. The short window (for example 5 minutes) makes the alert fast and lets it clear quickly. The long window (for example 1 hour) stops a brief blip from paging anyone. Page only when both are over threshold.
# Illustrative rule; thresholds are examples, tune them to your own SLO.
alert: ChatTaskSuccessBurn
when:
- task_failure_ratio[5m] > 14 * error_budget_ratio
- task_failure_ratio[1h] > 14 * error_budget_ratio
severity: page
Segment your metrics. An aggregate can sit comfortably inside the SLO while one segment is far outside it.
Worked example. Of 1,000,000 requests, 50,000 come from enterprise tenants. Enterprise tasks fail 20% of the time, which is 10,000 failures. The other 950,000 requests fail 1% of the time, which is 9,500. Total failures are 19,500, or 1.95% overall. The SLO says 2%, so the aggregate dashboard stays green while a customer tier sees one task in five fail. Slice by tier, tenant size, language, feature and model, and put SLOs on the segments that have contractual weight.
Picture it: A hotel reports that the average room temperature across the building is comfortable. One floor, the conference rooms, is freezing. The average is true and no use at all to the people on that floor. A separate thermostat and alarm per floor is what a segment SLO gives you. Where it stops matching: you choose the segments yourself, so pick the ones that carry contracts or risk.
Zero-tolerance signals. Some events should not be averaged at all. A failed tool call that enforces a safety property (an approval check, an authorisation lookup, a redaction step) should alert on a single occurrence. Record per-tool status (success, failure, timeout) as a metric, and give safety-critical tools a "any failure pages" rule rather than a ratio.
Exam angle. A scenario reports "overall quality is fine at 97%" while a customer segment complains. The answer is segment-level measurement and alerting. Common trap: lowering the aggregate threshold. That makes the alert noisier everywhere and still lets a small segment hide in the average.
3.6 Tool status, audit logs and privacy
Structured audit logs. For any action with consequences (refunds, data access, record changes), log who, what record, why and when, as structured fields, and log the outcome. "Why" means the stated reason or ticket and the trace id, not the model's chain of thought.
{
"ts": "2026-12-03T09:14:22Z",
"trace_id": "tr_8c1f",
"actor": {"user_id": "u_4412", "on_behalf_of_agent": "support-agent-v7"},
"action": "refund.create",
"record": {"type": "order", "id": "ord_9931"},
"reason": "ticket T-5520: duplicate charge",
"approval": "human:u_208",
"result": "ok"
}
Notice what is missing: the customer's card number, address and the full message text. Log identifiers that let an authorised person look the record up, not copies of sensitive values.
Privacy and retention. Prompts and responses can contain personal data. Decide what content you capture, why, who can read it, and when it is deleted. Capture content only where you need it (for example, for a sampled quality review), redact known patterns before storage, set a retention limit, and keep metrics (counts, token numbers, stop reasons) separate from content so metrics can live longer.
The same rule applies to any telemetry export built into developer tooling: check the vendor's monitoring documentation for which events are emitted and whether prompt text is included, and keep content logging off unless you have a reason and a retention policy for it.
Exam angle. A scenario asks for "a full record of every agent action for compliance" and mentions customer PII. The answer is structured audit records with identifiers and outcomes, access-controlled and retention-limited. Common trap: dumping complete prompts and responses into the general log index. That creates a second, unprotected copy of the sensitive data.
3.7 Classify the failure first
When something is wrong, the first step is to decide what kind of failure it is, because each kind has a different owner and a different fix.
| Class | Typical symptoms | First place to look |
|---|---|---|
| Infrastructure | Timeouts, 429s and 5xx, rising latency | API error rates and request_ids, retries, connection pools |
| Quality | Plausible but wrong or ungrounded answers, format drift | Retrieved context, prompt version, golden-set score |
| Safety | Disallowed content, leaked data, unauthorised action | Audit log, guardrail hits, tool permissions |
| Tool | Wrong or missing side effects, repeated tool errors | Per-tool status, tool input and output in the trace |
| Agent | Loops, wrong step order, abandoned tasks | Turn count, tool-call sequence, termination reason |
Follow the trace evidence: open the trace for a failing request and compare it with a healthy one. Look at what the model actually received (retrieved text, tool results, prompt version) before theorising about the model.
Figure 4. Classify the failure from the evidence
How to read this: follow the arrows from the top and stop at the first yes. Each box on the right names the first place to look and the owner of the fix.
Exam angle. A scenario gives a symptom and several "fixes" that each belong to a different class. The right answer is the one that matches the evidence. Common trap: changing the model or temperature before reading a single trace.
3.8 Isolate variables with a frozen golden set
When quality drops after a release that changed several things (prompt, model, retrieval settings), you cannot tell which change did it by arguing. Change one variable at a time against a frozen golden set: a fixed collection of inputs with expected outcomes (or graded by a fixed rubric) that never changes during the investigation.