Skip to content
Forward Deployed

Forward Deployed

Observability and Production Diagnosis

Trace a slow or wrong answer to the hop that caused it, without turning telemetry into a second copy of customer data.

Kind
Case study
Level
Core
View
Interview prep
Sections
4
By
Sourav Banerjee
Last updated
20 Nov 2026

Practise this as a worksheet: Observability for a Customer-Facing AI Application

Report an issue

Interview view. The case brief, design walkthrough, technical deep dives and quick review, condensed into bullets, tables and lines to say out loud, with interactive diagrams to step through.

Want to go deep? The full casebook has the complete reasoning in prose, the original diagrams, practice questions with worked answers and the sources.

Case brief

The case in one line: trace every "slow and sometimes wrong" complaint to the hop that caused it, without turning telemetry into a second copy of customer data.

30-Second Cheat Sheet

  • The complaint: users of a customer-facing AI app say it is slow and sometimes wrong.
  • The job: trace each complaint to the step behind it: a slow search, a model that ignored good evidence, a failing tool call or a backed-up queue.
  • The hard part, privacy: the evidence lives in the same requests that carry prompts, documents and identifiers.
  • The shape: one correlation ID per request, structured spans through retrieval, model and tools, exported asynchronously, redacted before storage and sampled toward errors and slow traces.
  • Access: authorised support sees only its own tenant.
  • Diagnosis runs top down: user outcome → slow or failing span → retrieved evidence compared with the answer.
  • The dangerous constraint: telemetry never stores raw prompts, documents or secrets, and support never reads another tenant's data.

1. Find the hop behind "slow and sometimes wrong"

The problem

  • Users of a customer-facing AI application say it is slow and sometimes wrong.
  • The team must trace each complaint to the step that caused it:
    • A slow search.
    • A model that ignored good evidence.
    • A failing tool call.
    • A queue that backed up.
  • The difficulty is privacy. The evidence that explains a failure lives in the same requests that carry customer prompts, documents and identifiers.
  • The telemetry must not become a second copy of that data.

The terms that carry the whole case

Term Meaning
Telemetry The operational data a system emits about itself: timings, error codes, counts and outcome labels
Span One timed record of one step, such as "retrieval took 1.2 seconds and returned 3 documents"
Trace The set of spans for one request, linked together
Correlation ID One identifier attached to a request on arrival and carried through every service, queue and integration. It lets us join spans from different systems into one trace.
Tenant One customer organisation on a shared platform. Acme and Globex are two tenants; neither may see the other's data.
p95 / p99 The response times that 95% and 99% of requests beat. They describe the slow tail that averages hide.
RAG Retrieval-augmented generation: fetch relevant documents first, then have the model answer only from them. A wrong answer can start in the search step or in the model.

The design in brief

  • Every request gets a correlation ID and structured spans through retrieval, model and tools.
  • Spans leave the request path asynchronously.
  • They are redacted before storage.
  • They are sampled so errors and slow traces are kept.
  • Authorised support staff see only their own tenant.
  • Diagnosis runs from the complaint down: the user's outcome first, then the slow or failing span, then the retrieved evidence compared with the answer.

The core idea as a flow

user complaint → correlated trace (via its correlation ID) → did retrieval find good evidence?

  • No → the fault is upstream in retrieval. Changing the model will not help.

  • Yes, but the answer contradicts it → fix the model or the prompt.

  • Both look right → the remaining suspects are tool calls and latency.

  • The figure is the whole method in one path.


2. Follow one request: Acme's German refund flow

The request: an Acme user asks the assistant about a refund in German.

  1. Correlation ID at authentication. The request gets its ID together with its tenant, Acme.
  2. Each hop records its time and outcome: retrieval, model call and tool call.
    • The raw prompt is not recorded by default.
  3. A classifier redacts sensitive values before anything is stored.
    • Kept: "Retrieval 1.2s, 3 docs".
    • Not kept: a full SSN (social security number, the United States personal identity number).
  4. Tenant-scoped support. When the user complains, support staff working for Acme open Acme's traces only.
    • A level-one (L1) support agent cannot open Globex tickets "to help debug".
  5. The trace separates cases that look identical to the user:
    • A slow first token versus a slow last sentence.
    • An empty retrieval versus a made-up answer versus a tool returning HTTP 500.
  6. Errors and outliers are always kept. Most successful, ordinary traffic is sampled: only a fraction of it is stored.
  • The loop: trace the path, hide the secrets, find the hop.
  • Throughout, telemetry must not stall the user.

3. What you need to design

The slice

  • One correlation ID through the AI path, redacted spans and tenant-scoped debugging.
  • It is one slice of a larger product and adds no product feature.

The dangerous constraint

  • Telemetry must never store raw prompts, documents or secrets.
  • It must never let support read another tenant's data.

By the end you should be able to

  • Explain the system at interview depth, starting from that constraint.
  • Answer follow-ups on:
    • Redaction
    • Sampling
    • Root-cause method
    • Failure policy
    • The two production incidents
    • Rollout

Who it's for

  • Forward Deployed, solutions and applied-AI engineering interviews.
  • Especially a production operations round that asks you to debug a live large language model (LLM) application, or handle a latency or cost incident.

What it assumes you know

  • Distributed tracing
  • Percentile latency
  • RAG pipelines
  • Multi-tenant access control

Each reads the anchor's spans at a different depth.

Related case Shared foundation What changes
Latency spike Correlated stage spans Diagnose stacked retrieval, reranker, queue and provider delays
Cost spike Versioned request and token metadata Find prompt expansion, model-route change and unsafe cache-key regression
Latency questions Per-hop timing Separate application queueing from inference prefill and decode
Poor RAG quality Retrieval and answer evidence Separate retrieval, synthesis, prompt, output and user-experience faults
Cost/latency pivots Tenant/workflow attribution Apply measure → route → bound → cache safely

How the sections divide the work

  • Design walkthrough: the answer you would give in the room. Work through it first.
  • Technical deep dives: the mechanisms, both incidents in full and the neighbouring prompts.
  • Practice (in the full casebook): rebuild the design from a blank page and rehearse every source question and pivot card.
  • Quick review: the one-page recall sheet for the night before.

Quick Recall: Lines to Say in the Interview

  • "Slow and sometimes wrong: I need to find the hop, not add more logging."
  • "One correlation ID from authentication through every service, queue and integration."
  • "Retrieval 1.2 seconds, 3 docs is kept; the SSN is not."
  • "Spans leave asynchronously, are redacted before storage and sampled toward errors and slow traces."
  • "Acme's support sees Acme's traces only; L1 can't open Globex tickets to help debug."
  • "If retrieval found nothing good, changing the model won't help."
  • "Trace the path, hide the secrets, find the hop, and never stall the user."

Design walkthrough

The goal: connect user-visible failures to technical causes, quickly and safely, without violating privacy or drowning operators in telemetry.

30-Second Cheat Sheet

  • Split the complaint into three problems: latency, correctness, diagnosability.
  • First design decision is the no-capture list: full prompts, raw documents, secrets and unbounded labels stay out by default. A narrow, audited break-glass path covers deep debugging.
  • Requirements must be able to fail a test. The functional core is the support workflow: complaint → request family, no raw content.
  • Size by collection policy: 500 rps × ~6 spans ≈ 3,000 spans/s; keep errors/outliers plus 5% → about 110–155 GB for 30 days. The classifier, not disk, is the constraint.
  • Tracing-first, two paths: the observability path describes the request path but can never authorise, alter or stall it.
  • Every layer has a failure policy: telemetry export degrades; missing auth, cross-tenant lookup, redaction failure and required audit evidence fail closed.
  • Diagnose top down: user outcome → stage spans → retrieved evidence versus answer.
  • Roll out in four phases with named owners, an eight-metric scorecard, a go/no-go gate and a risk register.

Opening line (source): "Connect user-visible failures to technical causes without violating privacy or drowning operators in telemetry." Then ask the first two questions, state assumptions aloud and invite the interviewer to redirect you.


1. Split the complaint into three problems

  • The customer wants to connect a user-visible failure to a technical cause, quickly, safely and without drowning operators in noise.
  • More logging does not achieve that. A vague complaint can't be instrumented, so the first job is to make it measurable.

