Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 5: Production operations

Chapter 18Reliability engineering for AI

30 min read, 1 lab, Intermediate

A 99.9% availability target leaves you 43 minutes of failure a month, and an LLM product can burn that in one afternoon of provider 429s, or lose a week of quality without a single error. This chapter turns reliability engineering into numbers and mechanisms for AI services: SLOs that include quality, failure modes you will actually meet, and the retries, fallbacks and load shedding that keep users served when parts break.

After this chapter you can

  • Define SLIs and SLOs for latency, availability and answer quality, and compute an error budget
  • Recognise failure modes specific to AI services, from XID errors to runaway agents
  • Design timeouts, retries with backoff, hedging and fallbacks that do not make outages worse
  • Apply load shedding and graceful degradation to protect a saturated model server
  • Plan capacity and headroom for GPU services that take minutes to scale
  • Run on-call, runbooks, blameless reviews and chaos experiments for an AI platform

SLIs, SLOs and error budgets for AI

A service level indicator (SLI) is a measured ratio of good events to total events, such as the share of requests answered successfully. A service level objective (SLO) is the target for that ratio over a window, such as 99.5% over 28 days. The error budget is what the SLO allows to fail: with 99.5% over 28 days, about 3.4 hours of total failure or 0.5% of requests.

The error budget is a decision tool. While budget remains, the team ships and takes risks; when it is spent, reliability work takes priority.

SLO typeGood eventExample target
AvailabilityRequest returns a usable response (not 5xx, not timeout)99.5% over 28 days
TTFT latencyFirst token within 1.5 s95% of requests
Inter-token latencyAverage gap under 60 ms99% of streaming requests
QualitySampled response passes the judge rubric97% weekly, on a fixed sample
Agent completionRun reaches a final answer within its step budget95% of runs

Write latency SLOs on TTFT and inter-token latency, not total duration, for the reasons covered in Observability for AI systems. Quality is an SLO, not a vibe: define a sampled, judge-scored good-event rate, give it a budget, and treat a breach like an outage. A model that answers fast and wrong is down from the user's point of view.

Alerting on burn rate

Burn rate is how fast you are spending budget relative to plan: a burn rate of 1 spends exactly the budget over the window. The Google SRE Workbook recommends multiwindow, multi-burn-rate alerts. A page fires when both a long and a short window burn fast, so you catch real incidents quickly and the alert clears soon after recovery.

slo-alerts.yaml (Prometheus rule)
groups:
  - name: chat-slo
    rules:
      - alert: ChatAvailabilityFastBurn
        # 99.9% SLO: 14.4x burn spends 2% of a 30-day budget in 1 hour
        expr: |
          (sum(rate(llm_requests_total{status="error"}[1h]))
            / sum(rate(llm_requests_total[1h]))) > (14.4 * 0.001)
          and
          (sum(rate(llm_requests_total{status="error"}[5m]))
            / sum(rate(llm_requests_total[5m]))) > (14.4 * 0.001)
        labels:
          severity: page
      - alert: ChatTTFTSlowBurn
        # Latency SLI: share of requests with TTFT at or under 1.5 s (needs a 1.5 bucket)
        expr: |
          (1 - sum(rate(llm_ttft_seconds_bucket{le="1.5"}[6h]))
                / sum(rate(llm_ttft_seconds_count[6h]))) > (6 * 0.05)
        labels:
          severity: ticket

Failure modes unique to AI services

AI services fail in all the ordinary ways and several new ones. The new ones are either hardware-heavy (GPUs fail more often than CPUs and take a whole replica with them) or silent (the system keeps returning 200s while being wrong).

