Observability and evaluation for production AI
Step 12 of 14. A healthy service is not the same as a helpful answer. Measure the whole request path, trace it, and evaluate quality separately from uptime.
Observability and evaluation in 60 seconds
- Healthy is not helpful: a service can return success codes all day while giving colleagues wrong, slow or unauthorised answers.
- Three tools, three jobs: metrics tell you how the system is behaving, traces tell you where one request spent its time, and evaluations tell you whether the answers were any good.
- Percentiles, not averages: watch p50, p95 and p99. A pleasant average can hide a group of people who wait far too long.
- Quality has its own measures: correctness, groundedness, retrieval, workflow, tool use, safety and task success, tracked beside latency and cost.
- Telemetry is data too: redact it, restrict it and expire it. An alert without an owner and a runbook is only noise.
The problem it solves
Store Assist can go wrong in quiet ways. Retrieval may return last year's scanner guide. A stock lookup may wait on a slow service. A provider quota may run out mid-morning. A tool call may carry a malformed argument. The model may claim something the evidence does not support. A cached answer may have outlived its procedure.
If your only signal is that the model API answered, all of these look like success. Observability answers three plain questions. What happened on this request? Why? What should the team do next? This step builds the instruments for that, plus the evaluation habit that tells you whether answers were worth giving.
Metrics across the request lifecycle
Group your measurements by layer, so that a bad number points to a place rather than to a mood. Each layer has its own signals, and an owner who can act on them.
| Layer | What to watch | Example for Store Assist |
|---|---|---|
| User outcomes | Resolution, repeat questions, thumbs down, escalations, abandoned conversations | Share of scanner questions that end without a second attempt or a support desk handoff |
| Answer quality | Groundedness, correctness, citation validity, refusal accuracy | Groundedness on sampled live answers against the 95% target |
| Application | Request rate, error rate by type, queue age, cache hit rate, tool success | Stock lookup failures per minute, incident ticket creation success |
| Model and retrieval | Time to first token, full latency, tokens in and out, provider errors, retrieval hit rate | Tokens per request against the 1,000 in and 250 out plan |
| Infrastructure | CPU, memory, connection pools, network, dependency health | Connection pool use against the 70 in flight at peak |
| Cost | Spend per request and per resolved question | Against the £0.03 target |
Percentiles tell the truth about waiting
The p50 is the median experience. The p95 is the point that 95 in every 100 requests beat, and the p99 shows the long tail. Averages smooth these away. An average of three seconds sounds fine until one request in twenty takes eleven, clustered in stores opening at 08:00. Those colleagues have a different product from the one the dashboard describes.
- Record latency as a histogram, not a single mean, so you can read any percentile later.
- Split time to first token from full answer time. They have separate targets: under 1.5 s and under 8 s at p95.
- Slice by route, store group and time of day, since a tail on one route is a different problem from a tail everywhere.
- Alert on sustained movement, such as ten minutes above target.
Traces follow one request end to end
A distributed trace is the story of a single request as it moves through your services. Every stage becomes a span with a start time, a duration and an outcome. When someone says that an answer felt slow, the trace shows whether the time went to the gateway, retrieval, the model or a downstream business service.
For the scanner question, a healthy trace holds these spans in order:
- Identity check and permission lookup.
- Request classification, which chooses the path.
- Cache lookup, with hit or miss recorded.
- Retrieval search over the scanner sync guide, then reranking.
- The model call, with token counts and the model version.
- The live device-management lookup, with its own timing and result.
- Delivery of the final answer to the colleague.
Give every request one trace identifier at the edge and carry it everywhere. For asynchronous work, such as a queued ticket, copy the identifier into the job so both halves can be joined. Otherwise background work becomes an orphan nobody can explain.
Evaluating quality apart from health
Infrastructure numbers show components running. They cannot show that a colleague got a useful, supported and permitted answer. For that you need evaluations built around the behaviour promised in step 1.
Build the set from real work: ordinary procedure questions, vague ones, questions where the source is out of date, cases where a document must stay hidden from this role, and cases where the right move is a clarifying question or a handover to the store support desk.
| Dimension | Question it answers | How to check it |
|---|---|---|
| Correctness | Does the answer deal with what was asked? | Compare with a reference answer or a reviewer's rubric |
| Groundedness | Is every claim supported by the retrieved evidence? | Claim-by-claim check against the cited passages |
| Retrieval quality | Did the right source appear in the results? | Labelled relevant passages, recall at k |
| Workflow | Did the run take the route it was meant to? | Compare the trace route with the expected route |
| Tool correctness | Were the right tools called with valid arguments? | Assert on recorded tool calls |
| Safety and privacy | Did it avoid disclosing or doing what it should not? | Adversarial cases, access-control cases, injection cases |
| Task success | Was the colleague's problem actually solved? | Outcome signals plus sampled human review |
Automated judges, including a second model scoring the first, are useful for catching regressions at scale. They also make mistakes. Calibrate any judge against people before you trust it, and keep checking it as prompts and models change.
Keeping telemetry safe
Logs and traces can quietly become a second copy of everything colleagues said, every document retrieved and every tool response. Treat them as regulated data from the first day.
- Log enough to diagnose, not enough to expose. Identifiers, timings, versions, counts and outcomes are usually enough. Full prompt text rarely needs to be kept by default.
- Redact before storage, not after. Personal data, secrets and tokens should never reach the log pipeline.
- Restrict content access. Raw conversations sit behind a separate permission with an audit trail.
- Expire on a schedule, and never let tokens or keys into a trace attribute.
Turning monitoring into action
A dashboard earns its place only when a person can act on it. Alert on sustained provider errors, a queue whose oldest item keeps ageing, p95 above target, repeated retrieval failures, and spend nearing its budget line.
Give each alert an owner and a short runbook: what to check first, which actions are safe, and when to escalate. In the end the instruments must let you say three things. We are inside our limits. Outcomes are good and safe. If something breaks, we can find the cause and recover.
An SLO set for Store Assist
Service level objectives turn the targets from step 1 into numbers you can alert on. Keep availability and quality as separate objectives, because one can be perfect while the other fails.
| Objective | Target | Measured how | Owner |
|---|---|---|---|
| Availability in trading hours | 99.9% of requests answered without a server error | Gateway success rate, 08:00 to 18:00 | Platform |
| Time to first token | p95 under 1.5 s | Edge timestamp to first streamed byte | Platform |
| Full answer time | p95 under 8 s | Edge timestamp to final event | Platform |
| Groundedness | At least 95% on the golden set and on live samples | Offline run plus sampled judge scores | ML |
| Correct escalation | At least 98% of sensitive requests handed over | Labelled sensitive cases and live audits | Product and security |
| Cost per resolved question | Under £0.03 | Total spend over resolved conversations | Product |
| Data isolation | Zero cross-colleague exposures | Access tests in CI and audit review | Security |
Pair each objective with an error budget. At 99.9% over a 300-hour trading month, the budget is about 18 minutes of failure. When it is nearly spent, releases slow and reliability work comes first.
Designing the golden dataset
The golden dataset is a fixed collection of cases with known good outcomes. It is the yardstick every change is measured against, so treat it like code.
- Source cases from reality. Start with anonymised real questions and failures from support, then add synthetic cases for rare risks.
- Cover the risk tiers. Include read-only questions, personal-data questions such as holiday hours, write actions such as a till PIN reset, and refund requests over £150.
- Include traps. A supplier manual with hidden instructions, a withdrawn recall notice, the regional store closure plan that this role may not read, and a procedure that changed on Monday.
- Label the expected behaviour, including when the right answer is a refusal, a clarifying question or an escalation.
- Version it. Add every production failure as a case, and never drop one for being hard.
- Keep a hidden slice that prompt authors never see, to detect tuning to the test.
- Start near 300 cases, at least 20 per risk tier, and grow from incidents.
Calibrating a judge model and sampling live traffic
To calibrate, have two trained reviewers score a few hundred answers against the rubric. Measure how often they agree with each other, then how often the judge agrees with them. If the judge falls well short of human agreement, fix its instructions or use it for coarse triage only. Repeat whenever the judge, rubric or main prompt changes.
Offline sets cannot see new kinds of question. Sample live traffic too: score a small random share automatically, oversample thumbs-down and escalated conversations, and send a weekly slice to human reviewers. Stratify by store and route so small groups are not drowned out.
Alert runbooks and dashboards per audience
| Alert | Likely cause | First checks | Owner |
|---|---|---|---|
| Provider errors above 2% for 5 minutes | Quota or provider incident | Error split, quota headroom, failover state | Platform |
| Queue age above 60 s | Consumers behind | Consumer count, poison messages | Platform |
| Groundedness sample below 93% | Stale index or prompt change | Recent releases, index lag | ML |
| Any cross-colleague exposure | Filter or cache scope failure | Disable path, call security | Security |
Different people need different views. Support leads want resolution and escalation by store. Engineers want latency, errors and traces. ML engineers want quality and drift. Finance wants spend per resolved question. Build one small dashboard per audience and link them by trace identifier.
Store Assist, worked through
Take the scanner question again: "Why won't my handheld scanner sync since this morning's update?" At 08:12 a colleague in one store waits 11 seconds. The aggregate p95 looks fine at 6.4 s, so no alert fired. The colleague's trace shows a 5.2 s span on the device-management lookup, because a slow dependency queued behind the 08:00 surge.
- Metrics view: per-route p95 for the agent route sits at 9.1 s, above the 8 s target, while the simple route is at 2.4 s. Slicing by route reveals the issue.
- Trace view: the lookup span dominates. A tight timeout and a cached fallback of the last known device state would have cut the wait.
- Quality view: a 2% live sample shows groundedness at 96%, so the answer text was sound. The problem was speed, not truth.
- Cost view: the plan is 45M tokens a day. Telemetry shows 52M, so retries add about 15%.
- Action: the runbook sets a 1.5 s timeout on that lookup and raises a ticket for its owner.
Telemetry needs a budget too. At about 15 spans a request, 36,000 requests a day make 540,000 spans. Keep all error and slow traces and sample the healthy rest at 10%.
import re, time, uuid
SAMPLE_HEALTHY = 0.10 # keep 10% of healthy traces in full
SLOW_MS = 8_000 # always keep traces slower than the full-answer target
MAX_ATTR_CHARS = 200 # never store long raw text in a span attribute
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
LONG_NUMBER = re.compile(r"\b\d{6,}\b")
def redact(text: str) -> str:
"""Strip obvious personal data before anything reaches telemetry."""
text = EMAIL.sub("[email]", text)
text = LONG_NUMBER.sub("[number]", text)
return text[:MAX_ATTR_CHARS]
class Span:
def __init__(self, trace_id, name):
self.trace_id, self.name = trace_id, name
self.start = time.monotonic()
self.attrs = {}
def end(self, outcome, **attrs):
self.duration_ms = int((time.monotonic() - self.start) * 1000)
self.outcome = outcome
# Only identifiers, versions and counts by default, not raw content.
self.attrs = {k: (redact(v) if isinstance(v, str) else v) for k, v in attrs.items()}
return self
def handle(request, pipeline, exporter, rng):
trace_id = request.get("trace_id") or uuid.uuid4().hex # created at the edge
spans = []
for stage in pipeline: # classify, cache, retrieve, model, tools
span = Span(trace_id, stage.name)
try:
result = stage.run(request)
spans.append(span.end("ok", route=stage.name, version=stage.version))
except Exception as exc:
spans.append(span.end("error", error=type(exc).__name__))
raise
total = sum(s.duration_ms for s in spans)
has_error = any(s.outcome == "error" for s in spans)
# Keep every error and slow trace, sample the healthy rest.
if has_error or total > SLOW_MS or rng.random() < SAMPLE_HEALTHY:
exporter.send(trace_id, spans)
return result
The stages, exporter and random source are placeholders. The shape matters: one identifier from the edge, redaction before storage, and sampling that never drops the traces you most need.
Design decisions
- One identifier, everywhere. Mint the trace identifier at the edge, pass it through every service and queue job, and return it to the client so support can quote it.
- Standard schema. Agree span, attribute and metric names across teams.
- Sampling policy. Keep all errors, slow requests and escalations, sample the rest, and record the rate.
- Redaction at source. Use a shared library on the write path, not a clean-up job.
- Retention tiers. Raw content for days, traces for weeks, aggregates for a year or more.
Measuring it
- Judge agreement: how often the automated judge matches human consensus, by dimension.
- Golden set pass rate: per dimension and risk tier, trended across releases.
- Live sample scores: groundedness and correctness on a weekly random sample, with confidence intervals.
- Retrieval recall at k and mean reciprocal rank on labelled queries.
- Drift: shifts in question mix and rising unknown-intent rates.
When to use it, and how much of it
| Situation | Level of observability | Why |
|---|---|---|
| Internal pilot in 5 stores | Traces, core metrics, a small golden set, weekly human review | Cheap to run and enough to find the big problems early |
| Region-wide launch | Full SLOs, per-route percentiles, sampled live evaluation, on-call runbooks | Failures now affect thousands of colleagues and need an owner |
| Write actions and approvals enabled | Tool-level audit trail, tool correctness checks, security alerts | Wrong actions have real cost and must be traceable |
| Stable, low-risk read-only feature | Lighter sampling, fewer dashboards | Spend effort where the risk is |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Cost | Telemetry storage and judge-model calls add real spend | Sample healthy traffic and score a small share of live answers |
| Privacy | More detail helps debugging and widens exposure | Redact at source and restrict raw content |
| Speed of change | Evaluation gates slow releases a little | Keep the gate set small and fast, and run the full suite nightly |
| Effort | Sets and runbooks need upkeep | Fund it |
What this means for your role
Common mistakes
Step checklist
- One trace identifier is created at the edge and appears in every service, queue job and log line.
- p50, p95 and p99 are recorded for first token and full answer time, by route.
- Availability and answer quality have separate SLOs with named owners and error budgets.
- A versioned golden set exists with cases in every risk tier, traps included, and a hidden slice.
- Any judge model has a recorded agreement rate against human reviewers.
- Live traffic is sampled for quality scoring, with extra weight on thumbs-down and escalations.
- Redaction runs on the write path, raw content access is restricted, and retention is defined.
- Each alert has an owner and a runbook, and runbooks were tried in a drill.
- Dashboards exist per audience.
Further reading
- Evaluation and observability: the wider topic for AI systems.
- Distributed tracing: how spans and identifiers work.
- Observability: metrics, logs and traces as a set.
- Step 5: Guardrails and privacy: what must be kept out of logs.
- Step 3: Reference architecture: where each span comes from.
You now have eyes on the whole system. The next step is changing it safely, which means versioning every moving part and releasing in small, reversible steps. Next: Step 13: Release engineering.