"The AI is slow and sometimes wrong, and nobody knows why" is three problems

Problem The question it asks
Latency Is the request slow, and where in the pipeline does the time go?
Correctness Is the answer wrong, and is the fault upstream in retrieval or downstream in the model or a tool?
Diagnosability Can support and engineering explain a failure without exposing sensitive content?

Each stakeholder wants a different signal

Stakeholder Wants
Support To triage a complaint without waiting on engineering
Engineering To know whether the fault is retrieval, the model or a tool integration
Security Assurance that telemetry does not become a new exposure surface
Executive sponsor Proof that quality improves release to release. A wall of green dashboards doesn't provide it.

Six questions to ask the interviewer

Question to ask What it's really asking What you then decide
What is slow: first token, full response or a specific workflow percentile? Is the user staring at a blank box, or waiting for the last sentence? SLO and which spans to time
What is wrong: empty retrieval, unsupported answer, tool failure or partial response? Empty search, made-up answer, tool 500, or a truncated reply? Outcome labels and quality checks
Which tenants and workflows are affected? Is only Acme's German refund flow slow, or everyone? Sampling and blast radius
What content is forbidden in telemetry by default? Can we store the full prompt, or only "retrieval 1.2s, 3 docs"? No-capture list and redaction
Who must diagnose incidents, and what may support see? Can L1 support open another tenant's raw tickets while debugging? Tenant-scoped views and access roles
What overhead, retention and sampling budget are acceptable? Can we afford 100% traces for 90 days, or 5% for 14? Collector and store size

SLO (service level objective) = the internal target the team commits to, such as "95% of answers in under 3 seconds".

The complete discovery set (eight questions)

The full design adds two questions to those six and says why each changes the design.

Question Why it changes the design
What counts as slow: which percentile, on which path, for which workflow? Sets the SLO the whole trace model is built to explain
What counts as wrong: incorrect, empty, hallucinated, or a surfaced tool failure? Decides which outcome tags every request carries
Which users and tenants are most affected? Decides where instrumentation starts
What may be captured by default, and what is contractually off limits? Writes the no-capture list before anything else
Who must diagnose a failure: support alone, or engineering every time? Decides whether a trace-linked support workflow is a requirement
What telemetry overhead is acceptable? Makes instrumentation a budgeted constraint
What retention window applies, and who may read traces under which role? Sets the store's retention and the access gateway
What must the sponsor see to believe quality is improving? Decides the top panel of the dashboard
  • Every answer lands on a concrete artefact: an SLO, an outcome tag, a no-capture list, a store size, the top dashboard panel.
  • If an answer wouldn't change anything you build, the question can wait.

2. Decide what not to collect first

  • The unusual first design decision is the no-capture list.
  • Full capture maximises forensic power, but it raises privacy exposure, access-control burden and storage cost all at once.
  • Data never collected can't leak through the trace store, can't overload a metrics backend and costs nothing to store.
Must be observable by default Must not be captured by default
Request identity: a stable request ID and tenant context Full prompts
Retrieval evidence: what was retrieved, and whether it was relevant Raw customer documents
Model invocation metadata: model version, prompt template version, generation settings Secrets
Tool call outcomes: status, latency, error class High-cardinality free-form labels: arbitrary user text, unbounded metadata keys
Timing at each hop of the pipeline
User-visible outcome tags: success, partial answer, escalation

Cardinality = the number of distinct values a label can take. region has a handful; a label holding free user text has as many values as there are requests, and every distinct value becomes a new series the metrics backend must index. That's why free-form labels sit with secrets.

The left column becomes a fixed span schema

  • Correlation ID, tenant, span name, timing, model and prompt-template versions, retrieval references, tool outcome, error class and user-visible outcome.
  • Retrieval references are document identifiers and query fingerprints, not document text.

Don't overcorrect

  • "Never capture anything" goes too far the other way.
  • Capture enough structure to diagnose most incidents, redact by default, and record hashes or stable references instead of content.
  • Keep a narrow break-glass path for approved deep debugging:
    • Deeper evidence only with approval
    • Strict access
    • A short timer on retention
    • An audit record of every use

The hidden constraint interviewers inject

  • Mid-round: "the customer will not allow raw prompts to be broadly retained."
  • A design that started from "capture everything" has to restart.
  • A design that started from the no-capture list only has to name its break-glass path.

3. State requirements as testable constraints

  • A requirement that can't fail a test is a preference.
    • "Observable" is a preference.
    • "Support moves from a complaint to the request family without seeing raw content" is a constraint, and it shapes the architecture.

Request family = the group of related requests behind one complaint (same user, workflow and time window), found through correlation IDs and outcome tags rather than by reading prompts.

Functional requirements (what it does)

  • The functional core is the support workflow: a support agent moves from a user complaint to the exact request family and explains the failure without seeing raw sensitive content.
  • Five more make that possible:
    1. Attach a stable correlation ID to every request and propagate trace context through authentication, tenant resolution, retrieval, model, tools, post-processing and queues, including across services and customer integrations.
    2. Capture per-hop timing across authentication, tenant resolution, retrieval, model call, tool use, post-processing and delivery, with outcome tags.
    3. Record retrieval evidence, model version, prompt template version, generation settings and tool outcomes as structured attributes.
    4. Keep an aggregate global dashboard for platform health separate from tenant-scoped views for customer debugging.
    5. Tag every request with a user-visible outcome, so complaints map to telemetry. Keep an access audit that doesn't depend on sampled debug traces.

Non-functional constraints, stated so a test can fail them

Constraint Stated so it can be tested
Latency Instrumentation must not become the outage; telemetry overhead is a budgeted constraint, measured with and without export
Availability Telemetry export failure degrades diagnostics but never blocks the user request
Security Full prompts, raw documents and secrets never captured by default; sensitive fields classified and hashed before storage; redaction pass rate = zero raw prompts in any sink
Compliance Audit logs (who accessed what) stay separate from debugging traces (what failed where)
Reliability No single global sampling rule governs all error paths
Cost Volume scales with request rate, trace rate, retention window and sampling rate, so the first decision is what not to collect
Diagnosability Trace coverage high enough that complaints map to traces; mean time to diagnose falls after the support workflow lands

The compact version (adds two easy-to-forget items)

  • The two additions: tenant isolation with bounded retention, and a stricter failure policy for protected-action evidence than for ordinary traces.
Requirement Example target / constraint
Non-blocking Telemetry cannot stall the user request
Overhead Stay within an agreed budget
Privacy No full prompts, raw documents, secrets or unbounded free-form labels by default; redact before storage
Isolation Tenant isolation; bounded retention
Audit Protected-action evidence has a stricter failure policy than ordinary traces
Volume (illustrative) 500 rps × ~6 spans ≈ 3,000 raw spans/s. Keep all errors/outliers (~2–5%) plus ~5% of normal traffic. ~200 B/redacted span × 30 days ⇒ ~110–155 GB (~270–390 GB at a more typical ~500 B/span). Classifier/export capacity matters more than disk.

Every requirement needs an owner

If you can't point to the component that satisfies a requirement, the design has a gap.

Requirement Primary component(s)
Complaint to request family, unaided Support and access gateway, tenant-scoped views, outcome tags
Correlation across services and queues Trace collector, queue serialisation contract
Per-hop timing Spans emitted at every hop into the collector
Structured evidence without raw content Sensitivity classifier, keyed hash (HMAC)
Global versus tenant views Two consumers of one store, with a permission boundary
Overhead within budget Sampling policy, attribute caps, bounded retention
Audit separate from debug Audit and redaction pipeline with its own write path

Spoken answer (source), for "What are the requirements?": "Functionally, one ID through every hop, timings and outcomes, tenant-scoped debug. Non-functionally, don't block the user, don't store the prompt, and still find why it was slow or wrong."


4. Size the telemetry by collection policy

  • Estimate from collection policy, not raw QPS (queries per second).
  • Volume, storage and query load all scale with sampling rate, cardinality bounds and retention window.
  • Observability data isn't free. Instrumentation that isn't budgeted becomes the outage.
  • Caveat: the source chapter gives no numbers. These come from a supplementary V2 tutorial "gap note", illustrative only. Say it aloud anyway: the conclusion surprises people.