FailureHow it shows upFirst response
GPU hardware faultXID errors in the kernel log, pods crash, DCGM_FI_DEV_XID_ERRORS nonzeroCordon and drain the node; see below
GPU out of memoryCUDA OOM on long prompts or large batches, server restartsCap context length and concurrency; reserve memory headroom
Provider outage5xx or timeouts from a hosted APIFail over to another provider or self-hosted model
Rate limitsHTTP 429 with a retry-after header, token-per-minute quota exhaustedBack off, queue, shift traffic, request quota ahead of launches
Silent quality regressionJudge scores or user feedback drop, no errorsRoll back the model or prompt; pin provider model versions
Runaway agentSteps, tokens and cost per run climb; one run makes hundreds of callsEnforce step, token, time and cost budgets per run
Cold startNew replica takes minutes to download weights and warm upKeep warm headroom; cache weights on local disk

XID errors are error codes the NVIDIA driver writes to the kernel log (dmesg) when something goes wrong on a GPU. Some point at your software, others at the hardware. NVIDIA's XID catalog lists them all; these are the ones worth memorising.

XIDMeaningUsual cause
13, 31Graphics engine exception, GPU memory page faultUsually an application or driver bug, like an illegal memory access
48Double-bit ECC errorUncorrectable memory error; drain and reset the GPU
79GPU has fallen off the busDriver lost contact with the GPU; drain the node, likely hardware
94, 95Contained and uncontained ECC error95 means the error could not be isolated; reset the GPU
On a GPU node
sudo dmesg -T | grep -i xid          # NVRM: Xid (PCI:0000:3b:00): 79, GPU has fallen off the bus
nvidia-smi -q -d ECC,RETIRED_PAGES   # ECC counters and page retirement or row remapping
kubectl cordon gpu-node-17 && kubectl drain gpu-node-17 --ignore-daemonsets --delete-emptydir-data

Automate this. A node health checker that watches XID events and cordons the node removes the need for a human at 3 a.m. and stops the scheduler from placing new pods on a broken GPU.

Timeouts, retries and hedging

Every call to a model needs a timeout, and for streaming calls it needs two: a TTFT timeout (how long to wait for the first token) and an idle timeout (the longest allowed gap between tokens). A single overall timeout either kills long, healthy generations or waits far too long on a dead backend.

Retries recover transient failures but can turn a brownout into an outage. If every client retries three times against an overloaded server, offered load quadruples at the worst moment. Three rules keep retries safe:

  • Exponential backoff with jitter. Wait random(0, base * 2^attempt), capped, so retries spread out instead of arriving in waves.
  • A retry budget. Allow retries only while they stay under about 10% of total requests, and never retry on a 429 sooner than its retry-after header.
  • Retry only what is safe to repeat. A model call is safe to repeat. A tool call that sends an email or charges a card is not, unless it carries an idempotency key.

Hedging sends a second copy of a request if the first has not answered within, say, the p95 latency, then uses whichever answers first and cancels the other. It cuts tail latency for cheap, short calls such as embeddings or classification. For long generations it doubles token cost, so hedge only on the TTFT phase and cancel the loser as soon as one stream starts.

Fallbacks, load shedding and graceful degradation

A fallback is a cheaper or more available way to answer when the preferred path fails: a smaller model, another provider, a cached answer, or a plain non-AI response. Plan them as a ladder, from full quality down to an honest error, and decide in advance which rung each product surface may drop to.

Load shedding rejects some work early so the rest succeeds. A GPU server has a hard throughput limit set by its batch size and KV cache. Above that limit, queues grow without bound and every request's latency rises until all of them time out, so the server does full work and delivers nothing. Shedding at a concurrency cap keeps admitted requests inside the SLO.

TechniqueHow it worksGood for
Concurrency capReject or reroute when in-flight requests exceed N per replicaProtecting a model server from overload
Queue with deadlineDrop queued requests whose deadline has already passedAvoiding work nobody is waiting for
Priority sheddingShed free-tier or batch traffic before paid interactive trafficMulti-tenant platforms
Output capsLower max_tokens or context length under loadTrading answer length for capacity
Feature degradationTurn off reranking, extra agent steps or long-context modeKeeping core answers flowing

