Tracing, SLOs and Incident Response

Updated · 10 min read
hardPython 3.13aiobservabilitytracingsloincidentsreliability

Observability is being able to answer "what happened to this request, and why?" from the data a system records. For an AI application, that means tracing each request through retrieval, the model and any tools, with the versions of the prompt, model and index used. Service level objectives (SLOs) turn "reliable" into numbers, and an error budget says how much failure is acceptable. When something breaks, graceful fallbacks protect users and a practiced incident process gets the service back.

"Monitoring Quality, Cost and Latency" covered dashboards and alerts. This lesson goes inside a single request, and through a bad day.

The Vocabulary

TermDescription
TraceIt is used to follow one request end to end, with a shared request ID
SpanOne step inside a trace: retrieval, model call, tool call, with its status and details
SLIA service level indicator: a measured number, such as availability or 95th-percentile latency
SLOIt is used to set a target for an SLI, such as 99.5% of requests succeeding each month
Error budgetThe failures the SLO allows: 0.5% of 60,000 requests is 300
FallbackIt is used to give users a safe, honest answer when a dependency fails
RunbookStep-by-step instructions for a known kind of incident

Example: Tracing a Request Through Failures

This program handles the same question three times: normally, with the model provider timing out, and with the search index down. call_model stands in for a hosted model call, with a fixed reply and token counts, so the example runs offline; the tracing and fallbacks are the real point.

Trace every request, budget for failure, fail safely, learn from incidents
Python
import itertools
import json
 
ids = itertools.count(1)
FAQ = {"library": "The library fee is $15 a year and covers book loans and printing."}
 
class Trace:
    """Records every step of one request under one ID, so a failure can be followed end to end."""
    def __init__(self, request_id):
        self.request_id, self.spans = request_id, []
    def span(self, name, status, **detail):
        self.spans.append({"trace": self.request_id, "span": name, "status": status, **detail})
 
def retrieve(question, trace, index_up):
    if not index_up:
        trace.span("retrieval", "error", error="vector index unavailable")
        raise ConnectionError("index down")
    doc = FAQ["library"] if "library" in question.lower() else None
    trace.span("retrieval", "ok", found=bool(doc), index_version="faq-2026-07")
    return doc
 
def call_model(prompt, trace, provider_up):
    if not provider_up:
        trace.span("model", "error", error="provider timeout after 10 s", model="model-v3")
        raise TimeoutError("provider timeout")
    trace.span("model", "ok", model="model-v3", prompt_version="p-12", tokens_in=410, tokens_out=24)
    return "The library fee is $15 a year. (Source: Fee Schedule 2026-27)"
 
def handle(question, provider_up=True, index_up=True):
    trace = Trace(f"req-{next(ids):04}")
    try:
        doc = retrieve(question, trace, index_up)
        try:
            reply = call_model(f"{doc}\n{question}", trace, provider_up)
        except TimeoutError:
            # Fallback 1: the model is down, but we have the source text: show it directly
            reply = f"(Our assistant is busy. From the school documents:) {doc}" if doc else "Please try again soon."
            trace.span("fallback", "used", kind="show source text")
    except ConnectionError:
        # Fallback 2: search is down: say so honestly and raise an alert, never guess
        reply = "Search is temporarily unavailable. Please try again in a few minutes or contact the office."
        trace.span("fallback", "used", kind="safe message", alert="page on-call: index down")
    trace.span("response", "ok")
    print(f"{trace.request_id}: {reply}")
    for s in trace.spans:
        print("   ", json.dumps({k: v for k, v in s.items() if k != "trace"}))
    print()
 
handle("How much is the library fee?")
handle("How much is the library fee?", provider_up=False)
handle("How much is the library fee?", index_up=False)
Output
req-0001: The library fee is $15 a year. (Source: Fee Schedule 2026-27)
    {"span": "retrieval", "status": "ok", "found": true, "index_version": "faq-2026-07"}
    {"span": "model", "status": "ok", "model": "model-v3", "prompt_version": "p-12", "tokens_in": 410, "tokens_out": 24}
    {"span": "response", "status": "ok"}
 
req-0002: (Our assistant is busy. From the school documents:) The library fee is $15 a year and covers book loans and printing.
    {"span": "retrieval", "status": "ok", "found": true, "index_version": "faq-2026-07"}
    {"span": "model", "status": "error", "error": "provider timeout after 10 s", "model": "model-v3"}
    {"span": "fallback", "status": "used", "kind": "show source text"}
    {"span": "response", "status": "ok"}
 
req-0003: Search is temporarily unavailable. Please try again in a few minutes or contact the office.
    {"span": "retrieval", "status": "error", "error": "vector index unavailable"}
    {"span": "fallback", "status": "used", "kind": "safe message", "alert": "page on-call: index down"}
    {"span": "response", "status": "ok"}

Explanation:

  • Every span carries the request ID and what matters for debugging: whether retrieval found anything, the index, model and prompt versions, and tokens. When a parent reports a wrong answer, the trace shows exactly which versions produced it.
  • Provider timeout: the trace shows the model span failed. Instead of an error page, the fallback shows the retrieved source text directly: less polished, still correct.
  • Index down: there's nothing safe to answer from, so the fallback says so honestly and pages the on-call person. It never lets the model guess without sources.
  • Traces must follow the privacy rules from "Data Leakage and Privacy Attacks": record versions, statuses and counts, not personal data or secrets.