Step Figure (V2 gap note, supplementary)
Peak traffic 500 requests/second
Spans per request ~6: auth, retrieval, model, tool, post-processing, plus the root request span
Raw span rate ~3,000 spans/second before sampling
Tail-biased retention 100% for error and latency-outlier traces, roughly 2-5% of volume
Probabilistic sampling for the rest (decided in the tail sampler) 5%
Effect Raw trace volume cut by roughly 90%, failure population preserved
Stored size ~200 bytes/span after redaction, 30-day retention, about 110–155 GB (roughly 270–390 GB at a more typical ~500 bytes/span)

The arithmetic behind the last two rows

  1. 2% anomalies: keep that 2% plus 5% of the remaining 98% → about 7% of spans.
  2. 5% anomalies: keep about 10%.
  3. Seven to ten percent of 3,000 spans/s → roughly 210 to 300 spans/s. That's the "cut by roughly 90%".
  4. At 200 bytes a span over the 2,592,000 seconds in 30 days: 210/s → about 109 GB; 300/s → about 156 GB.
  5. At 500 bytes a span: about 270 to 390 GB. The typical 500-byte figure comes from Grafana Tempo's trace-ingestion documentation.

The conclusion

  • Storage is not the constraint at this scale. Classifier CPU and the correctness of the redaction policy are.
  • Every span passes through the classifier before storage, so the classifier sits on the observability path's critical line.
  • Caveat: volume still depends on span size, overlap between sampling classes and traffic shape. Treat these as an order of magnitude.

Head versus tail sampling

Kind How it decides Strength Weakness
Head sampling At the start of a request Simple and cheap Blind to the ending: a 5% head sample drops 95% of failures along with 95% of successes
Tail sampling After the request completes Can keep slow and failed traces More buffering, infrastructure and careful policy; every trace held until its outcome is known
  • Scaling tail sampling: all spans of one trace must reach the same sampler instance, so a scaled deployment puts a trace-ID-aware load balancer in front of the tail-sampling collectors.
  • The interview-safe position: retain latency-heavy, error-heavy and anomalous traces first, then keep a small random share of the ordinary remainder.
    • Both decisions belong to the tail sampler after the trace completes.
    • A head sampler that dropped a request at the start can't keep it later when it fails.

The figure as a flow

incoming trace → sampling decision

  • Head branch → cheap and simple, but a rare, expensive-to-reproduce failure is dropped with the same probability as a healthy request → the only bad trace can be lost.
  • Tail branch → the decision sees the outcome → latency-heavy, error-heavy and suspicious traces are retained preferentially.
  • The sampling deep dive adds the overrides that protect rare failures and the drill for when a trace is lost anyway.

5. Draw the architecture end to end

  • Tracing-first: structured spans, selective redaction and a stable correlation ID on every request from the edge inward.
  • Two paths run side by side:
    • The request path serves the user. It may use retrieval, an LLM and tools.
    • The observability path describes those steps but cannot authorise, alter or stall them.
  • A bounded asynchronous export separates the two. Nothing raw crosses the classifier boundary into the trace store.

Trace one request through the design

  1. Edge. Give each authorised request a correlation ID and tenant scope; propagate both across services, queues and integrations.
  2. Time each step. Retrieval, model, tool and post-processing get structured version, error and outcome metadata, while the request continues to the user.
  3. Export asynchronously through a bounded buffer. If export fails, serve the user anyway and alert on the diagnostic gap.
  4. Classify and redact before storage. Where correlation is needed, replace the value with an HMAC fingerprint made with a secret key, and cap attribute cardinality.
  5. Bias retention toward error and slow traces, with exemplars and incident overrides so rare failures stay diagnosable.
  6. Store only bounded, retention-limited traces. Platform-wide aggregates go to the global dashboard; tenant and role access is enforced for support views.
  7. Write support access events to a separate, durable audit path, so trace sampling can't erase the record of who viewed evidence.

HMAC (hash-based message authentication code) = a hash made with a secret key. Same input + same key → same fingerprint, but nobody without the key can reverse it by guessing. The redaction deep dive has the detail.

Exemplar = a metric data point that carries the trace ID of one request it measured, so a latency chart links to a concrete trace. The link only helps if the sampler also keeps that trace, so exemplar traces are exempt from sampling.

The four-line whiteboard version

  • Request: auth/tenant → retrieval → LLM → tools → response.
  • Spans: async collector → classify/redact/HMAC → error-and-slow-biased sampling → bounded store → global aggregate and tenant-scoped support views.
  • Access audit is separate.
  • Telemetry export never blocks the user.

The other views the source draws

  • Request path, with trust boundaries: authenticate and assign correlation ID → resolve tenant → retrieve → model call → tool use → post-process → response and actual outcome. The ID is assigned at authentication; the actual outcome is recorded at the end.
  • Observability path: per-stage spans and outcome tags → async bounded buffer and trace collector → classifier (classify sensitivity, keyed HMAC, cap cardinality) → tail-biased sampling with error overrides and exemplars → retention-bounded trace store → global aggregate-only dashboard and support access gateway with tenant-scoped view. A separate durable, fail-closed access audit records who, when and why.
  • The source chapter's original two-path diagram (kept verbatim in the full casebook): request path = AuthN and tenant resolution → retrieval → model call → tool use → post-processing → response delivery. Observability path = trace collector (structured spans, correlation ID) → sensitivity classifier (hash or redact) → trace store (sampled, bounded retention) → global health dashboard (platform-wide) and tenant-scoped views (support and customer debugging).

Two properties that hold in every drawing

  1. Serving never waits for telemetry export. Buffer or export failure degrades observability without blocking the user.
  2. No raw content crosses the classification boundary.

Components and how each fails

Read the "fails how" column: it's the quickest way to see why each boundary exists.

Component Primary responsibility Notes Fails how
Trace collector Attach correlation ID, propagate context, capture spans per hop Structured, not raw text by default Context lost at a queue; orphan spans
Sensitivity classifier Classify and hash sensitive fields before they reach telemetry Runs before storage, not after A missed pattern writes PII into every downstream sink
Trace store Durable, retention-bounded storage of exported traces Retention window is a cost and privacy control Unbounded retention turns it into a data lake of customer content
Global dashboard Platform-wide health, release regressions Cross-tenant, aggregate only A tenant label on a global chart explodes cardinality
Tenant-scoped views Customer-specific debugging, support triage Access scoped by role and tenant One misconfigured view spans every tenant
Support and access gateway Role-based, tenant-scoped access to evidence Enforces least privilege "Can read all traces" becomes the default
Audit and redaction pipeline Enforces retention and redaction on export Defence in depth: code, collector, review Combined with debug traces, it inherits their sampling and short retention

PII (personally identifiable information) = anything that identifies a person: name, email, phone or account number.

Four questions to answer against the diagram

Question Answer
How does each request get a correlation ID? At authentication, before anything else runs
How does trace context flow across services and customer integrations? In headers between services, and in an explicit serialisation contract across queues
How does support jump from an alert to the request family without raw content? Through outcome tags, fingerprints and document references in a tenant-scoped view
How are global and tenant visibility separated? Two consumers of one store with a permission boundary: aggregates only on the global side, tenant and role checks on the support side

6. Name the failure policy for every layer

  • Every dependency needs an explicit answer: what happens when it's gone?

Five possible answers

Term Meaning
Fail open Continue with reduced visibility
Fail closed Refuse the action when integrity, privacy or authorisation would be compromised
Degrade Serve a reduced but safe experience
Queue Buffer the work with explicit bounds and retention
Human intervention Escalate when risk or ambiguity is too high for automation

The policy for each layer

Failure Policy
Auth token missing Fail closed; don't infer identity; ask the caller to re-authenticate
Telemetry export unavailable Degrade; keep serving, buffer a bounded summary, alert
Retriever timeout Retry once with jitter; if still failing, degrade to a reduced-answer path or ask for refinement
Model gateway rate limit Queue briefly if the SLA allows; otherwise fail gracefully with a specific retry message
Audit sink unavailable Usually fail closed for the audited action, or require a human; silent loss of audit evidence is unacceptable
Support lookup outside tenant scope Fail closed; no cross-tenant fallback
Repeated downstream timeouts Trip a circuit breaker; serve a safe degraded response or queue if the workflow permits
Evidence buffer full Dead-letter the overflow into a restricted quarantine queue with an incident marker, then alert a human