A circuit breaker completes the picture. After a run of failures to one backend it opens and sends traffic straight to the fallback for a cool-down period, then lets a few probe requests through. This stops a dead provider from costing every request a full timeout.

Capacity planning and headroom

Capacity planning answers "how many replicas do we need at peak, plus how much spare?". Start from measured per-replica throughput at your latency SLO, not from the throughput the server reaches with unlimited queueing. Little's law ties the numbers together: average requests in flight equal arrival rate times average time in the system.

Worked example
Peak traffic                 12 requests/s
Average request duration     6 s (prompt 800 tokens, 250 output tokens)
In flight at peak            12 x 6 = 72 concurrent requests
Measured cap per replica     16 concurrent requests while p95 TTFT stays under 1.5 s
Replicas for peak            72 / 16 = 4.5 -> 5
Plus N+1 for a GPU failure   6
Plus scale-up lag headroom   traffic grows 20% in the 8 min a new replica needs -> 7

The last line is what makes GPU capacity planning different. A web pod starts in seconds; a model replica needs a GPU node, a multi-gigabyte weight download and warm-up, often 5 to 15 minutes. Headroom must cover the scale-up lag, because autoscaling cannot rescue a spike that is shorter than the time it takes to add capacity. Scaling and routing inference covered the autoscaler mechanics; here the point is to budget for them.

Multi-provider and multi-region strategy

Hosted model APIs have outages and regional capacity limits like any cloud service, and self-hosted GPUs concentrate risk in a few expensive nodes. Spreading across providers or regions buys availability at the cost of complexity and of behaviour differences between models.

Multi-provider

  • Survives a single provider outage or quota cut
  • Needs a gateway that normalises APIs
  • Different models answer differently; evals per pair
  • Prompts may need per-provider variants

Multi-region

  • Survives a regional outage or capacity shortage
  • Same model, so behaviour is consistent
  • GPU capacity per region is scarce and uneven
  • Data residency rules may forbid some regions

Self-hosted fallback

  • Small open model you fully control
  • Covers provider outages and rate limits
  • You run the GPUs and own their failures
  • Lower quality; mark answers as degraded

An untested fallback is a guess. Route a small share of real traffic, say 1%, through the fallback path at all times so you know it works and see its quality scores.

On-call, runbooks and blameless reviews

Reliability is a practice as much as a design. An AI platform's on-call rotation needs alerts that map to SLOs, and a runbook for each alert: a short, tested document that says what the alert means and what to do first.

runbook: ChatAvailabilityFastBurn
Meaning   Error ratio is burning the 30-day budget 14x faster than planned.
Check     1. Gateway dashboard: which backend returns errors? (5xx, 429, timeout)
          2. Provider status page and our 429 count per provider.
          3. GPU row: XID errors, pod restarts, OOM kills in the last hour.
Act       Provider errors   -> set gateway weight for provider to 0, confirm fallback serving.
          GPU node errors   -> cordon node, confirm replicas rescheduled.
          Recent deploy     -> roll back model or prompt (see Model deployment pipelines).
Escalate  If not mitigated in 30 min, page the platform lead.

After an incident, write a blameless postmortem: a timeline, contributing causes, what went well, and action items with owners. Blameless means you ask how the system let a reasonable person make that choice, because people who fear blame hide the information you need.

  1. Detect

    An SLO burn alert pages on-call. Record when the problem started versus when the alert fired; the gap is a detection action item.

  2. Mitigate

    Restore service first with the cheapest safe lever: shift traffic, roll back, shed load. Root cause can wait.

  3. Communicate

    Post status updates on a fixed cadence, internally and to customers, even when there is nothing new.

  4. Review

    Within a week, hold the blameless review and file action items that change the system, such as a new alert, a guardrail or an automated drain.

Chaos experiments