Example: SLOs and the Error Budget

This program checks a made-up month of 60,000 requests against two SLOs: 99.5% availability and a 95th-percentile latency under 2 seconds. Day 18 has an outage followed by a slow recovery.

Python
import numpy as np
 
# A made-up month of Campus Helper requests: 30 days x 2,000 requests, with an incident on day 18
rng = np.random.default_rng(31)
days, per_day = 30, 2000
latency = rng.lognormal(mean=np.log(900), sigma=0.45, size=(days, per_day))     # milliseconds
failed = rng.random((days, per_day)) < 0.001                                     # normal: 0.1% errors
failed[17, 200:500] = True                                                       # day 18: a 300-request outage
latency[17, 500:900] *= 4                                                        # then slow recovery
 
SLO_AVAILABILITY, SLO_P95_MS = 0.995, 2000         # targets agreed with the school office
total = days * per_day
budget = (1 - SLO_AVAILABILITY) * total            # failures we can afford this month
print(f"Requests this month: {total:,}; error budget at {SLO_AVAILABILITY:.1%}: {budget:.0f} failed requests")
print(f"Failed requests: {failed.sum()} -> availability {1 - failed.mean():.3%}, budget used {failed.sum() / budget:.0%}")
p95 = np.percentile(latency, 95, axis=1)
print(f"Days with 95th percentile latency over {SLO_P95_MS} ms: {[int(d) + 1 for d in np.where(p95 > SLO_P95_MS)[0]]}")
print(f"Month 95th percentile: {np.percentile(latency, 95):.0f} ms; day 18: {p95[17]:.0f} ms")
 
print("\nError budget burned by day 18 alone:", f"{failed[17].sum() / budget:.0%}")
Output
Requests this month: 60,000; error budget at 99.5%: 300 failed requests
Failed requests: 378 -> availability 99.370%, budget used 126%
Days with 95th percentile latency over 2000 ms: [18]
Month 95th percentile: 1936 ms; day 18: 4790 ms
 
Error budget burned by day 18 alone: 100%

Explanation:

  • The SLO of 99.5% allows 300 failed requests this month: that is the error budget.
  • 378 requests failed, so availability was 99.370%, and 126% of the budget was used: the SLO was missed.
  • Day 18 alone used 100% of the budget. One incident cost a whole month's allowance, and its 95th-percentile latency (4,790 ms) broke the latency SLO too, while the month overall (1,936 ms) still looks fine. Averages hide incidents; check per day.
  • Teams use the budget to decide: with budget left, ship changes; with it spent, slow releases and fix reliability first.

Releasing and Recovering Safely

PracticeWhat it does
Canary releaseA small share of traffic tries the new version first
Blue/greenTwo full environments; switch traffic between them instantly
Shadow testingIt is used to send copies of real requests to a new version without showing users its answers
Version rollbackRoll back the model, the prompt or the index separately
Graceful degradationSmaller model, cached answers or source text when the main path fails
Rate limits and budgetsIt is used to cap traffic and spending per user and per day

Handling an Incident

StepWhat to do
1. DetectAn alert or user report; open an incident and name a lead
2. MitigateProtect users first: roll back, switch to a fallback, or turn a feature off
3. CommunicateTell affected users and the team what is happening and when to expect an update
4. FixFind and fix the cause; check with the evaluation set before re-enabling
5. ReviewA blameless review: what happened, why, and what changes prevent it; add a test

Common Mistakes

Logs without a request ID. You can't connect the retrieval, model and tool steps of one request.

No version in the trace. You can't tell which prompt or index produced a bad answer.

An error page as the only fallback. Design a safe answer for each failure.

Monthly averages only. One bad day can hide inside a good month.

Interview Corner

What would you put in a trace for an LLM request?

A request ID shared by every span; spans for retrieval, model and tool calls with status, timing, errors, and the versions of the prompt, model and index; and token counts, without personal data or secrets.

What is an error budget?

The amount of failure an SLO allows over a period; for 99.5% availability on 60,000 requests, 300 failures. When the budget is spent, the team prioritizes reliability over new releases.

Practice

Exercise: a third fallback. Add a case where retrieval finds nothing for the question (for example "Is there a swimming pool?") and the model is down. What should the user see, and what should the trace record?

Check your understanding:

  1. What did the fallback show when the model provider timed out?
  2. How much of the error budget did day 18 use?
  3. Why mitigate before investigating?

Quick check: tracing, SLOs and incidents

4 questions
1What happened when the search index was down?
2How many failures did the 99.5% SLO allow in 60,000 requests?
3What is shadow testing?
4What is the first step after detecting an incident and naming a lead?

Key Takeaways

Quick reference

NeedPractice
Follow a requestOne request ID across all spans
Debug answersRecord prompt, model and index versions
Set targetsSLIs, SLOs and an error budget
Survive failuresA safe fallback per dependency
Release safelyCanary, blue/green, shadow, rollback
LearnBlameless review and a new test

Was this tutorial helpful?

Lesson 163 of 186