SLA (service level agreement) = the promise to the customer, usually with penalties; looser than the internal SLO. Circuit breaker = stops calling a dependency after repeated failures, so the system stops waiting on timeouts. Dead-letter queue = holds messages that couldn't be processed so they aren't silently lost.

Say why the rows differ

  • A user-facing answer can sometimes degrade; an audit trail usually cannot.
  • A retriever timeout can be retried; a permission check can't be guessed.
  • In short: telemetry export may degrade, while missing auth, cross-tenant support lookup, raw-content redaction failure and required audit evidence fail closed.

Name the blast radius

Blast radius = the set of users a failure can reach.

Axis Example failure that spreads along it
Tenant A raw-prompt leak: usually tenant-scoped but workflow-wide
Workflow The same raw-prompt leak spans the whole workflow
Dependency A trace break at a queue boundary can hit one integration path across many tenants
Region A model outage may be regional
  • A misconfigured support tool can span every tenant.
  • Limiting blast radius along those axes is what lets one failure stay one incident.
  • The failure drills deep dive works through four more named failures and the abuse case.

7. Diagnose from the complaint down

  • A dashboard built from component metrics shows rates without telling anyone whether the user's experience improved.
  • So build it from one incident story, top down. The complaint: "the AI is slow and sometimes wrong."
Panel Shows
Top: user outcome Latency percentile, first-token time, failure and partial-answer rate, incident volume, affected tenant
Middle: likely causes Retrieval success, tool success, model error class, token cost. Request time split into retrieval, rerank, model queue, provider, tools and delivery.
Bottom: support mechanics Trace coverage, redaction rate, queue age for incidents, mean time to diagnose
  • Track completion, abandonment and support contacts alongside the technical signals. A system can get faster and still fail its users.

For latency: first token versus total time

  • Slow first token → prompt size, prefill, retrieval or queueing before generation.
  • Fast start that drags → a long decode, the token-by-token generation phase.
  • The neighbouring prompts deep dive explains why.

For a wrong answer: compare evidence with the answer

bad answer reported → did retrieval return relevant evidence?

  1. No: empty, stale or off-topic → the fault is upstream in retrieval. A better model can't answer from evidence it never received.
  2. Yes, but the answer contradicts it → suspect the model or the prompt construction (synthesis).
  3. Bad answer for only one tenant → suspect that tenant's configuration, access control or integration state before blaming the shared model.
  • This only works because of the signals kept in step 2:
    • Request and tenant correlation IDs.
    • Retrieval query fingerprints and document identifiers, not raw text.
    • Model version, prompt template version and generation settings.
    • Tool call status, latency and error class.
    • Outcome tags.

Alert on customer harm, not telemetry volume

  • Sustained latency above the SLO.
  • Elevated error rates.
  • Repeated empty retrievals.
  • A spike in fallback responses.
  • Critical tool failures.
  • A sudden rise in "wrong answer" feedback for one tenant or cohort.

Survive the dropped trace

  • Injection: sampling dropped the only bad trace.
  • Response: compare complaints with trace coverage → temporarily raise fidelity for the affected slice → reconstruct from gateway and dependency evidence → mark the gap → add error-class overrides and always-on exemplars.
  • A missing trace doesn't mean no failure. The sampling deep dive has the full four-step drill.

The two source incidents, in one line each (full versions in the deep dives)

Incident What the telemetry showed Response
Latency p95 22.18 s against a 7 s target. Retrieval 4.2 s, reranker 3.1 s, gateway queue 2.8 s, provider 9.36 s stacked up after a larger reranker and a model-route change. Roll back the route, cap candidates, enable a light-reranker fallback, keep EU traffic near an EU endpoint; load-test peak queue depth before repeating the experiment
Cost Requests +7%, input tokens +351%, cache hit rate 67% → 4%, and a larger prompt crossed an expensive model-routing threshold Roll back the template, restore compression and context caps, invalidate the flawed cache entries, version cost gates. The key also lost role_scope: a permission incident as well as a budget one.

8. Roll out in four phases with named owners

  • Observability fails socially before it fails technically. If no one owns a signal, no one owns the decision.
  • So the rollout has names, gates and exit criteria, not only components.

Four phases

Phase Owner Exit criterion
1. Define user-facing SLOs first Product and engineering, with the customer signing off Agreed latency targets, acceptable failures, support boundary, definition of a customer-visible incident. No agreement, no wider release.
2. Instrument one critical path The primary service team, with platform support One representative request traced end to end through auth, retrieval, model, tool and response assembly
3. Add the trace-linked support workflow Support engineering or customer success, with on-call defined A support agent moves from a complaint to a trace without asking the user for raw prompts
4. Add quality and cost signals with sampling The observability platform owner, with model and product owners setting thresholds Enough signal to detect regressions, sampling only what's needed

The weekly version (answer key)

  1. Weeks 0-1: SLOs.
  2. Weeks 1-2: a measurable "slow" and "wrong".
  3. Weeks 2-3: one instrumented path.
  4. Weeks 3-4: redaction scanning.
  5. Week 5: the support workflow.
  6. Weeks 6-8: quality and cost signals.

The eight-metric scorecard

Each metric has a calculation, an owner and an alert condition, so nobody argues about a number during an incident.

Metric Calculation Owner Alert when
Availability SLO Successful requests / total, excluding agreed out-of-scope failures Application engineering with platform The burn rate threatens the SLO
Latency SLO Latency at the agreed percentile, usually p95 or p99 Application engineering Sustained breach, or a breach after a release or canary
Retrieval and tool success Successes / attempts, by dependency and tenant The owning service team Below baseline, or a sudden shift in failure class
Token cost Tokens per successful request, or cost per tenant per day Product operations or finance partner Consumption rises faster than traffic, or exceeds budget
Quality-event rate Visible failures, escalations, reviewed bad outputs / sessions Product and ML engineering A meaningful rise after any release or config change
Trace coverage Traced requests / expected requests on the critical path Observability platform Below the minimum needed for the top failure path
Telemetry overhead Added latency, compute, storage, network versus baseline Platform and SRE Overhead materially raises latency or cost
Mean time to diagnose First report or alert to a credible root-cause hypothesis On-call engineering and support operations Stops improving, or exceeds the response target

SRE (site reliability engineering) = the team and practice that keeps production running. ML = machine learning.

Gates

  • Go/no-go: trace coverage at or above the minimum, and overhead not moving latency. Otherwise the release pauses.
  • Rollback triggers: loss of trace propagation, a spike in quality-event rate, or an unsustainable cost slope.

What is core, shared, adapter or configuration

Layer Contents
Configuration Per-customer sampling rates, retention windows, alert thresholds
Adapters Ticketing and alerting integrations
Shared service Collection, redaction, correlation propagation, the access gateway
Core product Request lifecycle, outcome tags, the minimal schema
  • That split keeps customer edge cases out of the core.

Launch readiness

  • A canary on one tenant or slice, and a fast rollback switch.
  • Old and new trace schemas interoperable during migration.
  • Support trained on what a healthy trace looks like.
  • A published operations guide: metric definitions, access rules, rollback steps.
  • Three artefacts before launch: an evidence policy, a response runbook and an access review.

Risk register

Risk Owner Mitigation Trigger
Sampling drops the only bad trace Observability platform Bias sampling toward error paths and reported incidents Support can't find evidence for an acknowledged failure
Telemetry becomes the bottleneck Platform and SRE Cap attributes, bound storage, monitor overhead Latency or cost rises after instrumentation changes
Support sees too much or too little Security and support engineering Role-based access, redaction, audit logging Sensitive content in support artefacts, or triage stalls
Quality signals are noisy Product and ML engineering Separate objective service metrics from subjective labels Alerts fire on expected experimentation
Adoption mistaken for success Product Track task completion and business outcome Usage rises while escalations and manual work stay flat

What proves the rollout worked

  • Mean time to diagnose.
  • The privacy invariant: zero raw content in any sink.
  • Trace coverage and telemetry overhead.
  • Latency, retrieval and tool success.
  • Quality-event rate and token cost by workflow.
  • Gate wider release on adequate trace coverage and tolerable overhead.