A chaos experiment deliberately injects a failure to test a hypothesis about how the system behaves. You state the steady state (the SLO holds), predict the outcome ("if the primary model dies, the gateway falls back within 5 s and the SLO holds"), inject the fault in a controlled scope, and compare. Failed predictions are the valuable result.

ExperimentInjectionWhat you learn
Kill a model replicaDelete the pod or stop the containerRetry and rescheduling behaviour, real recovery time
Slow backendAdd latency with a proxy such as ToxiproxyWhether timeouts and hedging are set correctly
Provider rate limitReturn 429 from a fake provider or gatewayBackoff, quota alerts, fallback routing
GPU lossCordon and drain a GPU nodeCapacity headroom, scheduling time, cold-start cost
Bad modelDeploy a candidate that fails evals in stagingWhether the deploy gates and canary catch it

Start in staging, then run small, announced experiments in production during working hours with a clear abort switch.

Key terms

SLI
A measured ratio of good events to total events, such as requests answered within 1.5 s.
SLO
A target value for an SLI over a time window, such as 99.5% over 28 days.
Error budget
The amount of failure an SLO allows; spending it slows releases.
Burn rate
How fast the error budget is being consumed relative to spending it evenly over the window.
XID error
An error code the NVIDIA driver logs for GPU faults, some caused by software and some by hardware.
Load shedding
Rejecting or rerouting excess work early so admitted requests still meet their latency target.
Hedging
Sending a duplicate request after a delay and using whichever answers first.
Circuit breaker
A switch that stops calling a failing backend for a cool-down period and routes to a fallback instead.
Blameless postmortem
An incident review that looks for system causes and fixes rather than individual fault.
Lab

Define SLOs, break the model server and keep the SLO with fallback and load shedding

Intermediate, 90 min

Goal: run a gateway in front of a primary and a fallback model, inject three failures, and measure the SLO with and without your resilience mechanisms. You only break containers you start yourself.

You need: Docker with Compose v2, Python 3.10 or newer with pip install httpx, about 6 GB of free RAM. All models run on CPU: qwen2.5:1.5b as primary and qwen2.5:0.5b as fallback.

  1. Write the SLO first, in a file you will commit:
SLO.md
Service   chat gateway
SLI       share of POST /chat requests that return 200 within 6 s
SLO       99% of requests per test run (28 days in production)
Budget    1% of requests
Degraded  responses from the fallback model count as good; tracked separately
  1. Create the gateway. It retries fast failures once with jitter, never retries into a rate limit, routes to the fallback when the primary fails or is busy, and sheds load with a fast 503 when everything is full:
gateway.py
import asyncio, os, random, time
import httpx
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
 
PRIMARY = os.getenv("PRIMARY_URL", "http://toxiproxy:8666")
FALLBACK = os.getenv("FALLBACK_URL", "http://ollama-fallback:11434")
PRIMARY_MODEL, FALLBACK_MODEL = "qwen2.5:1.5b", "qwen2.5:0.5b"
FALLBACK_ON = os.getenv("FALLBACK", "on") == "on"
MAX_PRIMARY = int(os.getenv("MAX_PRIMARY", "2"))    # in-flight cap for the primary
MAX_TOTAL = int(os.getenv("MAX_TOTAL", "6"))        # shed above this
PRIMARY_TIMEOUT, DEADLINE = 4.0, 8.0
 
state = {"inflight": 0, "rate_limited_until": 0.0}
client = httpx.AsyncClient()
app = FastAPI()
 
class RateLimited(Exception):
    pass
 
class ChatIn(BaseModel):
    prompt: str
 
async def generate(url, model, prompt, timeout):
    if url == PRIMARY and time.time() < state["rate_limited_until"]:
        raise RateLimited()
    r = await client.post(f"{url}/api/generate", timeout=timeout, json={
        "model": model, "prompt": prompt, "stream": False,
        "options": {"num_predict": 32}})
    r.raise_for_status()
    return r.json()["response"]
 
