By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
A misbehaving run leaves evidence in three places, and each answers a different question. A trace answers "why did this request do that?" — one tree of model and tool spans with inputs, outputs and timings. A metric answers "is the system healthy right now?" — cheap aggregated numbers. A log answers "what exactly happened at this point?" — a timestamped event. Lesson 11 set up tracing and Lesson 12 asserted trace shapes; this lesson is the operating review: what to record, what to aggregate, and what deserves a page.
| Signal | Question it answers | Keep it | Cost |
|---|---|---|---|
| Trace | Why did this request do that? | One tree per request, with model, tool and retrieval spans | Detailed and sampled |
| Metric | Is the system healthy now? | Error rate, p95 latency, tokens, fallback rate, cache hit rate | Cheap and aggregated |
| Log | What exactly happened at this point? | Request id, model, prompt version, step, decision, error class | Verbose but searchable |
Use all three, but do not use one as another. A metric with a request id as a label is a cardinality bomb; a trace used as a dashboard is too detailed to read; a log line with no request id is a coincidence. The request id is what lets you move between them.
The request id from Lesson 19 is the join key. Put it in the response header, in every log line and in the trace metadata, and keep it on the ticket so a customer screenshot maps to exactly one trace. Put the thread id, prompt version and model name there too: those are the four fields you will filter on at 2 a.m. tags and metadata in a RunnableConfig are inherited by child spans, so one object labels the whole request.
from langchain.messages import HumanMessage
# The edge from Lesson 19 supplies these values; nothing here calls a provider.
request_id = "req-7f3c9a"
config = {
"run_name": "support_turn",
"tags": ["support", "ticket-4521"],
"metadata": {
"request_id": request_id,
"thread_id": "thread-4521",
"prompt_version": "support-v7",
"model": "gpt-4.1-mini",
},
}
# agent is the compiled create_agent runtime from the earlier lessons.
result = agent.invoke(
{"messages": [HumanMessage("Can I still refund a damaged mug?")]},
config=config,
)Log the identifiers and decisions, not the contents. Full prompts, retrieved passages and tool payloads belong on a redacted trace with retention and access control, not in an application log that gets shipped somewhere cheap. The redaction boundary from Lesson 22 applies before the first log line, not after the incident review.
Responses carry usage metadata — input and output tokens, plus provider details when offered — and every paid call should land on a per-request record. Sum it per request, per thread, per day and per model. Separate input from output tokens because they price differently, count retried and fallback calls because they were paid for too, and record cache reads where the provider reports them. Then pair spend with value: cost per resolved ticket is the number a manager can act on; tokens per step is the number an engineer can debug.
An average hides the tail. A support turn at 1.2 seconds p50 and 9 seconds p99 feels broken to the one customer in a hundred, while the average still looks fine. Record latency per span — model, tool, retrieval — and compute p50, p95 and p99 from a histogram. Split by model and by tool, because a single slow dependency usually owns the tail. Page on the tail; file a ticket on the median. Streaming improves perceived speed but not the p95 of the full answer, so measure time-to-first-token separately from total time.
import math
RUNS = [
{"request_id": "req-1001", "latency_ms": 820, "in_tokens": 1100, "out_tokens": 350, "status": "ok"},
{"request_id": "req-1002", "latency_ms": 940, "in_tokens": 1250, "out_tokens": 410, "status": "ok"},
{"request_id": "req-1003", "latency_ms": 780, "in_tokens": 980, "out_tokens": 300, "status": "ok"},
{"request_id": "req-1004", "latency_ms": 1600, "in_tokens": 1400, "out_tokens": 520, "status": "ok"},
{"request_id": "req-1005", "latency_ms": 2100, "in_tokens": 1500, "out_tokens": 600, "status": "error"},
{"request_id": "req-1006", "latency_ms": 900, "in_tokens": 1120, "out_tokens": 380, "status": "ok"},
{"request_id": "req-1007", "latency_ms": 1100, "in_tokens": 1180, "out_tokens": 420, "status": "ok"},
{"request_id": "req-1008", "latency_ms": 850, "in_tokens": 1050, "out_tokens": 330, "status": "ok"},
]
def p95(values: list[int]) -> int:
"""Nearest-rank p95: the first value at or above 95% of the sample."""
ordered = sorted(values)
return ordered[max(0, math.ceil(0.95 * len(ordered)) - 1)]
tokens = sum(run["in_tokens"] + run["out_tokens"] for run in RUNS)
errors = sum(run["status"] != "ok" for run in RUNS)
latencies = [run["latency_ms"] for run in RUNS]
print(f"runs={len(RUNS)} errors={errors} tokens={tokens}")
print(f"p95_ms={p95(latencies)}")
status = "yes" if errors / len(RUNS) > 0.02 or p95(latencies) > 1500 else "no"
print(f"alert={status}")Wire the evaluation suite from Lesson 18 into a scheduled job and store its report: mean score per category, trajectory failures, safety failures, cost and latency per case, keyed by prompt version and model. A dashboard that shows traffic and latency but not quality will look healthy while the answers get worse. Link every failed case to its trace so a review can move from "the score dropped" to "this tool call changed" in one click instead of a morning.
Alert on symptoms a customer can feel, and keep the causes for the review. These are starting points, not universal thresholds; set the numbers from a week of your own traffic.
| Alert | Example threshold | Why page someone |
|---|---|---|
| Error rate | Above 2% over 10 minutes | Customers are getting failures now |
| p95 latency | Above 15 seconds over 10 minutes | The tail is already painful |
| Fallback rate | Above 5% of model calls | The primary provider is degraded and quality may change |
| Provider 429s | Any sustained burst | Rate limits become errors; check quota and queue |
| Token spend | Above 120% of the daily burn rate | A loop or a runaway thread is spending money |
| Eval score | Drop of 5 points versus the last accepted run | A prompt, model or tool change regressed quality |
| Approval backlog | Oldest pending request above 1 hour | Writes are stuck and customers are waiting |
| Zero traffic | No runs for 10 minutes during business hours | The service is down even though the process is up |
Key takeaways
Traces explain one request, metrics describe system health, and logs show exact events; the request id is the join key across all three.
Put the request id, thread id, prompt version and model on every request, but never in metric labels — keep high-cardinality ids in traces and logs.
Account for tokens per request, thread, day and model, including retries and fallbacks, and pair spend with cost per resolved ticket.
Page on error rate, p95 tail latency, spend burn, eval regressions and stuck approvals; alert on symptoms and keep traces for the cause.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.