Quick Recall: Lines to Say in the Interview

  • "Slow and sometimes wrong is three problems: latency, correctness and diagnosability."
  • "The first design decision is what not to collect."
  • "Data never collected can't leak, can't overload the backend and costs nothing to store."
  • "500 requests a second, about 3,000 spans a second, about 110 to 155 GB for 30 days. The classifier, not disk, is the constraint."
  • "A 5% head sample drops 95% of the failures, so both keep decisions belong to the tail sampler."
  • "The observability path describes the request path; it can't authorise, alter or stall it."
  • "Telemetry export degrades; missing auth, cross-tenant lookup and required audit evidence fail closed."
  • "Compare the evidence with the answer before blaming the model."
  • "Observability fails socially before it fails technically, so every signal has an owner."

Technical deep dives

The goal: have the mechanism ready for every follow-up: redaction, sampling, failure drills, the two incidents, the neighbouring prompts and the cost and latency pivots.

30-Second Cheat Sheet

  • Classify before storage. A classifier after storage protects nothing. A keyed hash (HMAC) keeps correlation without content; a missing key is an error, never a silent plain hash.
  • Three executable contracts: idempotent ingestion, the privacy invariant, failure visibility via a finally block.
  • Queues carry only what their schema includes. Serialise trace context, idempotency key and tenant scope, or spans go orphan.
  • Audit has its own path, so an access event can't be sampled away.
  • Sampling drops the only bad trace: fix with error-class overrides, always-on exemplars and incident escalation. A missing trace isn't proof of health.
  • Latency incident: p95 22.18 s against 7 s, several small changes stacked. Cost incident: requests +7%, input tokens +351%, cache 67% → 4%, and a lost role_scope.
  • Pivot pattern: measure → route → bound → cache safely.

1. Redaction, keyed hashing and data boundaries

  • A classifier that runs after storage protects nothing: the raw value is already written, and every system that reads the store has it.
  • So classification happens before a value can reach a trace. A keyed hash then preserves correlation without retaining content.

The data model

Record Carries Never carries
Request Tenant ID, prompt, optional user ID
ExportedTrace A bounded, structured attribute dictionary: correlation ID, tenant ID, prompt classification, query hash, spans, result status Raw prompt text (by default)
  • The prompt enters on the request side and stops at the classifier. Only its classification and fingerprint cross.

Why the hash must be keyed

  • HMAC-SHA256 combines the value with a secret key before hashing.
  • Same prompt + same key → same fingerprint, so it can deduplicate and correlate repeated queries across the store.
  • A plain unkeyed hash does that too, but anyone can hash a list of common prompts and match the results: a dictionary attack.
  • Without the secret key, nobody can brute-force common prompts back out of an HMAC.
  • RFC 2104, section 3: HMAC keys must be random (or from a cryptographically strong generator) and periodically refreshed to limit the damage of an exposed key.

Key handling rules

  • The key lives in a vault and is rotated, because a leaked key re-enables the dictionary attack.

  • A missing key raises an error. Never fall back silently to a plain unkeyed hash: it looks like success while removing the protection.

  • Store a key version beside each fingerprint.

  • Rotation has a cost: a fingerprint under the old key never matches one under the new key.

    • Expect correlation across the rotation boundary to break, unless lookups try both keys during an overlap window.

Three executable contracts

Three tests that fail when the code drifts.

Test What it proves
Idempotent trace ingestion: post the same trace twice The second post returns "deduplicated", so a retry never double-counts
Privacy invariant: a request containing person@example.com The address never appears in the exported JSON; the query hash is present; the classification is "sensitive"
Failure injection: the retriever raises a timeout after acceptance The failure is still observable; the trace summary is written in a finally block with an outcome="partial_failure" field
  • The last test guards the central failure drill: sampling and redaction must never hide a failure.
  • A finally block emits the summary whether the request succeeds or throws.

Schema, cardinality and queue boundaries

  • Telemetry attributes are schema-validated at ingestion.
  • Unknown high-cardinality fields are rejected or collapsed into a bounded "other" bucket.
  • Ingestion is idempotent, so retries don't double-count.
  • Queue serialisation contracts carry trace context, idempotency key and tenant scope explicitly.
    • Instrumented HTTP clients and servers carry trace context in the W3C traceparent header.
    • A queue message carries only what its schema includes.
    • If correlation and tenant scope aren't serialised into it, the consumer starts a fresh trace, and spans after the handoff become orphan spans with no parent.

Idempotency key = an ID that lets the receiver recognise a repeat of the same message, so processing it twice has the effect of processing it once.

Two paths: debug traces and access audit

Path Records Properties
Trace store What failed where Sampled, short-lived
Audit store Who viewed which trace, when and why Stricter durability
  • If audit lived in the trace store, it would inherit trace sampling and short retention, and an access event could be sampled away.
  • Global dashboards aggregate across tenants; support views are tenant-scoped by role.
  • Test the access gateway for leakage and audit every break-glass use.

2. Sampling toward failures and the missing-evidence drill

  • The case's signature phrase: "sampling drops the only bad trace."
  • Uniform sampling keeps a fixed fraction of everything. A fixed fraction of a rare thing is often zero.
  • Example (illustrative, not a source figure): at a 5% uniform rate, a failure that happens three times in an hour has about an 86% chance of leaving no trace at all (0.95 cubed).
  • Expect the interviewer to inject this mid-round. Have the answer ready.

The policy that survives rare failures

  • Head sampling is cheap but can't know a request's final outcome.
  • Tail-biased retention costs more buffering but preserves slow and failed traces.
  • Combine four mechanisms:
    1. Normal low-rate sampling for ordinary traffic.
    2. Error-class overrides: every request with a given error class is kept.
    3. Always-on exemplars, whose linked traces are always kept, plus a low-rate stream of kept traces for each path even when nothing looks wrong.
    4. Temporary tenant or route escalation during an incident, raising fidelity for just the affected slice.
  • Monitor trace coverage against complaints and request errors. Never read a missing trace as proof of health.

The "sampling drops the only bad trace" drill

Step Sampling drops the only bad trace
Detection Compare complaint intake, request errors and anomaly signals against sampled trace volume. Complaints rising while traces for that workflow fall is a blind spot, not a healthy system.
Containment Switch the affected tenant, route or error class to higher-fidelity sampling temporarily; preserve the raw event envelope in a protected quarantine store if policy allows
Recovery Reconstruct from neighbouring evidence: API gateway logs, model gateway errors, dependency spans, support tickets. Mark the missing trace explicitly in the incident record.
Prevention Never let one global sampling rule govern all error paths. Use error-class overrides, low-rate always-on exemplars and per-tenant incident escalation hooks.
  • The strong first move: contain impact, preserve evidence and make the failure legible, recording the uncertainty that reconstruction leaves.
  • The weak move: defending the sampler or arguing about probability.

3. Failure drills, the abuse case and chaos practice

  • The failure policy (walkthrough step 6) says what each layer does when a dependency disappears.
  • Four more named failures get the full drill.
Failure Detection Containment Recovery Prevention
Tenant ID has a high-cardinality bug Cardinality budgets and exporter rejections; a spike in unique tenant labels is itself an incident Strip or normalise untrusted attributes at ingestion; collapse unknowns into "other" Fix the mapper; backfill only the minimal aggregates for the review Schema-validate attributes; reject unknown high-cardinality fields before export
Logs store a raw prompt Scanners and red-team tests search logs, traces and support transcripts for PII and secret formats Revoke sink access, rotate exposed credentials, quarantine the log set Delete or redact per retention policy and contract; notify owners Enforce redaction in code, in the collector and in review
Trace context breaks at a queue A trace starts, then vanishes after async handoff; orphan spans; a spike in "unknown root" events Propagate a minimal correlation envelope through the queue Stitch spans by correlation ID and timestamp; mark the join as reconstructed Queue contracts carry trace context, idempotency key and tenant scope, and are tested
Quality metric improves while adoption falls Pair technical metrics with completion rate, retries, abandonment, support contacts Treat it as a product problem, not a hotfix Product review, metric reset, possibly roll back the latest change Track task completion and business outcome, not usage volume alone
  • A raw-prompt export is a privacy incident, not a logging bug.
    • Contain access to the sink.
    • Rotate exposed credentials if necessary.
    • Delete or redact according to the contract.
    • Fix the exporter guardrail.