@app.post("/chat")
async def chat(body: ChatIn):
    if state["inflight"] >= MAX_TOTAL:
        return JSONResponse({"error": "overloaded"}, 503, headers={"Retry-After": "1"})
    use_primary = state["inflight"] < MAX_PRIMARY or not FALLBACK_ON
    state["inflight"] += 1
    start = time.monotonic()
    try:
        if use_primary:
            for attempt in range(2):
                try:
                    text = await generate(PRIMARY, PRIMARY_MODEL, body.prompt, PRIMARY_TIMEOUT)
                    return {"model": PRIMARY_MODEL, "degraded": False, "text": text}
                except RateLimited:
                    break                                   # never retry into a 429
                except (httpx.TransportError, httpx.HTTPStatusError):
                    fast_failure = time.monotonic() - start < 1.0
                    if attempt == 0 and fast_failure:
                        await asyncio.sleep(random.uniform(0.1, 0.3))  # backoff with jitter
                        continue
                    break
            if not FALLBACK_ON:
                return JSONResponse({"error": "primary failed"}, 502)
        remaining = max(DEADLINE - (time.monotonic() - start), 0.5)
        text = await generate(FALLBACK, FALLBACK_MODEL, body.prompt, remaining)
        return {"model": FALLBACK_MODEL, "degraded": True, "text": text}
    except Exception:
        return JSONResponse({"error": "all backends failed"}, 502)
    finally:
        state["inflight"] -= 1
 
@app.post("/chaos/ratelimit")
async def chaos_ratelimit(seconds: int = 60):
    state["rate_limited_until"] = time.time() + seconds
    return {"rate_limited_for_s": seconds}
  1. Add the load generator, which sends requests at a fixed rate and computes the SLI:
loadgen.py
import asyncio, sys, time
import httpx
 
URL = "http://localhost:8080/chat"
rate, seconds, threshold = float(sys.argv[1]), int(sys.argv[2]), 6.0
 
async def one(client, i, results):
    t = time.monotonic()
    try:
        r = await client.post(URL, json={"prompt": f"One short fact about the number {i}."}, timeout=20)
        ok, degraded = r.status_code == 200, r.status_code == 200 and r.json()["degraded"]
    except Exception:
        ok, degraded = False, False
    results.append((ok, time.monotonic() - t, degraded))
 
async def main():
    results, tasks = [], []
    async with httpx.AsyncClient() as client:
        for i in range(int(rate * seconds)):
            tasks.append(asyncio.create_task(one(client, i, results)))
            await asyncio.sleep(1 / rate)
        await asyncio.gather(*tasks)
    good = sum(1 for ok, lat, _ in results if ok and lat <= threshold)
    lats = sorted(lat for _, lat, _ in results)
    print(f"n={len(results)} SLI={good / len(results):.3f} "
          f"p95={lats[int(0.95 * (len(lats) - 1))]:.2f}s "
          f"degraded={sum(d for *_, d in results)} errors={sum(not ok for ok, *_ in results)}")
 
asyncio.run(main())
  1. Wire it together with Toxiproxy between the gateway and the primary, so you can inject latency:
compose.yaml
services:
  ollama-primary:
    image: ollama/ollama:latest
    volumes: ["models:/root/.ollama"]
    environment: { OLLAMA_KEEP_ALIVE: "1h" }
  ollama-fallback:
    image: ollama/ollama:latest
    volumes: ["models:/root/.ollama"]
    environment: { OLLAMA_KEEP_ALIVE: "1h" }
  toxiproxy:
    image: ghcr.io/shopify/toxiproxy:latest
    ports: ["8474:8474"]
  gateway:
    image: python:3.12-slim
    command: sh -c "pip install -q fastapi uvicorn httpx && uvicorn gateway:app --host 0.0.0.0 --port 8080"
    working_dir: /app
    volumes: ["./gateway.py:/app/gateway.py"]
    environment:
      FALLBACK: ${FALLBACK:-on}
    ports: ["8080:8080"]
