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.

Measure in layers so a bad number points at a place, and use one trace identifier to join them.
LayerWhat to watchExample for Store Assist
User outcomesResolution, repeat questions, thumbs down, escalations, abandoned conversationsShare of scanner questions that end without a second attempt or a support desk handoff
Answer qualityGroundedness, correctness, citation validity, refusal accuracyGroundedness on sampled live answers against the 95% target
ApplicationRequest rate, error rate by type, queue age, cache hit rate, tool successStock lookup failures per minute, incident ticket creation success
Model and retrievalTime to first token, full latency, tokens in and out, provider errors, retrieval hit rateTokens per request against the 1,000 in and 250 out plan
InfrastructureCPU, memory, connection pools, network, dependency healthConnection pool use against the 70 in flight at peak
CostSpend per request and per resolved questionAgainst 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.

A waterfall shows where one request spent its time, so a slow answer can be traced to a single stage.

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.

DimensionQuestion it answersHow to check it
CorrectnessDoes the answer deal with what was asked?Compare with a reference answer or a reviewer's rubric
GroundednessIs every claim supported by the retrieved evidence?Claim-by-claim check against the cited passages
Retrieval qualityDid the right source appear in the results?Labelled relevant passages, recall at k
WorkflowDid the run take the route it was meant to?Compare the trace route with the expected route
Tool correctnessWere the right tools called with valid arguments?Assert on recorded tool calls
Safety and privacyDid it avoid disclosing or doing what it should not?Adversarial cases, access-control cases, injection cases
Task successWas 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.

ObjectiveTargetMeasured howOwner
Availability in trading hours99.9% of requests answered without a server errorGateway success rate, 08:00 to 18:00Platform
Time to first tokenp95 under 1.5 sEdge timestamp to first streamed bytePlatform
Full answer timep95 under 8 sEdge timestamp to final eventPlatform
GroundednessAt least 95% on the golden set and on live samplesOffline run plus sampled judge scoresML
Correct escalationAt least 98% of sensitive requests handed overLabelled sensitive cases and live auditsProduct and security
Cost per resolved questionUnder £0.03Total spend over resolved conversationsProduct
Data isolationZero cross-colleague exposuresAccess tests in CI and audit reviewSecurity

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

AlertLikely causeFirst checksOwner
Provider errors above 2% for 5 minutesQuota or provider incidentError split, quota headroom, failover statePlatform
Queue age above 60 sConsumers behindConsumer count, poison messagesPlatform
Groundedness sample below 93%Stale index or prompt changeRecent releases, index lagML
Any cross-colleague exposureFilter or cache scope failureDisable path, call securitySecurity

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%.

A traced request with redaction and bounded telemetry (illustrative) (python)
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

SituationLevel of observabilityWhy
Internal pilot in 5 storesTraces, core metrics, a small golden set, weekly human reviewCheap to run and enough to find the big problems early
Region-wide launchFull SLOs, per-route percentiles, sampled live evaluation, on-call runbooksFailures now affect thousands of colleagues and need an owner
Write actions and approvals enabledTool-level audit trail, tool correctness checks, security alertsWrong actions have real cost and must be traceable
Stable, low-risk read-only featureLighter sampling, fewer dashboardsSpend effort where the risk is

Trade-offs

DimensionEffectWhat to do about it
CostTelemetry storage and judge-model calls add real spendSample healthy traffic and score a small share of live answers
PrivacyMore detail helps debugging and widens exposureRedact at source and restrict raw content
Speed of changeEvaluation gates slow releases a littleKeep the gate set small and fast, and run the full suite nightly
EffortSets and runbooks need upkeepFund 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

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.

Search topics

↑↓ to move · Enter to open · Esc to close