The abuse case

  1. A developer adds a raw prompt field to a debug span to speed up triage.
  2. It works once.
  3. Then it becomes the easiest way to move PII into every downstream system that reads traces.

The fix has three layers:

  • A redaction policy.
  • An exporter guardrail that strips the field.
  • A test that fails whenever exported telemetry contains raw sensitive strings.

The remaining operational rules

Situation Rule
Repeated downstream timeouts Breakers stop them
Buffer overflow Enters restricted quarantine with an incident marker
Audit sink failure Blocks the audited action or requires a human
Retrieval failure May retry once, then return a clearly reduced answer
Model limits May queue briefly or return a retry instruction

Chaos practice

  • Inject in staging: sampler loss, queue-boundary breakage, redaction regressions and dependency timeouts.
  • It proves the failure policy works before production forces the discovery.

4. The latency spike after a reranker and model-routing change

  • A slow pipeline is rarely one slow component. No single span explains this incident, and every small change looked safe on its own.

Setting and symptom

  • Product: a B2B (business-to-business) SaaS support copilot inside a live support console.
  • Expectation: agents want answers in under 5 seconds, because the customer is waiting in chat.
  • Path: Support Console → RAG API → query rewrite → hybrid retriever → cross-encoder reranker → context compressor → LLM gateway → model provider → response evaluator → UI stream.
  • Target: 7-second p95 with a 12-second hard timeout.

Cross-encoder reranker = reads the query and each candidate document together to re-score them. More accurate than the first-stage retriever, much slower per candidate.

  • Symptom (2026-07-08, peak European hours):
    • Agents saw the spinner for 18 to 35 seconds.
    • Some answers arrived after the human agent had already replied.
    • Handle time rose 21%.
  • Not an outage: success rate stayed acceptable, but p95 and p99 broke the SLO.

Telemetry

Signal Value
p50 / p95 / p99 (eu-central-1, 5-minute window) 5310 ms / 22180 ms / 34890 ms
Timeout rate 12.8% against a 1.1% baseline, over 1842 requests
Retrieval p95 4200 ms
Reranker 3100 ms; cross_encoder_large_v4; 80 candidates in, 12 out; batch size 1; GPU queue depth 29; light-reranker fallback off
LLM gateway queue 2800 ms; primary provider degraded; 1 retry, retry-after 750 ms
Provider latency 9360 ms, routed to us-east-1 from eu-central-1
Context compression 740 ms
Tokens 18500 in, 610 out
First token / total 14120 ms / 23840 ms against a 12000 ms timeout budget

How to read it

  1. p50 of 5.3 s is near normal; p95 and p99 are far above it. The tail broke, not the median, which already hints at queueing.
  2. Add the stage figures: 4,200 + 3,100 + 2,800 + 9,360 + 740 ms ≈ 20.2 s, before query rewrite, evaluation and streaming.
    • Stage percentiles don't add exactly, so treat it as a budget check.
    • It shows the 22.18 s p95 is several moderate delays stacked, not one broken service.
  3. First token at 14.1 s is already past the 12 s budget. That settles one tempting fix in advance.
  4. A 12-second hard timeout and a 22.18 s p95 coexist only because they sit at different boundaries: the timeout fires at the gateway while the console keeps waiting and measuring.
    • Confirm where each timeout is enforced and measured before using either number in an alert.

What changed and why

  • Two changes landed within 24 hours:
    1. The reranker moved from cross_encoder_small_v2 to cross_encoder_large_v4.
    2. The router moved standard answers from a faster mid-tier model to a larger one after a quality experiment.
  • Process failure: the canary ran only in low-traffic hours and never tested peak GPU queue depth.
  • Root cause = compounded latency: a larger candidate set, a slower reranker, a bigger context, gateway queueing and cross-region routing stacked up.
  • The pipeline broke its budget because several "small" changes landed together.

Debugging path

  1. Decompose the trace into spans and compare each stage's p95 with its baseline.
  2. Check candidate count, context tokens, queue time, provider latency and regional routing.
  3. Compare canary with control and peak with off-peak.
  4. Check whether timeouts land before or after the first token.
    • A 14-second first token means streaming can't rescue the experience: the user sees nothing until then.

Fix

Now

  • Roll back the model route.
  • Cap reranker candidates at 30.
  • Enable the light reranker when GPU queue depth exceeds 10.
  • Reduce max context tokens.
  • Route EU traffic to an EU-capable endpoint.

Later

  • A latency budget per stage, and load-test gates for reranker queue depth.
  • Context caps per workflow and circuit breakers for provider degradation.
  • Quality experiments must pass latency and cost SLOs, not only answer quality.

Abuse angle

  • Latency becomes a safety risk when users abandon the assistant or bypass review.
  • Broad queries that trigger large candidate sets and expensive reranking are a cheap denial-of-wallet or denial-of-service vector: the attacker spends little to make the system spend a lot.

The answer to give

Spoken answer (source): "I would start with span-level latency decomposition. The trace shows retrieval at 4.2s, reranker at 3.1s, LLM queue at 2.8s, and provider latency at 9.3s, with 18.5k input tokens. That means this is a pipeline-budget failure, not just one slow API. I would roll back the model route, cap reranker candidates, enforce context compression, add queue-depth fallback, and make future quality experiments pass p95 latency and timeout-rate gates."

  • The weak answer: "increase the timeout and maybe use a faster model." It never reads a span.

5. The cost spike from a prompt-template and cache-key regression

  • Production generative AI systems fail economically as well as technically.
  • This incident produced no quality complaint at all. The only symptom was a budget alert.

Setting and symptom

  • Product: an executive dashboard copilot summarising revenue, pipeline, customer-risk notes and operational metrics.
  • Path: UI → metrics API → CRM-note retrieval → prompt assembler → semantic cache → LLM gateway → cost attribution.

CRM (customer relationship management) = the sales system of record.

  • The cache key should include: tenant, dashboard type, date range, normalised query and data snapshot ID.
  • The router picks a mid-tier or a larger model by context size and sensitivity.
  • Symptom (2026-07-08): the daily budget alert fired at 14:20.
    • The CFO (chief financial officer) asked why the assistant had used almost four days of budget before lunch.
    • $912 against a $240 daily budget = 3.8 days.

Telemetry

Signal Value
Spend $240 daily budget; $912 actual; $1680 projected by end of day
Deltas Cost +280% (3.8×); requests +7%; input tokens +351%
Prompt template exec_summary_v6; average context 4200 → 19000 tokens
Context contents all_notes_90d instead of top_20_notes_30d; 500 table rows instead of a cap of 80; compression disabled
Cache Hit rate 4% against a 67% baseline; key v5 = [tenant_id, query_text]; missing date range, snapshot ID, role scope
Routing GPT-4-class because context_tokens>12000; 21384 tokens in, 1288 out; about 4.6× the per-request cost of before ($1.44 against $0.31)

How to read it

  1. Requests grew 7%, so users didn't cause a 3.8× bill.
  2. Input tokens grew 351%, so the cost is in the shape of each request.
  3. Template row: context grew from 4,200 to 19,000 tokens.
  4. Routing row: that growth pushed requests over the 12,000-token threshold into an expensive model.
  5. Cache row: the system stopped reusing answers.

What changed and why

  • exec_summary_v6 added "more supporting context" after executives asked for richer explanations.
  • The same release changed cache-key normalisation, dropped the date-range and snapshot fields, and disabled compression while debugging a formatting issue.

Root cause = three effects multiplying

  1. The template expanded context.
  2. The larger context crossed the routing threshold into the expensive model.
  3. The cache-key regression collapsed the hit rate, so every large prompt paid full price.
  • The two key changes pulled in opposite directions:
    • Keying on raw query_text instead of a normalised query fragmented the keys, and the new template started from a cold cache. Together they explain 67% → 4%.
    • Dropping date range, snapshot and role scope made each key match more requests. On its own that would raise the hit rate, and it created the over-sharing risk below.
  • Each effect alone would be a moderate increase. Together they compound.

