LLM Evaluation and Observability Questions
Measuring, monitoring and releasing generative and LLM-powered systems. Covers evaluation of open-ended outputs (human review, calibrated model-graded judges, reference-based and embedding scores, perplexity), hallucination, toxicity, privacy-leak and red-team checks, offline benchmarks versus online monitoring, and production observability (logs, traces, metrics, cost and token attribution, privacy-safe telemetry, drift and quality alerts). Also release decisions: A/B tests, canary rollouts, SLOs and go or no-go gates. Building the grounding architecture itself, calibration of predictive models and general software testing are covered elsewhere.
How would you instrument token usage and cost attribution for a multi-tenant LLM API? What labels belong on each request, how do you handle streaming responses, and how do you present the data?
Sample Answer
Direct answer
Record usage per request, as the provider reports it, in an append-only ledger (a table to which rows are only ever added, never edited, so history can be audited), and attach a fixed set of labels: tenant, project or API key, route or feature, model, model version, request id, region, and whether the call was streamed and completed. Count input tokens, cached input tokens and output tokens separately, because they are priced differently. Cached input tokens are input tokens that the provider served from a stored copy of an earlier, identical prompt prefix instead of processing again; providers typically bill them at a lower rate, so check your provider's pricing documentation. In this ledger input counts only the uncached input tokens and cached_input the cached ones, as separate lines that add up: request r1 costs 1,200 x 1.0/1000 + 800 x 0.1/1000 + 300 x 4.0/1000 = 1.2 + 0.08 + 1.2 = 2.48 in the placeholder units below. Providers report usage in different ways, so confirm in your provider's usage documentation whether its input count already includes the cached part, and subtract it before storing if it does. Cost is computed later from a versioned rate table, never stored as the only truth. Present the data as per-tenant cost over time, split by feature, with a reconciliation line against the provider invoice.
What belongs on each request
| Field | Why |
|---|---|
| tenant_id, api_key_id | chargeback (billing a customer or internal team for the cost it causes) and per-tenant limits |
| route or feature name | which product surface drove the spend |
| model and model version | prices and quality differ by model |
| input_tokens, cached_input_tokens, output_tokens | separate rates |
| streamed, completed, finish_reason (why generation stopped, for example it ended normally, hit the output limit or was cancelled) | explains partial and cancelled calls |
| request_id, trace_id | joins cost to latency and errors |
Keep labels low-cardinality where they feed metrics (tenant, route, model). Put request id and user id in the ledger row and traces, not in metric labels, because every distinct combination of label values is its own time series (one stored sequence of values over time), so the series count is the product of the number of values of each label. The last line of the program prints an example.
Streaming responses
A streamed answer arrives in chunks, and the authoritative token counts usually arrive in a final usage frame (the last message of the stream, which carries the token counts), if the provider sends one. Three cases:
- Stream completes with a usage frame: use the reported numbers.
- Client disconnects or the stream errors before the final frame: the provider may still have generated (and billed) tokens. Write the row anyway, with
completed = false, count the output tokens you did stream with a stand-in estimate, and markestimated = true. - Retries: a retried request is a new billable call. Give each attempt its own row linked by an idempotency key (a unique id the client attaches to one logical request, so every retry of it is recognised as the same request) so a retry storm is visible, not hidden.
The program below builds a four-request ledger. Its token estimator is a stand-in (words times 1.3), used only when the provider's usage is missing; a real system would use the provider's reported count or the tokenizer that matches the model. Costs use placeholder rates in arbitrary units per 1,000 tokens, not real prices.
import pandas as pd
RATES = {"input": 1.0, "cached_input": 0.1, "output": 4.0} # placeholder cost units per 1,000 tokens, not real prices
def approx_tokens(text): # stand-in tokenizer: whitespace words * 1.3, only used when provider usage is missing
return round(len(text.split()) * 1.3)
def ledger_row(req_id, tenant, route, model, usage, streamed_text=None, completed=True, input_known=None):
est = False
if usage is None: # stream cut before the final usage frame; input tokens are known from the request we sent
usage = {"input": input_known, "cached_input": 0, "output": approx_tokens(streamed_text)}
est = True
cost = sum(usage[k] * RATES[k] / 1000 for k in RATES)
return dict(req_id=req_id, tenant=tenant, route=route, model=model, completed=completed, estimated=est, cost=cost, **usage)
rows = [
ledger_row("r1", "acme", "/chat", "model-a", {"input": 1200, "cached_input": 800, "output": 300}),
ledger_row("r2", "acme", "/chat", "model-a", {"input": 1500, "cached_input": 0, "output": 500}),
ledger_row("r3", "globex", "/summarize", "model-b", {"input": 4000, "cached_input": 3000, "output": 200}),
ledger_row("r4", "globex", "/chat", "model-a", None, streamed_text="word " * 120, completed=False, input_known=900),
]
df = pd.DataFrame(rows)
print(df[["req_id", "tenant", "route", "completed", "estimated", "input", "cached_input", "output", "cost"]].to_string(index=False))
print()
print(df.groupby(["tenant", "route"])[["input", "cached_input", "output", "cost"]].sum().round(3).to_string())
print()
total = df.cost.sum()
provider_invoice = 13.0 # pretend provider invoice in the same placeholder units
print(f"ledger total {total:.3f}, invoice {provider_invoice:.3f}, unattributed {provider_invoice-total:.3f} ({(provider_invoice-total)/provider_invoice:.1%})")
print(f"estimated rows: {int(df.estimated.sum())} of {len(df)}, cost share {df[df.estimated].cost.sum()/total:.1%}")
print(f"label combinations: 3 tenants x 4 routes x 3 models = {3*4*3} series; with a user-id label of 10,000 values = {3*4*3*10_000:,}")
Output:
req_id tenant route completed estimated input cached_input output cost
r1 acme /chat True False 1200 800 300 2.480
r2 acme /chat True False 1500 0 500 3.500
r3 globex /summarize True False 4000 3000 200 5.100
r4 globex /chat False True 900 0 156 1.524
input cached_input output cost
tenant route
acme /chat 2700 800 800 5.980
globex /chat 900 0 156 1.524
/summarize 4000 3000 200 5.100
ledger total 12.604, invoice 13.000, unattributed 0.396 (3.0%)
estimated rows: 1 of 4, cost share 12.1%
label combinations: 3 tenants x 4 routes x 3 models = 36 series; with a user-id label of 10,000 values = 360,000
Reading the output:
- Request r4 is the special row: its stream was cut before the usage frame, so the program takes input tokens from
input_known(the count the gateway already had from the request it sent) and estimates output tokens from the text streamed so far. It is a cancelled stream: 900 input tokens known, 156 output tokens estimated (120 words times 1.3, rounded). It is flaggedestimated, and that row is 12.1% of ledger cost, so the dashboard should show estimated cost separately. - The aggregation by tenant and route shows acme /chat at 5.980 and globex split between /chat (1.524) and /summarize (5.100). Cached input tokens cost a tenth as much in this rate table, so r3's 3,000 cached tokens matter: a cache hit rate belongs on the dashboard.
- Reconciliation: ledger total 12.604 against an invoice of 13.000 (a made-up figure in the same units) leaves 0.396 unattributed, 3.0%. Track that gap daily; a growing gap means missed rows (dropped events, an unlabelled service) or a changed price.
Presenting it
- Tenant view: spend by day, by feature, tokens per request, cache hit rate, with budget lines and soft alerts at 50%, 80% and 100% of quota.
- Internal view: cost per tenant against revenue per tenant (margin), top routes by spend, p95 tokens per request by route, and the estimated-cost share.
- Rules: show input and output separately, show cached tokens, say which figures are estimates, and let finance export the ledger.
Pitfalls
Storing computed dollars without the rates used (you cannot restate history when prices change); summing only completed requests and missing cancelled streams; hiding the unattributed gap; attributing shared costs (a long system prompt cached for everyone) to one tenant without a stated allocation rule.
Which telemetry signals would you capture to monitor LLM behavior in production? For each, say which failure modes it helps detect, how you would aggregate and store it, and what its limits are.
Sample Answer
Direct answer
Capture signals in four families: system (latency, errors, tokens, cost), input and output content (prompts, retrieved context, replies), quality (groundedness, meaning every claim in the reply is supported by the retrieved text; safety flags; format validity; drift in output statistics) and user feedback (thumbs, edits, retries, abandonment). Each one detects a different failure; no single signal covers them all. Store cheap numeric aggregates for everything and full content only for a sample plus every flagged request, because raw content is large, private and mostly uninteresting.
Signal by signal
| Signal | Failure modes it helps detect | Aggregate and store | Limits |
|---|---|---|---|
| Latency per span, time to first token (the wait until the first word appears) | Slow retrieval, provider slowdown, runaway generation | Histograms with fixed buckets (counts that can be added across servers; explained below); keep p50, p95, p99 | Says nothing about quality; a fast wrong answer looks healthy |
| Error, timeout, retry and rate-limit counts | Provider outages, quota exhaustion, broken tool calls | Counters by error class and model version | Silent quality failures return success |
| Token counts and cost | Prompt bloat, runaway loops, a template change that doubled the context | Sums and histograms of input and output tokens per feature and per user segment | A cost spike shows that something changed, not what |
| Output length and refusal rate | Sudden terse or verbose replies; over-refusal after a safety change | Daily distributions; a population stability index against a baseline | A shift is a symptom; quality may have improved or worsened |
| Groundedness or citation check on sampled replies | Hallucination in retrieval-based features | Pass rate per day and slice; full records for failures | Needs a judge with known error rates; context that is wrong passes |
| Safety and policy flags | Toxic output, leaked private data, injection symptoms | Counts per category; raw text only for flagged items, with access control | Classifiers miss novel phrasing and over-flag quoted speech |
| Format validity (JSON parses, schema fits) | Broken structured output that breaks downstream code | Pass rate; failure samples | A valid format can hold wrong content |
| Retrieval scores and empty-result rate | Index staleness, query rewriting errors | Score histograms; share of requests with no good passage | A high score does not mean the passage answers the question |
| User feedback and behaviour (thumbs, regenerate clicks, edits, session abandonment) | Real-world dissatisfaction no test set covered | Rates per slice with the trace id attached | Sparse and biased toward unhappy users |
| Version tags (model, prompt, index) | Cause of a regression | Attached to every trace | Only useful if recorded consistently |
Aggregation pitfalls, computed
Three terms first. A percentile is the value that a given share of requests beat: p50 is the median, p95 is the time 95 percent of requests beat, and p99 = 2163 ms would mean 99 requests in 100 finish faster than 2.2 seconds, so 1 user in 100 waits longer. Percentiles describe the slow tail that an average hides. A mergeable histogram counts how many requests fell into each of a fixed set of latency ranges (buckets); counts from different servers or minutes can simply be added bucket by bucket, whereas two p99 numbers cannot be combined into one. PSI, the population stability index, compares two distributions bucket by bucket: for each bucket take (new share minus old share) times the natural log of (new share divided by old share), and add them up. On two buckets by hand, shares 0.7 and 0.3 that become 0.5 and 0.5 give (0.5 - 0.7) x ln(0.5/0.7) + (0.5 - 0.3) x ln(0.5/0.3) = 0.0673 + 0.1022 = 0.1695 (the program prints it). A widely used rule of thumb, which comes from credit-risk scorecard monitoring and is not a standard, reads PSI below 0.1 as little change, 0.1 to 0.25 as moderate and above 0.25 as a large shift; the cut-offs shift with sample size and with how the buckets are drawn, so treat them as guidelines.
The program uses a seeded synthetic stream (invented numbers, not data from a real system): ten one-minute windows of 1000 request latencies, where minute 7 has a burst of slow retries. It shows why you store mergeable histograms rather than per-window percentiles, and how an output-length shift appears as a population stability index (PSI, defined above).
import os
os.environ["OMP_NUM_THREADS"] = "1"; os.environ["OPENBLAS_NUM_THREADS"] = "1"
import numpy as np
rng = np.random.default_rng(0)
# 10 one-minute windows x 1000 requests. Latency in ms (lognormal body); minute 7 has 8% slow retries.
mins = []
for m in range(10):
x = rng.lognormal(mean=np.log(800), sigma=0.35, size=1000)
if m == 7:
slow = rng.random(1000) < 0.08
x[slow] *= 6
mins.append(x)
allx = np.concatenate(mins)
print("pooled mean %.0f p50 %.0f p95 %.0f p99 %.0f" % (allx.mean(), *np.percentile(allx, [50, 95, 99])))
per_min_p99 = np.array([np.percentile(x, 99) for x in mins])
print("per-minute p99:", np.round(per_min_p99).astype(int).tolist())
print("mean of per-minute p99: %.0f (pooled p99 above)" % per_min_p99.mean())
# Fixed log-spaced histogram (the mergeable summary a metrics store keeps)
edges = np.geomspace(100, 20000, 41)
def hist(x): return np.histogram(x, bins=edges)[0]
merged = sum(hist(x) for x in mins)
def hist_pct(h, q):
c = np.cumsum(h); i = int(np.searchsorted(c, q * c[-1]))
return edges[i + 1] # upper edge of the bucket holding the quantile
print("histogram p99 from merged buckets: %.0f" % hist_pct(merged, 0.99))
print("buckets stored per window:", len(merged))
# Output-length drift: share of replies per length bucket, week 1 vs week 2, PSI.
w1 = rng.normal(180, 40, 5000).clip(5); w2 = rng.normal(150, 55, 5000).clip(5)
bins = [0, 100, 150, 200, 250, 1000]
p = np.histogram(w1, bins)[0] / 5000; q = np.histogram(w2, bins)[0] / 5000
psi = float(np.sum((q - p) * np.log(q / p)))
print("length bucket shares week1:", np.round(p, 3).tolist())
print("length bucket shares week2:", np.round(q, 3).tolist())
print("PSI = %.3f" % psi)
# Storage arithmetic with stated assumptions
req_per_day = 1_000_000; raw_kb = 6; kept_fraction = 0.02
print("raw traces for every request: %.1f GB/day" % (req_per_day * raw_kb / 1e6))
print("traces for 2%% sample plus all flagged (assume 1%%): %.2f GB/day" % (req_per_day * (kept_fraction + 0.01) * raw_kb / 1e6))
# PSI by hand on two buckets: shares [0.7, 0.3] become [0.5, 0.5]
p2, q2 = np.array([0.7, 0.3]), np.array([0.5, 0.5])
terms = (q2 - p2) * np.log(q2 / p2)
print("two-bucket PSI terms", np.round(terms, 4).tolist(), "total %.4f" % terms.sum())
Output:
pooled mean 885 p50 798 p95 1467 p99 2163
per-minute p99: [1745, 1762, 1715, 1916, 1740, 1863, 1772, 7395, 1850, 1829]
mean of per-minute p99: 2359 (pooled p99 above)
histogram p99 from merged buckets: 2402
buckets stored per window: 40
length bucket shares week1: [0.021, 0.2, 0.462, 0.278, 0.038]
length bucket shares week2: [0.178, 0.324, 0.318, 0.148, 0.032]
PSI = 0.534
raw traces for every request: 6.0 GB/day
traces for 2% sample plus all flagged (assume 1%): 0.18 GB/day
two-bucket PSI terms [0.0673, 0.1022] total 0.1695
How the code works, step by step:
rng.lognormal(...)draws synthetic latencies. Real latencies are skewed: most requests cluster near a typical value and a few are very slow. A lognormal shape (the logarithm of the value is bell-shaped) imitates that. Minute 7 multiplies 8 percent of its requests by 6 to mimic a burst of slow retries.np.percentilecomputes the exact percentile from raw values; that needs every raw latency kept, so it cannot be done after the fact from aggregates.np.geomspace(100, 20000, 41)makes 41 bucket edges (so 40 buckets) from 100 ms to 20,000 ms, each edge about 14 percent above the last, so buckets are narrow where latencies live and wide in the tail.np.histogramcounts requests per bucket, andsum(hist(x) for x in mins)adds the ten windows' counts together: that addition is the merge.hist_pctfinds the percentile from counts alone:np.cumsumgives running totals,np.searchsortedreturns the first bucket whose running total reaches 99 percent of all requests, and the function reports that bucket's upper edge. That is why it can only be accurate to within one bucket width.- The last block computes PSI on five output-length buckets, and then on the two-bucket example above.
Reading it:
- The mean (885 ms) is far below the p99 (2163 ms): the tail is where users feel pain, so alert on percentiles, not means.
- Averaging per-minute p99 values gives 2359, but the pooled p99 is 2163. Percentiles do not average. Minute 7's p99 of 7395 ms dominates the average, yet it affected one minute of ten. Store bucket counts and merge them, then read the percentile from the merged histogram.
- The merged histogram reports 2402 for p99: an upper bucket edge, so it can overshoot the exact value by up to one bucket width (here 239 ms above 2163, in a bucket about 300 ms wide). Narrower buckets shrink this error at the cost of more series; 40 buckets per window is already small.
- Output length: week 2 shifted mass into the shortest bucket (0.021 to 0.178), PSI 0.534, far above the 0.25 rule-of-thumb line for a large shift. That is a drift alarm. It does not say whether replies got better or worse; a quality sample must answer that.
- Storage: with the assumed 1,000,000 requests a day and 6 KB per trace (an assumption), keeping every trace is 6.0 GB per day, while a 2% random sample plus an assumed 1% of flagged requests is 0.18 GB per day. Aggregates are kept for all requests either way.
Retention and privacy
Aggregates can live for months at low cost. Raw prompts and replies need redaction of personal data, access control, a short retention window, and a documented rule for what gets sampled. Keep all flagged traces and a random baseline sample; the baseline is what lets you measure the flag rate honestly.
Pitfalls
- Alerting on a single metric. Latency can improve exactly because a prompt change made replies shorter and worse.
- Dashboards without slices (topic, user segment, language): a regression confined to one slice vanishes in the average.
- Judge-based quality metrics with no calibration. Treat their trend as a signal and audit them against human labels.
What does observability mean for an LLM-powered feature, and how does it differ from observability of a conventional service? Name the key signals you would capture.
Sample Answer
Direct answer
Observability means you can answer "why did the system do that?" from the data it emits, without shipping new code. For a conventional service, the questions are about health: did the request succeed, how long did it take, what resource was used. For an LLM feature there is a second question that status codes cannot answer: was the output any good? The model can return HTTP 200 with a fluent, confident, wrong answer, so observability for an LLM feature adds the content of each step (prompt, retrieved context, output) and quality signals computed on it, linked to the usual latency and error data.
How it differs from a conventional service
| Aspect | Conventional service | LLM-powered feature |
|---|---|---|
| Failure shape | Errors, timeouts, crashes: visible in status codes | Silent quality failures: invented facts, off-topic or unsafe replies, all with status 200 |
| Behaviour | Deterministic: same input, same output; a bug is reproducible | Non-deterministic (sampling) and sensitive to wording; reproduction needs the exact prompt, parameters and model version |
| What defines "correct" | A spec and assertions | No single correct output; correctness is graded by rubric, reference, human or a model-based judge |
| Cost | Roughly proportional to requests and compute time | Proportional to tokens (the word-pieces the model reads and writes), so one verbose prompt can cost many times another |
| Pipeline | Calls through services | A chain: input checks, retrieval, optional tool calls, the model call, output checks (guardrails: automatic checks that block or fix unsafe or malformed text going in or out). Any link can be the cause |
| Data sensitivity | Logs often hold metadata | Prompts and replies hold user text, possibly private, so capture needs redaction and retention rules |
| Change | Code deploys | Prompt edits, model version swaps and index refreshes change behaviour with no code deploy |
The signals to capture
A trace is the full record of one request; each step inside it is a span (one timed operation with attributes). Capture these per request:
- Latency per span and end to end, including time to first token (how long until the first word of the reply appears) for streamed replies (replies shown word by word as the model writes them).
- Errors and retries, including provider rate limits and timeouts.
- Token counts in and out, and derived cost.
- Inputs and outputs: the final prompt after template filling, retrieved passages with their IDs and scores, tool calls and results, the reply.
- Versions: model identifier, prompt template version, index version, sampling settings.
- Quality signals: groundedness (does the reply stay within the retrieved context), safety flags, format validity, plus user feedback (thumbs, edits, retries, abandonment).
- User and session identifiers, to find all requests affected by a problem.
A worked example
The program below uses one hand-written trace (timings and token counts are invented inputs) for a retrieval-augmented feature (one that first looks up relevant documents and puts them in the prompt), and six hand-written replies. The groundedness check is a deterministic stand-in: a real system would put a model-based judge or an entailment model (a model that decides whether a passage supports a claim) there. The stand-in only tests that every number in the reply appears in the retrieved context.
How to read the code. Part 1: each span is a tuple (name, start_ms, end_ms, tokens_in, tokens_out), so ("retrieve", 12, 95, 0, 0) means retrieval ran from millisecond 12 to 95 and used no model tokens. The guardrail spans are the automatic input and output checks, and rerank re-orders the retrieved passages with a more careful score. The program prints each span's duration, its share of the 940 ms total and its tokens, then a cost from the token counts. Part 2: each request is a (question, reply, retrieved context) triple, and stub_check pulls every number out of the reply and the context and compares the two sets.
import re
# One request through a retrieval-augmented chat feature, hand-written spans.
# Each tuple is (name, start_ms, end_ms, tokens_in, tokens_out).
spans = [
("guardrail_in", 0, 12, 0, 0),
("retrieve", 12, 95, 0, 0),
("rerank", 95, 160, 0, 0),
("llm_call", 160, 910, 1450, 180),
("guardrail_out",910, 940, 0, 0),
]
total_ms = spans[-1][2] - spans[0][1]
tin = sum(s[3] for s in spans); tout = sum(s[4] for s in spans)
print("end-to-end ms:", total_ms)
for name, a, b, ti, to in spans:
print(f"{name:14s} {b-a:4d} ms {100*(b-a)/total_ms:5.1f}% tokens in/out {ti}/{to}")
UNIT_IN, UNIT_OUT = 1.0, 3.0 # assumed cost units per 1000 tokens, for illustration only
print("cost units:", round(tin/1000*UNIT_IN + tout/1000*UNIT_OUT, 3))
# Six requests: every one returns HTTP 200. A quality check on the reply tells them apart.
reqs = [
("What was Q2 revenue?", "Revenue in Q2 was 4.2 million.", "Q2 revenue: 4.2 million. Q1 revenue: 3.9 million."),
("What was Q1 revenue?", "Revenue in Q1 was 3.9 million.", "Q2 revenue: 4.2 million. Q1 revenue: 3.9 million."),
("Q2 growth?", "Growth was 12 percent.", "Q2 revenue: 4.2 million. Q1 revenue: 3.9 million."),
("Q2 revenue?", "I could not find that.", "No relevant documents."),
("Q2 revenue?", "Revenue in Q2 was 4.2 million.", "Q1 headcount: 40."),
("Q1 revenue?", "Revenue in Q1 was 3.9 million.", "Q2 revenue: 4.2 million. Q1 revenue: 3.9 million."),
]
def numbers(t): return set(re.findall(r"\d+(?:\.\d+)?", t))
def stub_check(answer, context):
"""Stand-in for a real groundedness judge: every number in the reply must appear in the context."""
nums = numbers(answer)
if not nums: return "no_claim"
return "grounded" if nums <= numbers(context) else "ungrounded"
print()
for q, a, c in reqs:
print(f"http=200 {stub_check(a, c):10s} {q}")
Output:
end-to-end ms: 940
guardrail_in 12 ms 1.3% tokens in/out 0/0
retrieve 83 ms 8.8% tokens in/out 0/0
rerank 65 ms 6.9% tokens in/out 0/0
llm_call 750 ms 79.8% tokens in/out 1450/180
guardrail_out 30 ms 3.2% tokens in/out 0/0
cost units: 1.99
http=200 grounded What was Q2 revenue?
http=200 grounded What was Q1 revenue?
http=200 ungrounded Q2 growth?
http=200 no_claim Q2 revenue?
http=200 ungrounded Q2 revenue?
http=200 grounded Q1 revenue?
What this shows:
- The trace pins the time: the model call is 750 of 940 ms, so tuning retrieval would barely move the total. A conventional service dashboard would show this too.
- The cost line is in invented relative units (output tokens assumed three times the price of input tokens). The point is that cost comes from the token columns, which a conventional dashboard has no column for.
- All six requests return status 200. The quality check separates them: the "Q2 growth" reply quotes 12 percent that appears nowhere in the context (ungrounded), the fifth reply states Q2 revenue from a context holding only headcount (also ungrounded), and the fourth declines honestly. The stand-in is crude: it counts the digit in a label such as "Q2" as a number, so reply 5's numbers are 2 and 4.2 while its context holds 1 and 40, and reply 1 passes only because the context happens to contain "Q2" and "Q1" too.
- The program does not join anything; the join is done by the person reading the logged trace. Because the trace also stores the retrieved passages, an ungrounded reply can be sorted into two causes: the context held the facts but the reply invented others (a model fault, as with the growth figure), or the context never held the facts (a retrieval fault, as in reply 5, where the passage was about headcount). Without the retrieved text in the trace you could not tell these apart.
Limits and pitfalls
- Quality signals are themselves measurements with error; a stand-in or judge needs calibration against human labels.
- Logging full prompts is a privacy risk; redact, restrict access, and set retention.
- Without version tags on every trace, you cannot tell a regression caused by a prompt edit from one caused by a data change.
- Dashboards of averages hide tails and slices; keep percentiles and group by user segment and topic.
Design the dashboards you would build to monitor an LLM product: one for infrastructure and reliability owners, one for product owners. What would each show, which alerts, and how would a viewer drill down? Include how bias, privacy-leak risk and user satisfaction surface.
Sample Answer
Direct answer
Build two dashboards on the same trace data (a trace is the record of one request's path through the system, made of spans, one per step such as retrieval or a model call). The reliability dashboard answers "is it up, fast, and within budget?" for SRE and infrastructure owners, and pages people. The product dashboard answers "is it good, fair, safe and liked?" for product owners, and feeds weekly decisions rather than pages. Both drill from a headline number to a slice, to a single trace. Bias, privacy-leak risk and satisfaction live on the product side, behind access controls, because the drill-down ends in user conversations.
Reliability dashboard (SRE, infrastructure)
| Panel | Shows | Alert |
|---|---|---|
| Availability and error rate | Successful responses over total, by endpoint, model version, region | SLO burn rate (below) |
| Latency | p50, p95, p99 of time to first token and total time | p95 above the limit for several windows |
| Throughput and saturation | Requests per second, queue depth, rate-limit rejections | Queue depth growing |
| Tokens and cost | Input and output tokens per request, spend per feature | Spend per request outside a band |
| Dependencies | Retrieval, tool and provider call latency and failure | Dependency failure share |
| Deploys | Version markers on every chart | None, context only |
Terms in the table: a percentile such as p95 is the value that 95 percent of requests beat (p50 is the median, p99 means only 1 request in 100 is slower), which shows the slow tail that an average hides. Time to first token is how long a user waits until the first word of a streamed reply appears. Saturation is how full the system is relative to what it can handle, and queue depth is how many requests are waiting for a free worker (a growing queue means saturation). Rate-limit rejections are requests refused because a quota was exceeded, either ours or the model provider's.
Drill-down: headline chart, then split by version, region and endpoint, then the slowest or failed traces, then the span waterfall, a chart that lays a trace's spans out along a time axis so you can see which step took the time.
Alerting on an SLO (service level objective: a target such as 99.5% of requests succeed). The error budget is 1 minus the target, here 0.005. The burn rate is the observed bad fraction divided by the budget: 1.0 means spending the budget exactly as fast as allowed, and below 1.0 is healthy; there is no universal normal for a latency percentile, so judge p95 against your own latency limit and its history. A robust page requires a short window and a long window to both exceed the threshold, so a one-hour blip does not page and a real incident is not missed. The program below computes it on hand-set hourly data (20,000 requests per hour, an incident starting at hour 7).
Product dashboard (product owners)
| Panel | Shows | Notes |
|---|---|---|
| Quality | Share of sampled answers passing a rubric (human or judge model), faithfulness for grounded products | Judge scores are proxies validated on human labels |
| Safety | Policy-violation rate, refusal rate, over-refusal on benign prompts | Both directions matter |
| Satisfaction | Thumbs up/down, task resolved, regenerate and abandon rates, by feature | Self-selected feedback, so show response counts |
| Bias | The same quality, refusal and satisfaction metrics split by language or user group, with intervals and the gap to the best group | Show uncertainty; small groups produce wild rates |
| Privacy-leak risk | Count of responses where a detector finds personal data patterns or memorised text, and of prompts that contained personal data and were retained | A detector count is a lower bound, not a guarantee |
| Topic and intent mix | What users ask about and where failures cluster | Finds the slice to fix |
Alerts: week-over-week drop in the quality pass rate beyond its interval, a rise in policy violations, a gap between groups that widens, and any leak-detector hit above zero for a restricted category (this one goes to the security owner, not the product channel).
Drill-down: metric, then slice, then a sample of examples with the rubric result, then the full conversation only if the viewer's role allows it.
Access controls on the sensitive panels
- Roles: SREs see operational traces with content redacted; product owners see aggregates and redacted examples; a small named reviewer group (privacy, trust and safety) can open raw conversations, with each open logged and a stated purpose.
- Redaction at ingestion: strip or hash identifiers and personal data before traces reach the dashboard store, and set retention limits.
- Small-cell suppression: do not show a group metric below a minimum count, because a rate over 5 users can identify them. The program uses a floor of 100 for illustration; choose the floor with your privacy owner.
- Leak panel is itself sensitive: store only counts and categories, not the leaked strings, in the shared view.
Worked example
The program has two parts. Part 1 computes the SLO burn rate over one-hour and six-hour windows and pages when both exceed 3 (a threshold chosen here as policy, not a standard). Part 2 builds a small synthetic conversation log, then shows the refusal rate with a Wilson interval (a 95 percent range for the true rate that stays sensible on small counts) per language group, suppressing any group below the floor. The last lines count personal-data pattern hits in four hand-written outputs; the regular expression is a minimal illustration of the kind of detector that feeds the leak panel, covering only a US-style phone fragment, a social-security-like number and a simple email shape, and production detectors must also handle other formats, obfuscation and memorised text.
import numpy as np
import pandas as pd
# ---- Part 1: SLO burn-rate alert for the reliability dashboard (hand-set hourly data) ----
SLO = 0.995 # target: 99.5% of requests succeed within the latency limit
budget = 1 - SLO # allowed bad fraction = 0.005
THRESH = 3.0 # page when the budget is spent 3x too fast (a policy choice)
req_per_hour = 20_000
bad_per_hour = np.array([60, 80, 70, 90, 75, 85, 70, 400, 450, 420, 430, 410]) # incident starts at hour 7
def burn(bad, window):
frac = bad[-window:].sum() / (req_per_hour * window)
return frac / budget # 1.0 = spending the budget exactly as fast as allowed
for hour in (6, 7, 8, 9, 10, 11):
b = bad_per_hour[:hour + 1]
short, long_ = burn(b, 1), burn(b, min(6, len(b)))
page = short > THRESH and long_ > THRESH # both windows must exceed the threshold
print(f"hour {hour:2d}: burn(1h)={short:5.2f} burn(6h)={long_:5.2f} page={page}")
# ---- Part 2: product dashboard slice with a privacy floor (synthetic conversation log) ----
rng = np.random.default_rng(0)
groups = {"lang_a": (900, 0.040, 0.78), "lang_b": (700, 0.045, 0.77), "lang_c": (40, 0.12, 0.60)}
rows = []
for g, (n, refuse_p, sat_p) in groups.items():
for _ in range(n):
rows.append((g, int(rng.random() < refuse_p), int(rng.random() < sat_p)))
d = pd.DataFrame(rows, columns=["group", "refused", "thumbs_up_or_resolved"])
K_MIN = 100 # privacy floor: cells smaller than this are not shown to product viewers
def wilson(k, n, z=1.96):
p = k / n
c = (p + z * z / (2 * n)) / (1 + z * z / n)
h = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return c - h, c + h
lo2, hi2 = wilson(2, 10)
print(f"Wilson interval for 2 refusals in 10: [{lo2:.3f}, {hi2:.3f}]; the plain p +/- 1.96*sqrt(p(1-p)/n) lower end would be {0.2 - 1.96 * np.sqrt(0.2 * 0.8 / 10):.3f}")
out = []
for g, x in d.groupby("group"):
n = len(x)
if n < K_MIN:
out.append((g, n, "suppressed (n < %d)" % K_MIN, "", ""))
continue
lo, hi = wilson(x.refused.sum(), n)
out.append((g, n, f"{x.refused.mean():.3f} [{lo:.3f}, {hi:.3f}]", f"{x.thumbs_up_or_resolved.mean():.3f}", ""))
print(pd.DataFrame(out, columns=["group", "n", "refusal rate [95% Wilson]", "satisfaction", ""]).iloc[:, :4].to_string(index=False))
# PII-leak counter: simple pattern count on logged outputs (stub detector, illustrates a count not a guarantee)
import re
outputs = ["Call me at 555-0142 or mail a@b.co", "No personal data here", "ID 123-45-6789 appeared", "Plain answer"]
pat = re.compile(r"\b[0-9]{3}-[0-9]{4}\b|\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b|[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.[a-z]{2,}")
hits = [bool(pat.search(o)) for o in outputs]
print("outputs with a pattern hit:", sum(hits), "of", len(outputs))
Output:
hour 6: burn(1h)= 0.70 burn(6h)= 0.78 page=False
hour 7: burn(1h)= 4.00 burn(6h)= 1.32 page=False
hour 8: burn(1h)= 4.50 burn(6h)= 1.95 page=False
hour 9: burn(1h)= 4.20 burn(6h)= 2.50 page=False
hour 10: burn(1h)= 4.30 burn(6h)= 3.09 page=True
hour 11: burn(1h)= 4.10 burn(6h)= 3.63 page=True
Wilson interval for 2 refusals in 10: [0.057, 0.510]; the plain p +/- 1.96*sqrt(p(1-p)/n) lower end would be -0.048
group n refusal rate [95% Wilson] satisfaction
lang_a 900 0.039 [0.028, 0.054] 0.774
lang_b 700 0.041 [0.029, 0.059] 0.780
lang_c 40 suppressed (n < 100)
outputs with a pattern hit: 2 of 4
- At hour 7 an incident raised the bad rate to about 2% (400 of 20,000, four times the budget rate). The one-hour burn is already 4.00 at hour 7 and 4.50 at hour 8, but the six-hour window still holds quiet hours, so its burn is only 1.32 and then 1.95, and the page waits. By hand at hour 10: the last six hours (5 to 10) hold 85 + 70 + 400 + 450 + 420 + 430 = 1,855 bad requests out of 120,000, which is 1.55% and a burn of 1.55 / 0.5 = 3.09, above 3 together with the one-hour burn of 4.30. So the first page is at hour 10, the fourth bad hour (7, 8, 9, 10), and it stays on at hour 11. This delay is the price of avoiding false pages; a lower long-window threshold pages earlier and more often.
- The Wilson line shows why that interval is used: for 2 refusals in 10 the plain margin would put the lower end below zero, while the Wilson interval stays between 0 and 1 and is centred slightly toward the middle. It widens as n shrinks, which is why lang_c would be too uncertain to show anyway.
lang_aandlang_bhave refusal rates of 0.039 and 0.041 with overlapping intervals: no evidence of a gap.lang_c, with 40 conversations, is suppressed. Suppression protects individuals but can hide the group at highest risk, so give the restricted reviewer role the pooled figure over a longer period for that group.- Two of the four sample outputs matched a personal-data pattern, which is a number of the sample, not a rate.
Mistakes to avoid
- One dashboard for everyone: product owners get paged on latency, SREs get raw conversations.
- Averages only. Always show a percentile or a distribution for latency and an interval for rates.
- Bias metrics without group sizes or intervals.
- Satisfaction shown without the number of responses behind it.
Design a production monitoring plan to detect a rise in hallucinations for an LLM question-answering service handling 200k queries a day. What signals would you collect, what thresholds would alert, and what automated action would follow?
Sample Answer
Direct answer
Monitor three kinds of signals together: a cheap proxy on every request (citation validity, unsupported numbers, empty or weak retrieval, abstention rate), a sampled model-judge hallucination rate on a few percent of traffic, validated by a small human audit, and user and system signals (thumbs-down, re-asks, version changes). Alert on the sampled rate with a threshold derived from the sample size, since too small a sample cannot detect a realistic rise. Attach automated actions in tiers: warn, page, then a pre-approved rollback or stricter mode when the proxy and the sampled rate agree.
What 200,000 queries a day means
The average load is 2.31 queries per second (printed below); the point is that you cannot have people read all of it and may not want to run a model judge on all of it. So the design question is how many answers must be judged to see a rise of a given size.
Signals to collect
| Signal | Coverage | Role |
|---|---|---|
| Invalid citation rate, unsupported-number rate | 100% | Fast, cheap early warning |
| Empty or low-score retrieval, answered anyway | 100% | Root-cause hint |
| Abstention rate | 100% | A sudden fall means the system stopped saying "I don't know" |
| Judge-model hallucination flag rate | A sample | The main alerting metric |
| Human audit (for example 100 per day) | A small sample | Keeps the judge honest: re-measure its sensitivity and false-flag rate. At a 3% true rate, 100 audited answers hold only about 3 hallucinations, so pool several weeks (four weeks is about 84, which pins a sensitivity near 0.80 to roughly plus or minus 9 points) and audit judge-flagged and unflagged answers separately |
| Thumbs-down, re-ask, escalation | Whatever users give | Lagging confirmation |
| Prompt, model, index and data versions | 100% | Segment every metric by these, since a rise is usually tied to a change |
Segment each metric by intent type and version so one failing segment does not hide inside the average.
Setting a threshold that can be defended
Assume the judge flags a true hallucination with probability 0.80 and a clean answer with probability 0.02 (stand-in numbers for a judge you have measured against human labels). The goal is to catch a rise of the true rate from 3% to 4.5%. The judge-flagged rate then moves from 4.34% to 5.51%, a smaller visible change because of the judge's own errors. The alert fires when the day's flagged share exceeds
τ=q0+z1−αnq0(1−q0)where q0 is the baseline flagged share, n the judged answers that day, and z1−α the normal quantile for the one-sided false-alarm rate α (here 0.001). Plain meaning of each piece:
- One-sided means we only alert when the rate goes up, not when it goes down.
- α, the false-alarm rate, is the chance that an ordinary day, with no real change, crosses the line anyway. At 0.001 that is about one false alarm per 1,000 days.
- Power 1−β is the chance that a day on which the rate really has risen does cross the line. Power 0.90 means 9 such days in 10 are caught.
- zq, the normal quantile, is how many standard deviations above the average you must go to leave a share q of ordinary days below the line. A standard deviation is the typical size of the day-to-day wobble. The normal approximation treats the day's flagged share as a bell curve, which is close but not exact for small proportions.
By hand for n=1000: z1−α=3.09, the wobble is 0.0434×0.9566/1000=0.00644, so τ=0.0434+3.09×0.00644=0.0633. The sample size for power 1−β (here 0.90, so z1−β=1.28) is
n=(q1−q0z1−αq0(1−q0)+z1−βq1(1−q1))2with q1 the flagged share after the rise. By hand with q0=0.0434 and q1=0.0551: the top is 3.09×0.2039+1.28×0.2282=0.6297+0.2924=0.9221, divided by q1−q0=0.0117 gives about 78.8, and 78.8 squared is about 6,211 (the program prints each piece). The program computes it and then simulates 20,000 days at each sample size, with a fixed seed.
import os
os.environ["OMP_NUM_THREADS"] = "1"
import numpy as np
from scipy import stats
queries_per_day = 200_000
print("average queries per second:", round(queries_per_day / 86400, 2))
# The judge is imperfect: it flags a true hallucination with prob SENS and a clean answer with prob FPR.
SENS, FPR = 0.80, 0.02
obs = lambda p: SENS * p + FPR * (1 - p)
p0, p1 = 0.03, 0.045 # true rate at baseline vs the rise we must catch
q0, q1 = obs(p0), obs(p1)
print("true rates", p0, p1, "-> judge-flagged rates", round(q0, 4), round(q1, 4))
alpha, power = 0.001, 0.90 # one-sided daily alert threshold; target detection power
za, zb = stats.norm.ppf(1 - alpha), stats.norm.ppf(power)
n_need = ((za * np.sqrt(q0 * (1 - q0)) + zb * np.sqrt(q1 * (1 - q1))) / (q1 - q0)) ** 2
t1, t2 = za * np.sqrt(q0 * (1 - q0)), zb * np.sqrt(q1 * (1 - q1))
print(f"z(1-alpha) {za:.2f}, z(power) {zb:.2f}; terms {t1:.4f} + {t2:.4f} = {t1 + t2:.4f}; over (q1-q0) {q1 - q0:.4f} = {(t1 + t2) / (q1 - q0):.2f}; squared {n_need:.1f}")
se1000 = np.sqrt(q0 * (1 - q0) / 1000)
print(f"threshold at n=1000: {q0:.4f} + {za:.2f} x {se1000:.5f} = {q0 + za * se1000:.4f}")
print("judged answers needed per day (normal approximation):", int(np.ceil(n_need)))
rng = np.random.default_rng(0)
DAYS = 20000
for n in (500, 1000, 2000, 4000, 6212):
thr = q0 + za * np.sqrt(q0 * (1 - q0) / n) # alert when flagged share exceeds this
fa = np.mean(rng.binomial(n, q0, DAYS) / n > thr)
det = np.mean(rng.binomial(n, q1, DAYS) / n > thr)
print(f"n/day={n:5d} ({100*n/queries_per_day:.2f}% of traffic): alert above {thr:.4f}, false-alarm days {fa:.4f}, detection on day 1 {det:.3f}")
# Pooling the same 1000/day over 3 days divides the variance of each decision by 3 (standard error by about 1.7), at the cost of delay
n3 = 3000
thr3 = q0 + za * np.sqrt(q0 * (1 - q0) / n3)
print("1000/day pooled over 3 days: detection", round(float(np.mean(rng.binomial(n3, q1, DAYS) / n3 > thr3)), 3),
"false alarm", round(float(np.mean(rng.binomial(n3, q0, DAYS) / n3 > thr3)), 4))
It prints:
average queries per second: 2.31
true rates 0.03 0.045 -> judge-flagged rates 0.0434 0.0551
z(1-alpha) 3.09, z(power) 1.28; terms 0.6297 + 0.2924 = 0.9221; over (q1-q0) 0.0117 = 78.81; squared 6210.9
threshold at n=1000: 0.0434 + 3.09 x 0.00644 = 0.0633
judged answers needed per day (normal approximation): 6211
n/day= 500 (0.25% of traffic): alert above 0.0716, false-alarm days 0.0024, detection on day 1 0.063
n/day= 1000 (0.50% of traffic): alert above 0.0633, false-alarm days 0.0014, detection on day 1 0.120
n/day= 2000 (1.00% of traffic): alert above 0.0575, false-alarm days 0.0015, detection on day 1 0.340
n/day= 4000 (2.00% of traffic): alert above 0.0534, false-alarm days 0.0015, detection on day 1 0.681
n/day= 6212 (3.11% of traffic): alert above 0.0514, false-alarm days 0.0014, detection on day 1 0.898
1000/day pooled over 3 days: detection 0.524 false alarm 0.0011
Reading it:
- Need 6,211 judged answers a day, about 3.1% of traffic, for 90% detection on the first day. The simulation confirms it (0.898 at 6,212).
- Smaller samples cannot see this rise quickly. At 1,000 judged a day (0.5% of traffic) the chance of an alert on day 1 is 0.120; at 4,000 it is 0.681.
- False alarms: the simulated rate is 0.0014 to 0.0015 per day for 1,000 to 6,212 judged answers and 0.0024 at 500, against the 0.001 design value, because the normal approximation is rough at these small proportions (the real count distribution is skewed, with a longer upper tail than a bell curve). Each simulated figure carries sampling noise of about 0.0003 from 20,000 days. At about 0.0015 per day that is one false alarm roughly every 700 days; if that is too noisy, raise the threshold slightly or require two consecutive days.
- Pooling trades delay for power: judging 1,000 a day and testing every 3 days on 3,000 answers detects the rise 0.524 of the time within that first window, with a simulated false-alarm rate of 0.0011 per test (close to the 0.001 design value; the gap is sampling noise). Pooling three days divides the variance of the estimate by 3 (the standard deviation shrinks by a factor of about 1.7), which is why 3,000 answers see more than 1,000 do (0.524 against 0.120), at the cost of waiting three days.
A larger jump needs far fewer judged answers, since n shrinks with the square of the effect size; that is why the 100% proxies catch big failures within hours, while the sampled rate catches slow drift.
Automated actions, in tiers
- Warn (proxy up 2x its baseline, or sampled rate above τ once; 2x is a policy choice, large enough to sit well outside normal wobble in a cheap counter that is measured on every request, small enough to catch a real shift early): post to a channel and trigger an extra human audit.
- Page (sampled rate above τ on two consecutive tests, because two independent crossings are far less likely by luck than one, or proxy and sampled rate both up): notify the on-call, freeze deploys, and tag the change that went out recently.
- Automatic mitigation (only when pre-approved and safe to reverse): roll back the last prompt, model or index version behind a feature flag; switch to a stricter answer mode (require a citation for every claim, raise the abstention threshold); route low-confidence intents to a fallback. Log every action.
Review automatic actions by hand within one working day, and keep the rollback reversible.
Failure modes
- Judge drift: the judge model or prompt changes and the baseline shifts; re-measure with the human audit.
- Traffic mix shift: a new customer segment raises the true rate with no code change; segment metrics.
- Alert fatigue: every extra threshold is another chance for a false alarm (the multiple-testing problem: test 20 independent signals at 0.001 each, and false alarms arrive about 20 times as often); keep one primary alert and treat the rest as context.
Running the code
Needs Python 3 with numpy and scipy. Copy the program into a file and run it with python.
Unlock Full Question Bank
Get access to all 11 LLM Evaluation and Observability interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.