The Restart Pattern
Every team I have worked with that runs agents in production without proper observability does the same thing when something breaks: they restart the agent and hope. A user reports a bad answer, a PM forwards a screenshot, someone tries to reproduce, fails, and the incident closes as "could not repro." A week later the same class of bug shows up again. The team adds another guardrail in the prompt, ships, and waits for the next ticket.
This is not debugging. It is superstition. You cannot fix what you cannot see.
The shift from "restart and hope" to "open the trace, see exactly what happened, run it again in staging" is the single largest productivity unlock I have seen in agentic systems. It is also the line between an AI feature that improves over time and one that quietly regresses until someone notices.
The Trace Is the Unit
Forget metrics for a moment. The primary unit of observability for an agent is the trace.
One user request equals one trace. Every LLM call inside that request, every tool call, every retrieval, every guardrail evaluation — each one is a span under that trace. A trace with one parent span and twelve children tells the whole story of what your agent did, in order, with inputs and outputs, latencies and costs, in the right hierarchy.
Metrics are aggregations of traces. Logs are span attributes. Alerts are queries against traces. Build the trace right and everything else falls out for free.
The OpenTelemetry GenAI semantic conventions stabilized in late 2024 and are now actually good. Use them. The temptation to roll your own attribute names ("model_id" vs "model_name" vs "llm.model" — I have seen all three in the same codebase) is the kind of decision you regret six months later when you switch from Langfuse to Datadog and discover none of your dashboards work.
The conventions to know:
gen_ai.system— "anthropic", "openai", "bedrock"gen_ai.request.model— "claude-sonnet-4-5-20250929"gen_ai.response.model— what the provider actually served (sometimes different)gen_ai.usage.input_tokens/gen_ai.usage.output_tokensgen_ai.response.finish_reasons— "stop", "tool_use", "max_tokens"gen_ai.request.temperature,gen_ai.request.max_tokens
These are the boring fields. They are also the fields that, when consistent across every span, let you ask questions like "what is the p95 latency of Sonnet calls when the prompt cache hits, broken down by tenant" without writing a parser.
The Fields That Actually Matter
On top of the OTel conventions, the attributes I have found load-bearing in real incidents:
| Attribute | Why it matters |
|---|---|
gen_ai.request.cache_read_tokens | Distinguishes a cache hit from a cold prompt. 90% of cost variance. |
agent.step_number | Which iteration of the agent loop. Catches runaway agents fast. |
agent.tool_calls_so_far | The agent's call budget consumption. Alert if it crosses 8. |
retrieval.recall_at_5 | Eval signal piggybacked on the live trace. Compare prod vs eval set. |
judge.score | Post-hoc LLM-as-judge score on the response. |
tenant.id (as attribute) | For filtering. Never as a metric label. See cardinality below. |
prompt.version | Which version of the system prompt was active. Catches deploy regressions. |
parent_span_id | The OTel-default. Without it, the trace is just a bag of events. |
The cache_read_tokens field deserves its own paragraph. Anthropic prompt caching makes a Sonnet call cost either $0.018 or $0.002 depending on whether the cache hit. If your traces do not surface that, you cannot tell whether a cost spike is from traffic growth or from someone introducing a non-deterministic field into the cached prefix. I have seen both. I have also seen a deploy that put a timestamp in the system prompt header and dropped the cache hit rate from 94% to 0% overnight, costing $4,200 in three days before anyone noticed.
Log the Payload, Not Just the Metadata
This is the part teams get wrong most often. They log token counts and latencies and finish reasons, and skip the input and output text because "it's too big" or "PII."
Storage is cheap. Debugging at 3am with no payload is not.
The rule I use: log the full input and full output for every error trace, and for a 10% sample of successful traces. Compress with zstd, store in S3 with a 90-day TTL, keep an index in your trace store that points to the blob. The compressed median is around 4KB per trace. At 200k traces per day, that is 80MB per day, $0.02 per day of S3, $7 per month. The eng-hour you save the first time you can replay a bad trace pays for the storage forever.
If you do not log the full payload, your dashboards will tell you that the agent took 4.2 seconds and called the search tool twice. They will not tell you why.
PII: Redact at Emission
The right place to redact PII is the moment the log line is created, not in the dashboard.
The wrong approach: store the raw input, render it in the dashboard, and apply a regex filter in the UI. Now your raw input is in your trace store, your blob store, your backups, and your compliance officer's nightmares.
The right approach: a redactor that runs inside the instrumentation wrapper, before the span is exported. Use a deterministic redaction key per tenant, so that the same email address always redacts to the same token across that tenant's traces. That preserves debuggability — you can still see that "user [email_a3f4]" appears in three different traces — without storing the email.
function redact(text: string, tenantId: string): string {
const key = redactionKey(tenantId); // HMAC key, stored in KMS
return text
.replace(EMAIL_RE, (m) => `[email_${hmac(key, m).slice(0, 4)}]`)
.replace(PHONE_RE, (m) => `[phone_${hmac(key, m).slice(0, 4)}]`)
.replace(CC_RE, "[card_redacted]");
}
The deterministic-token-per-tenant pattern is the difference between "we have logs but they're useless for debugging cross-trace user behavior" and "we can trace a single (redacted) user across a week of activity without storing their identity."
Cardinality Discipline
The fastest way to bankrupt yourself on observability is to put user_id in a metric label. At 100k users, a counter labeled by user_id has 100k time series in your metrics backend. Datadog will charge you for that. Prometheus will OOM. Honeycomb is more forgiving, but even there, high-cardinality labels turn into expensive aggregations.
The rule: high-cardinality fields go on the span as attributes. Low-cardinality fields go on metrics as labels.
| Field | Span attribute | Metric label |
|---|---|---|
tenant.id | Yes | Only if < 100 tenants |
user.id | Yes | Never |
request.id | Yes (auto) | Never |
agent.tool_name | Yes | Yes |
gen_ai.request.model | Yes | Yes |
prompt.version | Yes | Yes |
gen_ai.response.finish_reasons | Yes | Yes |
When in doubt, attribute. You can always aggregate up later. You cannot aggregate down from a metric to a trace.
The Four Signals to Alert On
I have tried alerting on every dimension at one time or another. The four that consistently catch real problems and ignore noise:
- Cost per request, p95, by feature. A sudden 2x rise almost always means a prompt cache miss, a retry loop, or a runaway agent. Threshold: 50% above 7-day baseline, sustained 15 minutes.
- Tool error rate, by tool. The agent will silently route around a broken tool by trying it three times and giving up. The user sees a worse answer. You see nothing — unless you alert. Threshold: 5% error rate sustained 10 minutes, per tool.
- Judge score, p50, by feature. If your offline LLM-as-judge runs on a 10% sample of prod traces, a drop in the median judge score from 0.85 to 0.78 over an hour is a regression. Threshold: 0.05 absolute drop, 1-hour window.
- End-to-end p95 latency. Agents add latency through retries and re-planning, not through individual call slowness. p95 catches it. p50 does not.
Notice what is not on this list: token counts, individual span latencies, exception rates from the SDK. Those are debugging signals, not alerting signals. Alerting on them creates noise that drowns the four signals above.
Sampling: Skew Toward the Failures
100% of error traces. 10% of successful traces. Full payload on errors, metadata-only on the unsampled successes.
The reason is asymmetric value. A successful trace tells you the system worked, which you already know from the metric. A failed trace contains the entire reason the system did not work. If you sample errors at 10% you will lose the trace that explains the production incident the one time it matters.
Honeycomb's dynamic sampling can do this cleanly with a few rules. Langfuse can do it via SDK config. Datadog LLM Observability defaults to 100% which is fine if you can afford it; below 1M traces/day, do not bother sampling at all and save yourself the operational complexity.
Replay Infrastructure
A trace is only useful if you can re-run it.
The pattern I use: every trace stores the exact (system_prompt, user_messages, tool_definitions, model, temperature, top_p, seed_if_any) that went into the LLM call, plus the actual response. A CLI command reads the trace by ID, reconstructs the call, and replays it against a configurable backend — staging, a different model, a different prompt version.
$ agent-replay trace_01HXJ2K4Q --against staging --prompt v17
Original: claude-sonnet-4-5, prompt v15, judge=0.62 (FAIL)
Replay: claude-sonnet-4-5, prompt v17, judge=0.91 (PASS)
Diff written to /tmp/trace_01HXJ2K4Q.diff
This single command turns "could not repro" into a 90-second feedback loop. It also turns the prompt-iteration workflow from "edit, deploy to staging, hope someone hits the case" into "pull 50 failed traces from last week, replay them all against the new prompt, look at the diff."
Build this on day one. Or on day thirty, when you have spent a week trying to reproduce a bug a customer reported in a screenshot.
A Concrete Instrumentation Snippet
The minimum viable wrapper around an Anthropic call, in TypeScript with OpenTelemetry:
import { trace, SpanStatusCode } from "@opentelemetry/api";
import Anthropic from "@anthropic-ai/sdk";
const tracer = trace.getTracer("agent");
const client = new Anthropic();
export async function callClaude(
params: Anthropic.MessageCreateParams,
ctx: { tenantId: string; promptVersion: string; stepNumber: number }
) {
return tracer.startActiveSpan("gen_ai.chat", async (span) => {
span.setAttributes({
"gen_ai.system": "anthropic",
"gen_ai.request.model": params.model,
"gen_ai.request.max_tokens": params.max_tokens,
"gen_ai.request.temperature": params.temperature ?? 1.0,
"tenant.id": ctx.tenantId,
"prompt.version": ctx.promptVersion,
"agent.step_number": ctx.stepNumber,
});
try {
const t0 = performance.now();
const res = await client.messages.create(params);
const latencyMs = performance.now() - t0;
span.setAttributes({
"gen_ai.response.model": res.model,
"gen_ai.usage.input_tokens": res.usage.input_tokens,
"gen_ai.usage.output_tokens": res.usage.output_tokens,
"gen_ai.usage.cache_read_input_tokens":
res.usage.cache_read_input_tokens ?? 0,
"gen_ai.usage.cache_creation_input_tokens":
res.usage.cache_creation_input_tokens ?? 0,
"gen_ai.response.finish_reasons": [res.stop_reason ?? "unknown"],
"gen_ai.latency_ms": latencyMs,
});
// Payload capture: 100% on error path, 10% sample on success.
if (shouldCapturePayload(span)) {
await capturePayload(span.spanContext().traceId, {
input: redact(JSON.stringify(params.messages), ctx.tenantId),
output: redact(JSON.stringify(res.content), ctx.tenantId),
});
}
return res;
} catch (err) {
span.setStatus({ code: SpanStatusCode.ERROR, message: String(err) });
span.recordException(err as Error);
await capturePayload(span.spanContext().traceId, {
input: redact(JSON.stringify(params.messages), ctx.tenantId),
error: String(err),
});
throw err;
} finally {
span.end();
}
});
}
A few things to note. The cache_read_input_tokens and cache_creation_input_tokens are the fields you actually need to compute true cost — input_tokens is the cache-miss count only. The payload is captured to a separate store (S3 or the trace store's blob backend) keyed by traceId, not stuffed into the span itself — span attributes have size limits in most exporters. The redaction happens before capture, so the blob store never sees raw PII.
This is the minimum. The full version adds idempotency keys, request_id propagation, retry instrumentation, and a gen_ai.cost_usd derived attribute. It also wraps each tool call in its own span, with gen_ai.tool.name and the tool's input/output JSON captured the same way.
Honest Tool Review
I have used or audited each of these in production.
Langfuse. The best default for most teams. Prompt management, eval workflows, full payload capture, and the data model maps cleanly to traces and spans. Their open-source version is genuinely usable if you can run Postgres + Clickhouse. The downside is that the alerting story is weak — you will end up forwarding metrics to Datadog or Grafana anyway.
Helicone. Cheaper and simpler. Good for proxying calls and capturing basic traces. Weaker on agent workflows where one request is twelve spans. Their newer features have closed some of the gap, but Langfuse is still ahead on agent traces.
Honeycomb. The best general-purpose observability tool for high-cardinality data. You have to instrument it yourself with OpenTelemetry, but once you do, the query experience for "find me the slowest traces last Tuesday where the tenant was X and the prompt version was Y" is unmatched. The eval and prompt-management story is missing — pair with Langfuse for that.
Datadog LLM Observability. The easy choice if you are already on Datadog. The data model is reasonable, the dashboards are fine, and the alerting integrates with everything else. It is expensive at scale and the prompt-eval workflow is the weakest of the four. Good for teams where the platform-engineering org has standardized on Datadog and a separate AI observability tool is politically dead on arrival.
For a new team, I default to: Langfuse for traces, evals, and prompts, plus Honeycomb or Grafana Cloud for alerting and SRE-style dashboards. The two together cost less than Datadog alone and the data model is better.
What Didn't Work
We once tried to skip the trace store entirely and just dump every LLM call to Postgres with a JSONB column for inputs and outputs. The reasoning was that Postgres is operationally familiar, queryable in SQL, and we already had it.
It worked for about six weeks. Then the table hit 200M rows, the JSONB GIN index started taking 40 minutes to vacuum, and a query for "all errors from tenant X last week" took 90 seconds. Worse, we had no concept of a trace hierarchy — every row was a standalone LLM call. Reconstructing a single user request meant joining on a request_id and ordering by timestamp, and the order was sometimes wrong because two spans had identical timestamps to the millisecond.
We migrated to OpenTelemetry plus Langfuse over a long weekend. Query latency dropped to 200ms. We deleted the Postgres table and freed up 800GB. The lesson was not "Postgres is bad" — it was "trace data has a shape, and storing it in a row-oriented store throws away the shape." Use a tool built for the shape.
A Closing Note
If you cannot replay last Tuesday's bad response, you do not have an observable system. You have a guess.