Debugging path

  1. Start with cost per workflow, not global provider spend.
  2. Compare request count, input and output tokens, model route, cache hit rate and prompt version before and after the deploy.
  3. Sample traces to see what was assembled.
  4. Check whether the added context improved answers enough to justify its cost.

The hidden correctness bug

  • The key also lost role_scope.
  • One user's executive summary could be served to another role whenever the query text matched.
  • A cost incident turned out to be a permission incident too.
  • Cache changes need a security review as well as a cost review: a cache key defines who may receive a stored answer.

Fix

Now

  • Roll back exec_summary_v6.
  • Restore compression.
  • Cap CRM notes and table rows.
  • Force the mid-tier model for routine summaries.
  • Invalidate every cache entry written under cache_key_version=v5, because any might have been served across roles.

Later

  • Cost regression tests in CI and per-workflow token budgets.
  • Cost and latency approval for template upgrades.
  • Track hit rate by version.
  • Budget-aware routing with graceful degradation.

The answer to give

Spoken answer (source): "The telemetry shows usage grew only 7%, but input tokens grew 351%, cache hit rate dropped to 4%, and requests started routing to a GPT-4-class model. I would roll back the prompt template, restore compression, cap context, fix the cache key, and add CI gates for token and cost regression. I would also audit cache safety because missing role_scope can create data exposure."

  • The weak answer: "ask users to make shorter queries or switch to a cheaper model." It blames usage that grew only 7%.

6. Neighbouring prompts read from the same traces

  • The full design combines a group of interview prompts into one read: the anchor, the two incidents, three neighbouring prompts, then a card for every cost and latency pivot.
Case in the group What it contributes here
Observability for a Customer-Facing AI Application (anchor) Discovery, no-capture list, requirements, sizing, architecture, redaction, sampling, failure policy, triage, rollout and delivery (walkthrough steps 1 to 8, the redaction and sampling deep dives, and the fifty-minute plan in Practice)
Incident: latency spike after a reranker and model-routing change The latency spike deep dive
Incident: cost spike from a prompt-template and cache-key regression The cost spike deep dive
OpenAI practice prompt: Latency Regression in an LLM Application This deep dive, and pivot card 15.3
OpenAI practice prompt: RAG System with Poor Answer Quality Walkthrough step 7 and this deep dive
Reported OpenAI prompt: diagnose high latency in an LLM inference pipeline This deep dive
Playbook drill: LLM costs exploded after launch Pivot card 15.1
Scenarios 1, 2, 6, 7, 10, 11, 12 Pivot cards 15.2 to 15.8
Rate limits throttling at peak, users abandon mid-stream Pivot cards 15.9 and 15.10
  • Caveat: the sizing numbers in walkthrough step 4 come from the V2 tutorial's "My Perspective on the Gaps" note: supplementary, not chapter content.
  • The pivot cards live in the full casebook's Practice section.

Latency regression in an LLM application

Prompt: "An enterprise customer reports that responses have become slow."

  1. Clarify which latency: time to first token, time between tokens, total completion time or user-perceived latency.
  2. Decompose across ten stages:
    • Client and network
    • Authentication
    • Middleware
    • Retrieval
    • Prompt construction
    • Model prefill
    • Token generation
    • Tool calls
    • Post-processing
    • Streaming
  3. Check input and output token counts, and retrieval p95 and p99.
  4. Then check retry rates, rate-limit throttling and traffic patterns.
  5. Finish with model version, prompt changes, cache hit rates and regional routing.
  • The latency incident is this prompt with real numbers.

Follow-up: "it only happens at peak traffic."

  • Peak-only latency points at queueing, not a slower model. Separate queue wait from service time.
  • Queueing delay climbs steeply as utilisation nears 100%.
    • For a simple single queue, the wait is about ρ/(1−ρ) × service time at utilisation ρ.
    • That's 4× at 80% and 9× at 90%.
  • A rising p99 with a flat p50 usually means queueing.
  • Fix: add admission control and shed non-interactive work to batch.
  • Sourcing: the utilisation point comes from the source's additions file, section D; the multiples are simple single-queue arithmetic.
  • Related trap: a synchronous evaluator or logger on the hot path can cancel the benefit of streaming.

RAG with poor answer quality

  • Separate seven failure classes, and measure each separately:
    1. Retrieval
    2. Context assembly
    3. Reasoning or synthesis
    4. Prompt or instruction
    5. Output format
    6. Evaluation
    7. User experience
Layer Metrics
Retrieval recall@k, precision@k, and ranking metrics such as MRR or nDCG
Context assembly Citation correctness, context sufficiency
Generation Answer faithfulness, answer relevance, abstention quality
Whole application End-to-end task success

recall@k = fraction of all relevant documents that appear in the top k. precision@k = fraction of the top k that are relevant. MRR (mean reciprocal rank) averages one divided by the rank of the first relevant result. nDCG = normalised discounted cumulative gain.

  • The triage flowchart in walkthrough step 7 is the first cut; these metrics are the second.

Follow-up: "would you fine-tune the model?" Classify the problem first.

Problem type Usual fix
Knowledge Retrieval or data access
Behaviour Prompting, fine-tuning or structured output
Freshness Indexing and the data pipeline
Permission Access-control-aware retrieval
  • Fine-tuning mainly helps the behaviour problem. It's a poor fix for missing knowledge, stale indexing or unauthorised retrieval.
  • Ovadia et al. (2023) found unsupervised fine-tuning a weaker way to add knowledge than retrieval, on their benchmarks.