volumes:
  models: {}
docker compose up -d
docker compose exec ollama-primary ollama pull qwen2.5:1.5b
docker compose exec ollama-primary ollama pull qwen2.5:0.5b
curl -s -X POST localhost:8474/proxies \
  -d '{"name":"primary","listen":"0.0.0.0:8666","upstream":"ollama-primary:11434"}'
docker compose exec ollama-fallback ollama run qwen2.5:0.5b "hi"   # warm the fallback
curl -s -X POST localhost:8080/chat -H 'content-type: application/json' -d '{"prompt":"hi"}'

The last command should return JSON with "model": "qwen2.5:1.5b" and "degraded": false.

  1. Measure the baseline at a rate your laptop handles comfortably. Expect an SLI of 1.000 and a p95 of a few seconds; if p95 is above 4 s, lower the rate:
python3 loadgen.py 0.5 120
  1. Run each experiment twice, first with FALLBACK=off docker compose up -d gateway, then with FALLBACK=on docker compose up -d gateway. Start loadgen.py 0.5 120 in one terminal and inject the fault about 20 seconds in from another:
# A. Kill the model server
docker compose stop ollama-primary        # restore later: docker compose start ollama-primary
 
# B. Add 6 s of latency on the primary path
curl -s -X POST localhost:8474/proxies/primary/toxics \
  -d '{"name":"slow","type":"latency","stream":"downstream","attributes":{"latency":6000}}'
# remove: curl -s -X DELETE localhost:8474/proxies/primary/toxics/slow
 
# C. Exhaust a rate limit for 60 s
curl -s -X POST 'localhost:8080/chaos/ratelimit?seconds=60'
 
# D. Overload: four times the baseline rate
python3 loadgen.py 2 60
  1. Record the results in a table in your repo. The numbers below are illustrative; yours will differ, but the pattern should match:
results.md
Experiment        Fallback off          Fallback on
A kill primary    SLI 0.20, errors 48   SLI 1.00, degraded 47
B +6 s latency    SLI 0.18              SLI 0.98, degraded 46
C rate limit      SLI 0.50              SLI 1.00, degraded 30
D overload 4x     SLI 0.35, p95 19 s    SLI 0.80, p95 4.9 s, fast 503s

Check your work: with fallback off, experiments A to C break the SLO; with fallback on, A to C hold 99% or close to it, and the degraded count shows the fallback did the work. In D, shedding keeps p95 of admitted requests under 6 s instead of letting every request slow down together.

Stretch: add a circuit breaker that skips the primary for 30 seconds after five consecutive failures, and show in experiment B that it cuts p95 from about 5 s to about 1 s. Then write a one-page blameless postmortem for experiment B as if it had happened in production.

Check yourself

An overloaded model server starts timing out. Every client retries up to three times immediately. What happens next?

Your chat product has a 99.9% availability SLO and no errors this month, but user complaints about wrong answers doubled after a provider model update. What is the root problem with your reliability setup?

Traffic can grow 25% in 5 minutes. A new model replica takes 10 minutes to become ready. What does this imply for capacity planning?

The kernel log on a GPU node shows Xid 79. What is the right first action?

Recap

  • SLOs for AI cover latency (TTFT and inter-token), availability and quality, and the error budget turns reliability debates into arithmetic.
  • Alert on burn rate with paired long and short windows, not on raw error spikes.
  • AI adds hardware faults (XID, OOM), provider limits, silent quality regressions and runaway agents to the usual failure list.
  • Use separate TTFT and idle timeouts, retry with jittered backoff inside a budget, and hedge only cheap calls.
  • A fallback ladder plus load shedding keeps admitted requests inside the SLO when capacity runs out.
  • Size GPU capacity from measured per-replica throughput, add N+1 and enough headroom to cover the minutes a replica takes to start.

Go deeper