High latency in an LLM inference pipeline

  • The layer below the application. Walk the full stack: tokenisation, network, batch size, KV cache and post-processing.
  • Two facts carry the answer (source's additions file, section B):
Phase What it does Sets Scales with
Prefill Processes the whole prompt in parallel Time to first token Input tokens
Decode Generates one token at a time Tokens per second Output tokens
  • Frozen UI → prompt size, retrieval and queueing.
  • Fast start that drags → output length.

Applied to the latency incident

  • Most of the 14.1 s first-token time accrued before the provider started: retrieval, reranking, compression and gateway queueing account for about 10.8 s, and 18,500 input tokens add prefill on top.
  • The 9.7 s from first token to completion for 610 output tokens is slow decode, cross-region round trips and streaming.
  • Both halves need attention.

The rest of the stack

  • Batch size trades throughput for per-request latency. With continuous batching nothing waits for a batch to fill, but each decode step slows as more sequences share it.
  • KV cache (key–value) holds attention state for tokens already processed, so the model doesn't recompute the prompt for every new token.
    • Its memory caps how many sequences fit on a GPU at once.
    • A full cache forces queueing or preemption.
    • Kwon et al. (2023) and the vLLM tuning guide describe these limits.
  • Post-processing is usually small, but a synchronous evaluator or logger on the hot path isn't.
  • The same stack walk anchors the LLM Inference Serving case, so prepare it once.

7. The cost and latency pivot pattern

  • Ten members of this prompt group are the same system asked a cost or latency question.
  • Every strong answer runs through four verbs, in order:
  1. Measure. Attribute cost and latency per stage, tenant, workflow, model and prompt version first. Segregate batch and evaluation spend from interactive traffic so they can't hide inside it.
  2. Route. Match model and path to risk: simple tasks go to smaller models.
  3. Bound. Cap output length, context, top-k, retries, agent steps, timeouts and budgets.
  4. Cache safely. Cache only with tenant, permission scope and version in the key.

Three recurring situations

Situation Move
Peak HTTP 429 (rate-limit) errors Separate the provider's limits from your own gateway's; shed non-interactive work
Abandoned streams Cancel generation and in-flight tools. Saves spend only where the provider stops generating on cancel: some hosted providers keep billing after a client cancels, while self-hosted engines such as vLLM's OpenAI-compatible server abort generation on disconnect.
Sudden cache miss Inspect normalisation, prompt prefix bytes, TTL and version before adding capacity

TTL (time to live) = how long a cached item stays valid.

Prompt cache versus response cache

  • Prompt caching is a byte-exact prefix match. One changed byte invalidates everything after it.
  • Silent-miss causes: a timestamp in the system prompt, unsorted JSON keys, a reordered tool list or a model swap.
  • The Claude and OpenAI prompt-caching documentation both describe this exact-prefix behaviour.
Cache What it reuses Saving Watch for
Provider prompt cache The processed prefix; the model still generates Input cost and first-token time Any changed prefix byte causes a silent miss
Application response cache (as in the cost incident) The whole answer; skips the model call The full call Key must carry tenant, permission scope and data version

The pivot cards

  • Each pivot gets a card: the dominant driver, the cheapest lever, the metric that proves it, the move to refuse and the line to say.
  • Shared customer-communication sentence: "Acknowledge impact, show measured cause, provide immediate mitigation, then explain long-term prevention and success metric."
  • The ten cards are in the full casebook's Practice section, so you can attempt each before revealing it.

8. References

Primary references

Fact-check sources from the original case (checked 27 September 2026)

Source Supports
Grafana Tempo docs: Manage trace ingestion Typical span size (~500 bytes) behind the storage sizing
RFC 2104: HMAC, section 3 Keys HMAC keys must be random and periodically refreshed
OpenAI API docs: Deprecations GPT-4-class list prices. A 21,384-token prompt exceeds the 8K GPT-4 context, so the 32K model's list prices of $60 per million input and $120 per million output tokens apply: 21,384 in and 1,288 out cost about $1.44.
Ovadia et al. 2023, Fine-Tuning or Retrieval? (arXiv 2312.05934) Fine-tuning is a weak way to add knowledge compared with retrieval
Kwon et al. 2023, Efficient Memory Management for LLM Serving with PagedAttention Continuous batching and KV-cache limits
vLLM docs: Optimization and Tuning Batch size, preemption and chunked prefill trade-offs
GDPR (Regulation 2016/679), Recital 26 Pseudonymised data is still personal data
EDPB Guidelines 01/2025 on Pseudonymisation Keyed hashes as pseudonymisation, not anonymisation
GDPR Article 17: Right to erasure Deletion requests reach linked fingerprints
Claude docs: Prompt caching Exact prefix match; timestamps, unsorted JSON, tool changes and model swaps break the cache
OpenAI API docs: Prompt caching Exact prefix match and minimum cacheable length
OpenRouter help: Which providers stop billing when a stream is cancelled Cancelling a stream stops billing only on some providers
vLLM docs: OpenAI-compatible server Self-hosted engines abort generation on client disconnect

Quick Recall: Lines to Say in the Interview

  • "A classifier after storage protects nothing; a missing HMAC key is an error, never a plain hash."
  • "A queue message carries only what its schema includes, so trace context and tenant scope go in the contract."
  • "Audit has its own durable path, so an access event can't be sampled away."
  • "A fixed fraction of a rare thing is often zero. A missing trace isn't proof of health."
  • "A raw-prompt export is a privacy incident, not a logging bug."
  • "Retrieval 4.2, reranker 3.1, queue 2.8, provider 9.36 seconds: a pipeline-budget failure, not one slow API."
  • "Requests up 7%, input tokens up 351%: the cost is in the shape of each request."
  • "A cache key defines who may receive a stored answer."
  • "Measure, route, bound, cache safely."

Quick review

One sentence (the source's sixty-second close): correlate every request, collect structured evidence without raw content, retain anomalies preferentially, and let support trace a complaint to a cause within its tenant. Prove both privacy and low overhead before widening rollout.

30-Second Cheat Sheet

  • Ask first: what is slow, what is wrong, which tenants, what is forbidden to collect, who may diagnose, what overhead and retention.
  • Two paths: the request path serves; the span path describes it and never blocks the user.
  • No-capture by default: full prompts, raw documents, secrets, unbounded labels.
  • Redact before storage; a missing HMAC key is an error.
  • Keep rare failures with error overrides, exemplars and incident sampling.
  • Fail closed on missing auth, cross-tenant lookup and required audit evidence.
  • Two incidents: latency p95 22.18 s vs 7 s (stacked delays); cost +7% requests, +351% input tokens, cache 67% → 4%, lost role_scope.
  • Pivots: measure, route, bound, cache safely.

1. Recall the path, the rules and the incidents

Ask first

  1. What is slow?
  2. What is wrong?
  3. Which tenants?
  4. What content is forbidden to collect?
  5. Who may diagnose?
  6. What overhead and retention are acceptable?

The whiteboard path

  • Request: auth/tenant → retrieval → LLM → tools → response.
  • Spans: async collector → classify/redact/HMAC → error-and-slow-biased sampling → bounded store → global aggregate and tenant-scoped support views.
  • Access audit is separate.
  • Telemetry export never blocks the user.

Four rules

  1. No full prompts, raw documents, secrets or unbounded labels by default.
  2. Redact before storage; a missing HMAC key is an error.
  3. Keep rare failures with error overrides, exemplars and incident sampling.
  4. Missing auth, cross-tenant lookup and required audit evidence fail closed.

Numbers and incidents

Sizing is illustrative, from the supplementary V2 gap note.

Item Value
Raw span rate 500 requests/s × six spans ≈ 3,000 raw spans/s
Kept Errors and slow traces, plus about 5% of normal traffic
Storage About 110–155 GB for 30 days at 200 bytes a span
Real constraint The classifier, not disk
Latency incident p95 22.18 s against 7 s, from stacked retrieval (4.2 s), reranker (3.1 s), queue (2.8 s) and provider (9.36 s) delays; the canary never tested peak
Cost incident Traffic +7%, input tokens +351%, cache 67% → 4%, routing threshold crossed; missing role_scope also risked leakage

Diagnosis

  1. Start at the user outcome, then stage spans.
  2. Empty or stale retrieval → upstream.
  3. Good evidence contradicted by the answer → model or prompt.
  4. One tenant → configuration, access or integration.
  5. First-token versus total time separates prompt and prefill from a long decode.
  • A missing trace is not proof of health.

Rollout

  1. SLOs.
  2. One critical path.
  3. The support workflow.
  4. Quality and cost signals with sampling.
  • Go/no-go on trace coverage and overhead.
  • Roll back on lost propagation, a quality-event spike or an unsustainable cost slope.

Pivots

  • Measure, route, bound, cache safely.
  • Contain, attribute, then diagnose.

Key takeaways

Topic Takeaway
The complaint "Slow and sometimes wrong" is three problems (latency, correctness, diagnosability), each made measurable before any design
No-capture list The first design decision: full prompts, raw documents, secrets and unbounded labels stay out by default
Requirements Stated so a test can fail them; the support workflow is the functional core and overhead is a budget
Sizing Telemetry cost is set by collection policy; storage is small and the classifier is the real constraint
Architecture Tracing-first; the observability path can't block the request path and nothing raw crosses the trust boundary
Redaction Classification and keyed hashing before storage; three tests pin idempotency, privacy and failure visibility
Sampling Tail-biased with error overrides and exemplars, because uniform sampling drops the only bad trace
Failure policy Every layer has one; audit evidence fails closed where user answers can degrade
Diagnosis Dashboard built top down from the complaint; wrong answers triaged by comparing evidence with output
Latency incident Compounded latency from several small changes, found only by comparing each span with its baseline
Cost incident Prompt growth, a routing threshold and a broken cache key multiplying, hiding a permission leak
Neighbouring prompts Three practice prompts are the same traces at different depths: stage decomposition, the seven RAG failure classes, the inference stack
Rollout Four phases with named owners, an eight-metric scorecard, explicit go/no-go gates and a risk register
Delivery The fifty minutes go to the no-capture list, the dropped-trace drill and the support test
Pivots Every cost and latency pivot answered with a card built from measure, route, bound and cache safely

Sixty-second close (source): "Correlate every request, collect structured evidence without raw content, retain anomalies preferentially, and let support trace a complaint to a cause within its tenant. Prove both privacy and low overhead before widening rollout."


Flashcard Drill


Quick Recall: Lines to Say in the Interview

  • "What's slow, what's wrong, which tenants, and what am I forbidden to collect?"
  • "Telemetry export never blocks the user."
  • "Redact before storage; a missing HMAC key is an error."
  • "Missing auth, cross-tenant lookup and required audit evidence fail closed."
  • "3,000 spans a second, 110 to 155 GB for 30 days: the classifier, not disk, is the constraint."
  • "22.18 seconds against 7 was several delays stacked, and the canary never tested peak."
  • "Traffic up 7%, input tokens up 351%, and the cache key lost role_scope."
  • "A missing trace is not proof of health."

Where next