▚ The AI Engineer's Field Manual
Module 12b · Act IV — Production & the Business

Cloud Deployment & Production Operations — AWS, CI/CD, Kubernetes, SLOs and the Rehearsed Rollback

"A deploy button is easy. The hard part is the 2 a.m. page, and knowing what you will do before it comes."

~9 hours Builds on: Module 12 (the FastAPI/Docker service), Module 07 (eval gate), Appendix 2 (SLOs) Tools: AWS ECS Fargate · Terraform · GitHub Actions · Kubernetes · Prometheus · Grafana · Langfuse Job-spec line it unlocks: "Deploy and operate containerised ML services on AWS with CI/CD, SLOs and incident response"

01 · The hookThe Container Worked. At 2:07 a.m. It Was Wrong.

This chapter is about running a model service for other people, on someone else's computers, without watching it. You will put the service from Module 12 on AWS, make it deploy itself, and decide in advance what happens when a release goes bad.

Field report · Slack message, Friday 16:40

"Great news from Monday's exec review: the container runs. Bad news: it runs on Sam's laptop and one test VM.

Lumen Telecom signed for the churn API at $40,000 a month. The contract promises 99.5% of requests succeed, counted over each 30 days. Miss it and we credit them 25%, which is $10,000, plus a very awkward call from their VP.

Priya, you are first on call from Monday. I need it on AWS, deployed by the pipeline and not by a person, with a rollback you have practised. Nobody gets to learn rollback during an incident."

— Viktor Sterling, CTO of "SaaSify"

Priya Raman is the engineer who has to answer that message. She wrote none of the model code. Her job starts where Module 12's FastAPI and Docker service ends: the container exists, the tests pass, and nothing yet keeps it alive on a Tuesday night.

Viktor has given Priya one number to protect. The contract allows 0.5% failure in a month. The rest of this chapter is what she builds, in order, so that she can protect that number while asleep.

Start with that number. A 30-day month has 43,200 minutes. Half a percent of them is 216 minutes of allowed failure. Those 216 minutes are the error budget, and every bad release, provider outage and runaway bill in this chapter is paid for out of it.

By the end Priya will have lived through three incidents in a row. A bad model version. A provider outage. A prompt that loops. The code for all three runs on your machine, in one script, with no cloud account. That script is the lab.

You already know this

Nine years of web work covers more of this than you think. The new part is that the service can be up and wrong, and that the tooling names things differently.

What you already know, in this chapter's vocabulary.
You know it asHere it is called
git push then a deploy scriptCI/CD: a pipeline that tests, builds an image, and rolls it out on every merge
A .env file with an AWS keyAn IAM role and a short-lived token (OIDC): no key to leak
nginx health checkReadiness probe: should this copy get traffic yet?
Blue-green deployCanary release: send 10% of traffic to the new version first
"The site is down" callIncident response: severity, roles, a timeline, a blameless postmortem
Uptime percentage in a contractSLO and error budget: the same promise, turned into minutes you can spend

The one genuinely new idea is what "broken" means. A model service can answer every request with a 200 and still be wrong. So this chapter measures the answers as well as the status codes.

02 · The pathFrom Laptop to Cloud: One Picture, Drawn Twice

A cloud deployment is a package (the image) travelling from your laptop to a shelf (the registry) to a running place (the runtime). Without the picture in your head, every AWS service name looks like a separate thing to learn.

Priya has one container, one contract and a Monday start date. Before she opens the AWS console she wants the whole route on one page, because an engineer who cannot draw the path cannot debug it at 2 a.m.

Here is the route in plain words. You build an image: a sealed copy of your code and its libraries. You push it to a registry: a shelf that stores images by name and tag. A runtime pulls the image and starts copies of it. Users reach those copies through a front door.

Notice what moves. Only the image travels. Your laptop is where it is made, the registry is where it rests, and the runtime is where it runs. That is why "it works on my machine" stops mattering once the image is the unit you ship.

Your laptopImageRegistryRuntimeUsersbuildpushpullserve123Only the image moves. Everything else is a place it rests or runs.
Fig. 12b.1 — The abstract route. One thing moves (the image) through four moves: build, push, pull, serve.
  1. The image (marker 1). The highlighted box in the middle. It is built once on your laptop or in CI, and it never changes after that. The same bytes run in staging and in production. That is the whole point of containers.
  2. The registry (marker 2). A shelf with labels. Each image gets a tag such as a git commit id. Marker 2 sits over the registry because "which tag is live?" is the question every rollback answers.
  3. The runtime (marker 3). The computers that start copies of the image. On AWS this chapter uses ECS Fargate; later it also uses Kubernetes. The runtime pulls from the registry, so the laptop can be switched off.

Now the same five stages again, with the real names Priya types. Compare Fig. 12b.2 with the first picture, box for box.

Laptopapp.pypytest -qImagechurn:3f9c1abDockerfileECRchurn-servicetags immutableECS Fargate2 tasks0.5 vCPU eachLoad balancerport 80checks /readyzdockerbuilddockerpushECSpullsHTTPrequest123Same five stages as Fig. 12b.1, now with the real names Priya types.
Fig. 12b.2 — The same route with real values: a git-SHA tag, an ECR repository, two Fargate tasks at 0.5 vCPU each, a load balancer checking /readyz.
  1. Image tag 3f9c1ab (marker 1). The tag is the first seven characters of the git commit. If production misbehaves you can name exactly which commit is running, and exactly which one to go back to.
  2. Immutable tags (marker 2). ECR can refuse to overwrite a tag that already exists. Then "3f9c1ab" can never silently become different bits. Without that rule, a rollback to a tag might not give you the old code.
  3. Two tasks (marker 3). Two copies behind one front door. One can fail or be replaced while the other keeps answering. Section 4 prices these two tasks at about $36 a month.
The five stages on the laptop and in the cloud, with what flows out of each.
StageOn the laptopIn the cloudWhat flows out
Testpytest -qThe same command, run by GitHub Actions on every pushA pass or a fail
Builddocker buildThe same command, in CIAn image, tagged with the git SHA
StoreLocal Docker cacheECR repositoryA pullable image name
Runuvicorn app:appECS Fargate tasks (or Kubernetes pods)Running copies, health-checked
Serve and watchcurl localhost:8000Load balancer, Prometheus, alertsAnswers, plus numbers about the answers

The rest of the chapter fills in this table from top to bottom, then adds the part laptops never needed: what happens when the new image is bad.

Image
A sealed, versioned copy of the code plus everything it needs to run. Built once, never edited.
Registry (ECR)
The shelf that stores images by name and tag. A rollback is "run an older tag from here".
Runtime
Whatever starts copies of the image and restarts them when they die: ECS Fargate, Kubernetes, Lambda.
Why only the image moves
So the thing you tested is exactly the thing that runs. Config such as MODEL_VERSION is injected at start, not baked in.

03 · Build the serviceA Service Priya Can Operate: Metrics, Probes, Logs, a Version Label

The model code from Module 12 answers requests. An operable service also reports how it is doing, says when it is ready, writes searchable logs, and states which version it is. Without those, an incident is guesswork.

Priya has the picture of the route. Before anything goes to AWS she needs the service to tell her what it is doing, because on Monday night the only witness she will have is what the service reports about itself.

We start from the smallest possible service and add one operational feature per chunk. Five features, in this order:

Each feature is under 30 lines. The version from Module 12's churn service already had Pydantic validation and a lifespan hook, so that is not re-explained here. What is new is everything Prometheus and the platform need from it.

You have not been taught any of the lines below yet, and you are not expected to know them. Guess first from the names, then open the answers. Each line is built up from nothing in the five chunks that follow.

Sharpen your pencil

These ten lines come from the finished app.py. Three are filled in for you. In the blank rows, write in plain English what you think each line does.

MODEL_VERSION = os.environ.get("MODEL_VERSION", "dev")Reads the version label from an environment variable, falling back to "dev". The deploy pipeline sets it; nobody types it.
REQUESTS = Counter("http_requests_total", ..., ["route", "status", "version"])
LATENCY = Histogram("http_request_duration_seconds", ..., buckets=(0.005, ..., 2.5))
@app.middleware("http")Wraps every request in the function below it, before and after the endpoint runs.
response = await call_next(request)
name = route.path if route else "unmatched"
LATENCY.labels(name).observe(time.perf_counter() - start)
raise HTTPException(status_code=503, detail="model not loaded")Answers "not ready" with a 503 until the model is loaded, so the load balancer holds traffic back.
log.info(json.dumps(fields, sort_keys=True))
SCORE.labels(MODEL_VERSION).observe(prob)
Check your answers
MODEL_VERSION = os.environ.get("MODEL_VERSION", "dev")Reads the version label from an environment variable, falling back to "dev". The deploy pipeline sets it; nobody types it.
REQUESTS = Counter("http_requests_total", ..., ["route", "status", "version"])Creates a counter, a number that only goes up, with three labels. Each distinct label combination is its own running total.
LATENCY = Histogram("http_request_duration_seconds", ..., buckets=(0.005, ..., 2.5))Creates a histogram: counts of how many requests fell into each time bucket, from 5 ms up to 2.5 s.
@app.middleware("http")Wraps every request in the function below it, before and after the endpoint runs.
response = await call_next(request)Runs the real endpoint and waits for its response. Everything before this line happens before the endpoint, everything after happens after.
name = route.path if route else "unmatched"Uses the route template such as /predict as the label. Unknown URLs all become "unmatched", so a scanner cannot invent endless label values.
LATENCY.labels(name).observe(time.perf_counter() - start)Records how long this request took into the histogram for this route.
raise HTTPException(status_code=503, detail="model not loaded")Answers "not ready" with a 503 until the model is loaded, so the load balancer holds traffic back.
log.info(json.dumps(fields, sort_keys=True))Writes one JSON object on one line. Log search tools can then filter on route or status.
SCORE.labels(MODEL_VERSION).observe(prob)Records the probability the model returned, per version. This is how a bad model shows up while every status code is still 200.

If you guessed the counter and the histogram from their names, you already understand most of Prometheus. The only new idea is the label: a label is what lets one metric name hold many separate running totals.

Build it in chunks

We build app.py in five chunks. Each chunk is also saved as its own file (app_c1.py to app_c4.py, then app.py), and each runs on its own.

  1. Chunk 1 — one endpoint that returns a churn probability

    Start with only the business function. Everything operational is added around it later, so each addition is easy to see.

    Step-by-step: what chunk 1 does, in plain English
    1. Import FastAPI and Pydantic. Pydantic checks the shape of incoming JSON for us.
    2. Create the app object. FastAPI routes web requests to functions through it.
    3. ChurnRequest declares two fields with limits. A tenure of -1 is rejected before our code sees it.
    4. predict computes a score: tickets push it up, tenure pulls it down. 1 / (1 + exp(-logit)) squeezes any number into 0 to 1.
    5. The function returns a dictionary, and FastAPI turns it into JSON.
    app_c1.py — chunk 1runs offline
    # pip install "fastapi>=0.115,<1" "pydantic>=2.8,<3"
    # Chunk 1: one endpoint that turns a customer into a churn probability.
    import math
    
    from fastapi import FastAPI
    from pydantic import BaseModel, Field
    
    app = FastAPI(title="churn-service")
    
    
    class ChurnRequest(BaseModel):
        tenure_months: int = Field(ge=0, le=120)
        support_tickets: int = Field(ge=0, le=50)
    
    
    @app.post("/predict")
    def predict(req: ChurnRequest) -> dict:
        # A tiny logistic model: more tickets raise risk, longer tenure lowers it.
        logit = 0.4 * req.support_tickets - 0.05 * req.tenure_months
        return {"churn_probability": round(1 / (1 + math.exp(-logit)), 4)}

    @app.post("/predict") — a decorator that says "this function answers POST requests at /predict".

    Run python rung_check.py app_c1. It drives the service in-process, no server needed. You should see a 200 and a probability, and 404 for the pages not built yet.

    terminalactual output
    $ python rung_check.py app_c1
    POST /predict -> 200 {'churn_probability': 0.9089}
    GET /healthz -> 404 (not built yet)
    GET /readyz -> 404 (not built yet)
    GET /metrics -> 404 (not built yet)
    headers: none
  2. Chunk 2 — measure every request and publish the numbers at /metrics

    A service nobody can measure is a service nobody can defend. This chunk adds the two measuring tools and a page for Prometheus to read.

    Step-by-step: what chunk 2 does, in plain English
    1. Create a Counter for requests (labelled by route and status) and a Histogram for how long they take.
    2. Create a second histogram, SCORE, for the probabilities the model returns. This is the model-specific signal.
    3. The middleware starts a timer, runs the real endpoint with call_next, then stops the timer.
    4. It labels the measurement with the route template, or "unmatched" for unknown URLs, so label values stay few.
    5. /metrics returns every metric as plain text, in the format Prometheus reads.
    6. predict now also calls SCORE.observe(prob).
    app_c2.py — chunk 2: the lines it addsruns offline
    # pip install "fastapi>=0.115,<1" "pydantic>=2.8,<3" "prometheus-client>=0.21,<1"
    # Chunk 2: chunk 1 plus a /metrics page that Prometheus can read.
    # ... (unchanged lines omitted) ...
    import time
    # ... (unchanged lines omitted) ...
    from fastapi import FastAPI, Request, Response
    from prometheus_client import CONTENT_TYPE_LATEST, Counter, Histogram, generate_latest
    # ... (unchanged lines omitted) ...
    
    REQUESTS = Counter("http_requests_total", "Requests served", ["route", "status"])
    LATENCY = Histogram("http_request_duration_seconds", "Request time", ["route"],
                        buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5))
    SCORE = Histogram("prediction_score", "Churn probability returned",
                      buckets=(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9))
    
    
    @app.middleware("http")
    async def measure(request: Request, call_next):
        start = time.perf_counter()
        response = await call_next(request)
        route = request.scope.get("route")
        # Use the route template, never the raw URL: raw URLs make endless label values.
        name = route.path if route else "unmatched"
        LATENCY.labels(name).observe(time.perf_counter() - start)
        REQUESTS.labels(name, str(response.status_code)).inc()
        return response
    
    
    @app.get("/metrics")
    def metrics() -> Response:
        return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)
    # ... (unchanged lines omitted) ...
        prob = round(1 / (1 + math.exp(-logit)), 4)
        SCORE.observe(prob)  # the model-specific signal: what is the model saying?
        return {"churn_probability": prob}

    prometheus_client.Counter and Histogram — in-process meters; @app.middleware("http") — code that wraps every request.

    Run python rung_check.py app_c2. The /metrics lines show one /predict request counted. The "unmatched 404" count of 2 is our own check calling two pages not built yet.

    terminalactual output
    $ python rung_check.py app_c2
    POST /predict -> 200 {'churn_probability': 0.9089}
    GET /healthz -> 404 (not built yet)
    GET /readyz -> 404 (not built yet)
    GET /metrics -> 200
        http_requests_total{route="/predict",status="200"} 1.0
        http_requests_total{route="unmatched",status="404"} 2.0
        prediction_score_count 1.0
    headers: none
  3. Chunk 3 — load the model at startup and add two health probes

    A platform decides whether to send traffic or restart a pod by asking the service. These two endpoints are the answers.

    Step-by-step: what chunk 3 does, in plain English
    1. Keep the model in a module-level dictionary that starts empty. Empty means "not ready".
    2. A lifespan function fills it once at startup and clears it at shutdown. Never load per request.
    3. /healthz always answers 200 while the process runs. This is the liveness probe.
    4. /readyz answers 503 until the weights exist, then 200. This is the readiness probe.
    5. predict now reads its weights from the loaded model instead of constants.
    app_c3.py — chunk 3: the lines it addsruns offline
    # Chunk 3: chunk 2 plus a model that loads at startup and two health probes.
    # ... (unchanged lines omitted) ...
    from contextlib import asynccontextmanager
    # ... (unchanged lines omitted) ...
    from fastapi import FastAPI, HTTPException, Request, Response
    # ... (unchanged lines omitted) ...
    MODEL: dict = {}  # filled once at startup; empty means "not ready"
    
    
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        MODEL["weights"] = {"tickets": 0.4, "tenure": -0.05}  # real life: download + load
        yield
        MODEL.clear()
    
    
    app = FastAPI(title="churn-service", lifespan=lifespan)
    # ... (unchanged lines omitted) ...
    
    
    @app.get("/healthz")
    def healthz() -> dict:
        return {"status": "alive"}  # liveness: "the process is not stuck"
    
    
    @app.get("/readyz")
    def readyz() -> dict:
        if "weights" not in MODEL:  # readiness: "send me traffic yet?"
            raise HTTPException(status_code=503, detail="model not loaded")
        return {"status": "ready"}
    # ... (unchanged lines omitted) ...
        w = MODEL["weights"]
        logit = w["tickets"] * req.support_tickets + w["tenure"] * req.tenure_months
    # ... (unchanged lines omitted) ...
        SCORE.observe(prob)

    lifespan with @asynccontextmanager — code that runs before the first request and after the last. HTTPException(503) — return an error status.

    Run python rung_check.py app_c3. Both probes now answer 200, and each probe call shows up in the request counter.

    terminalactual output
    $ python rung_check.py app_c3
    POST /predict -> 200 {'churn_probability': 0.9089}
    GET /healthz -> 200 {'status': 'alive'}
    GET /readyz -> 200 {'status': 'ready'}
    GET /metrics -> 200
        http_requests_total{route="/predict",status="200"} 1.0
        http_requests_total{route="/healthz",status="200"} 1.0
        http_requests_total{route="/readyz",status="200"} 1.0
        prediction_score_count 1.0
    headers: none
  4. Chunk 4 — one JSON log line per request

    Metrics say how many failed. Logs say which one and why. Writing the log as JSON means a search tool can filter on route and status.

    Step-by-step: what chunk 4 does, in plain English
    1. Send logging to standard output. Containers collect standard output and ship it to CloudWatch.
    2. log_json turns keyword fields into one JSON line.
    3. The middleware makes a short random request_id, returns it in a header, and logs it. Support can quote that id and you can find that exact line.
    4. It logs route, status and duration in milliseconds.
    app_c4.py — chunk 4: the lines it addsruns offline
    # Chunk 4: chunk 3 plus one JSON log line per request.
    import json
    import logging
    # ... (unchanged lines omitted) ...
    import sys
    # ... (unchanged lines omitted) ...
    import uuid
    # ... (unchanged lines omitted) ...
    
    logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
    log = logging.getLogger("churn")
    
    
    def log_json(**fields) -> None:
        # One JSON object per line: a log search can filter on route or status.
        log.info(json.dumps(fields, sort_keys=True))
    
    # ... (unchanged lines omitted) ...
        seconds = time.perf_counter() - start
        LATENCY.labels(name).observe(seconds)
    # ... (unchanged lines omitted) ...
        response.headers["x-request-id"] = uuid.uuid4().hex[:12]  # lets support quote one request
        log_json(event="request", request_id=response.headers["x-request-id"], route=name,
                 status=response.status_code, duration_ms=round(seconds * 1000, 2))

    logging and json.dumps — standard library only. uuid.uuid4().hex[:12] — a short unique id.

    Run python rung_check.py app_c4. A JSON line appears before each result line. The ids differ on every run.

    terminalactual output
    $ python rung_check.py app_c4
    {"duration_ms": 1.78, "event": "request", "request_id": "a0dfeb845f8d", "route": "/predict", "status": 200}
    POST /predict -> 200 {'churn_probability': 0.9089}
    {"duration_ms": 0.59, "event": "request", "request_id": "e79e78940adb", "route": "/healthz", "status": 200}
    GET /healthz -> 200 {'status': 'alive'}
    {"duration_ms": 0.51, "event": "request", "request_id": "93a99706b81a", "route": "/readyz", "status": 200}
    GET /readyz -> 200 {'status': 'ready'}
    {"duration_ms": 2.45, "event": "request", "request_id": "1bdcce7bb077", "route": "/metrics", "status": 200}
    GET /metrics -> 200
        http_requests_total{route="/predict",status="200"} 1.0
        http_requests_total{route="/healthz",status="200"} 1.0
    ...
  5. Chunk 5 — a version label on every metric, log line and response

    When a release goes bad, the first question is "which version is this?". Labelling everything with the version answers it in one click.

    Step-by-step: what chunk 5 does, in plain English
    1. Read MODEL_VERSION from the environment. The deploy pipeline sets it to the git SHA.
    2. Add version as a third label on the request counter, and as a label on the score histogram.
    3. Return it in an x-model-version header and add it to every log line.
    4. Now two versions running side by side produce two separate lines on the same dashboard.
    app.py — chunk 5: the lines it addsruns offline
    # Chunk 5 (the whole service): chunk 4 plus a model-version label on everything.
    # ... (unchanged lines omitted) ...
    import os
    # ... (unchanged lines omitted) ...
    # Set by the deploy pipeline (a git SHA or registry version), never typed by hand.
    MODEL_VERSION = os.environ.get("MODEL_VERSION", "dev")
    # ... (unchanged lines omitted) ...
    REQUESTS = Counter("http_requests_total", "Requests served", ["route", "status", "version"])
    # ... (unchanged lines omitted) ...
    SCORE = Histogram("prediction_score", "Churn probability returned", ["version"],
    # ... (unchanged lines omitted) ...
        REQUESTS.labels(name, str(response.status_code), MODEL_VERSION).inc()
        response.headers["x-model-version"] = MODEL_VERSION
    # ... (unchanged lines omitted) ...
                 status=response.status_code, version=MODEL_VERSION, duration_ms=round(seconds * 1000, 2))
    # ... (unchanged lines omitted) ...
        SCORE.labels(MODEL_VERSION).observe(prob)

    os.environ.get("MODEL_VERSION", "dev") — read configuration from the environment, with a default.

    Run MODEL_VERSION=3f9c1ab python rung_check.py app. Every metric line now ends in version="3f9c1ab".

    terminalactual output
    $ MODEL_VERSION=3f9c1ab python rung_check.py app
    {"duration_ms": 1.87, "event": "request", "request_id": "3f799aa6bab9", "route": "/predict", "status": 200, "version": "3f9c1ab"}
    POST /predict -> 200 {'churn_probability': 0.9089}
    {"duration_ms": 0.5, "event": "request", "request_id": "496b329ed1f2", "route": "/healthz", "status": 200, "version": "3f9c1ab"}
    GET /healthz -> 200 {'status': 'alive'}
    {"duration_ms": 0.4, "event": "request", "request_id": "9349aa28071b", "route": "/readyz", "status": 200, "version": "3f9c1ab"}
    GET /readyz -> 200 {'status': 'ready'}
    {"duration_ms": 1.34, "event": "request", "request_id": "48cb879e8138", "route": "/metrics", "status": 200, "version": "3f9c1ab"}
    GET /metrics -> 200
        http_requests_total{route="/predict",status="200",version="3f9c1ab"} 1.0
        http_requests_total{route="/healthz",status="200",version="3f9c1ab"} 1.0
        http_requests_total{route="/readyz",status="200",version="3f9c1ab"} 1.0
    ...

The whole program

Chunk 1 is the request model and predict. Chunk 2 adds the three meters, the middleware and /metrics. Chunk 3 adds lifespan and the two probes. Chunk 4 adds log_json and the request id. Chunk 5 adds MODEL_VERSION and the version label. The file below is app.py, exactly as saved in the code folder.

app.pyruns offline
# pip install "fastapi>=0.115,<1" "pydantic>=2.8,<3" "prometheus-client>=0.21,<1"
# Chunk 5 (the whole service): chunk 4 plus a model-version label on everything.
import json
import logging
import math
import os
import sys
import time
import uuid
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException, Request, Response
from prometheus_client import CONTENT_TYPE_LATEST, Counter, Histogram, generate_latest
from pydantic import BaseModel, Field

logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(message)s")
log = logging.getLogger("churn")


def log_json(**fields) -> None:
    # One JSON object per line: a log search can filter on route or status.
    log.info(json.dumps(fields, sort_keys=True))


# Set by the deploy pipeline (a git SHA or registry version), never typed by hand.
MODEL_VERSION = os.environ.get("MODEL_VERSION", "dev")
MODEL: dict = {}  # filled once at startup; empty means "not ready"


@asynccontextmanager
async def lifespan(app: FastAPI):
    MODEL["weights"] = {"tickets": 0.4, "tenure": -0.05}  # real life: download + load
    yield
    MODEL.clear()


app = FastAPI(title="churn-service", lifespan=lifespan)

REQUESTS = Counter("http_requests_total", "Requests served", ["route", "status", "version"])
LATENCY = Histogram("http_request_duration_seconds", "Request time", ["route"],
                    buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5))
SCORE = Histogram("prediction_score", "Churn probability returned", ["version"],
                  buckets=(0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9))


@app.middleware("http")
async def measure(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    route = request.scope.get("route")
    name = route.path if route else "unmatched"
    seconds = time.perf_counter() - start
    LATENCY.labels(name).observe(seconds)
    REQUESTS.labels(name, str(response.status_code), MODEL_VERSION).inc()
    response.headers["x-model-version"] = MODEL_VERSION
    response.headers["x-request-id"] = uuid.uuid4().hex[:12]  # lets support quote one request
    log_json(event="request", request_id=response.headers["x-request-id"], route=name,
             status=response.status_code, version=MODEL_VERSION, duration_ms=round(seconds * 1000, 2))
    return response


@app.get("/healthz")
def healthz() -> dict:
    return {"status": "alive"}  # liveness: "the process is not stuck"


@app.get("/readyz")
def readyz() -> dict:
    if "weights" not in MODEL:  # readiness: "send me traffic yet?"
        raise HTTPException(status_code=503, detail="model not loaded")
    return {"status": "ready"}


@app.get("/metrics")
def metrics() -> Response:
    return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)


class ChurnRequest(BaseModel):
    tenure_months: int = Field(ge=0, le=120)
    support_tickets: int = Field(ge=0, le=50)


@app.post("/predict")
def predict(req: ChurnRequest) -> dict:
    w = MODEL["weights"]
    logit = w["tickets"] * req.support_tickets + w["tenure"] * req.tenure_months
    prob = round(1 / (1 + math.exp(-logit)), 4)
    SCORE.labels(MODEL_VERSION).observe(prob)
    return {"churn_probability": prob}

Read the output. The last chunk's output has three things to check. The first line, POST /predict -> 200, shows the endpoint still works after four additions. The metric lines each end in a version label, so two versions running together would be two separate lines. The headers show the version and a request id, which is the handle for finding one request in the logs.

That tiny model gave 0.9089 for a customer with 2 months of tenure and 6 support tickets. Keep this number. In Section 7 the mean of these scores, per version, is how a bad model shows itself while every status code stays 200.

Following one request through the new code

The code is done, but Priya is not yet sure she can predict what the service will write down. She traces one request by hand.

POST /predictarrivesmiddlewarestarts a timerhandlerscore 0.9089middlewarestops: 2.4 mscounter +1 /predict 200histogram 2.4 ms: le=0.005log line {route, ms, ver}GET /metricsPrometheus reads every 15 s123One request leaves three kinds of evidence behind.A counter, a histogram, and a log line.
Fig. 12b.3 — One POST to /predict leaves three kinds of evidence: a counter increment, a histogram observation, and a log line. Prometheus reads the first two from /metrics.
  1. The timer stops (marker 1). The middleware wraps the endpoint. The 2.4 ms is the time between its two clock reads, measured around the handler that returned 0.9089.
  2. Three outputs (marker 2). The counter adds one to the series route=/predict, status=200. The histogram files 2.4 ms under the "less than or equal 0.005 s" bucket. The log line carries the same facts as text, with a request id.
  3. /metrics (marker 3). Nothing is pushed anywhere. Prometheus calls this page every 15 seconds and stores what it finds. That pull model is why a crashed service shows up as a gap in the graph.

Read the picture left to right. The request arrives, the middleware starts a timer, the handler scores the customer, and the middleware stops the timer at marker 1 in Fig. 12b.3. The three outputs at marker 2 are the evidence Priya will use for the rest of the chapter.

Anatomy of a Prometheus histogram — the one declaration to know by heart
LATENCY = Histogram(1"http_request_duration_seconds",2
                    "Request time", ["route"],3
                    buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5))4
  1. The type. A histogram stores counts per bucket, not each time. That keeps memory flat however many requests arrive. People mistakenly expect it to hold the raw values.
  2. The name. Name it with the unit, seconds, as Prometheus convention says. Mixing milliseconds in one service and seconds in another is how a dashboard shows nonsense.
  3. The labels. ["route"] means one set of buckets per route. Add a label only when you will want to split a graph by it, because each combination is a separate stored series.
  4. The buckets. Edges in seconds, chosen around your SLO. If the promise is "under 300 ms", you want an edge at 0.25 and one at 0.5. Default edges are tuned for web pages, not models.

Count it. Time it. Label it.

Ask ready before sending traffic.

Log one line per request, as JSON.

Stamp the version on everything.

Count and time: the counter and histogram at marker 2 of Fig. 12b.3. Ready: /readyz answering 503 until the model is loaded. Line: the log output of chunk 4. Version: the label added in chunk 5.

"A commercial APM tool already measures all of this automatically. Why am I hand-writing counters?"

— a nine-year engineer who has used Datadog

For request counts and latency, an agent does measure them for you, and you should use one if your company pays for it. The hand-written parts are the model-specific ones: the score histogram and the version label. No agent can guess that "mean score moved from 0.30 to 0.62" is your emergency.

The honest downside: hand-written metrics are code you must maintain, and a careless label (a customer id) can make a monitoring bill explode. The next questions explain that risk.

Questions you might be asking now

Four questions that come up the first time you read the code above. Every answer reuses the same ten request times, shown once here, in milliseconds and sorted: 80, 85, 90, 95, 100, 105, 110, 120, 400, 900. The numbers come from metrics_by_hand.py.

How can Prometheus know the p95 if it never stores each request time?

It estimates it. The histogram stores only how many requests fell in each time bucket. A function then finds the bucket holding the target rank and assumes the values inside it are spread evenly. The estimate is good when buckets are narrow around your SLO and rough otherwise.

Percentile, in words: the p95 is the time that 95 out of 100 requests beat. With our ten requests, the work goes like this:

  1. Count per bucket, cumulative. At most 100 ms: 5 requests. At most 250 ms: 8. At most 500 ms: 9. At most 1000 ms: 10. Cumulative means each bucket includes the ones before it, which is how Prometheus stores them.
  2. Find the target rank. p95 of 10 requests is rank 0.95 × 10 = 9.5.
  3. Find the bucket that holds rank 9.5. Nine requests are at most 500 ms and ten at most 1000 ms, so rank 9.5 is inside the 500 to 1000 ms bucket.
  4. Interpolate inside it. Start at 500. Add (1000 − 500) × (9.5 − 9) ÷ (10 − 9) = 250. The estimate is 750 ms.
0 - 100 ms5 requests100 - 250 ms3 requests250 - 500 ms1 request500 - 1000 ms1 request12rank 5 of 10: the top of this bucketp50 = 100 msrank 9.5 of 10: halfway up this bucketestimate p95 = 750 msbut the true p95 was 900 ms
Fig. 12b.4 — Ten request times as four histogram buckets. The p50 estimate is exact here (100 ms); the p95 estimate is 750 ms against a true 900 ms.
  1. p50 (marker 1). Rank 5 out of 10 is the fifth fastest request. The first bucket holds exactly five, so the fifth sits at its top edge, 100 ms.
  2. p95 (marker 2). Rank 9.5 falls between the ninth and tenth request, inside the 500 to 1000 ms bucket. The estimate assumes the one request in that bucket sits halfway up. It actually took 900 ms. A bucket gives a range, never the exact value.
Exact against estimated percentiles for the same ten requests.
PercentileExact (sorted list)From the four buckets
p50100 ms100.0 ms
p95900 ms750.0 ms
p99900 ms950.0 ms

The honest limit: the estimate for p95 is 150 ms too low here, because one slow request sits near the top of a wide bucket. The fix is more buckets near the number in your SLO, not more requests.

metrics_by_hand.py outputactual output
$ python metrics_by_hand.py
exact:   p50 = 100 ms   p95 = 900 ms   p99 = 900 ms
buckets:  {'le=100': 5, 'le=250': 8, 'le=500': 9, 'le=1000': 10} total = 10
estimate p50 = 100.0 ms
estimate p95 = 750.0 ms
estimate p99 = 950.0 ms
counter rate = 15.0 requests per second

A histogram trades exactness for a fixed memory cost; put bucket edges where your SLO is.

The request counter only ever goes up. How is a number that only grows useful?

You never read the counter itself. You read how fast it grew between two readings, which is what the query function rate() gives you. A growing total survives a missed reading; a "requests per second" number would not.

  1. First scrape. At 12:00:00 the counter reads 12,000.
  2. Second scrape. 60 seconds later it reads 12,900.
  3. Subtract and divide. (12,900 − 12,000) ÷ 60 = 15 requests per second. The script prints exactly that.
  4. Restart. If the process restarts, the counter returns to 0. rate() sees a drop, treats it as a reset and carries on instead of reporting a negative rate.
12,00012,90012:00:0012:01:00run: 60 srise: +900900 ÷ 60 s = 15 requests per second123
Fig. 12b.18 — A counter read twice. The two readings, 60 seconds apart, differ by 900, so the rate is 15 requests per second.
  1. First reading (marker 1). The counter said 12,000 at 12:00:00. The number alone means nothing; it is only the total since the process started.
  2. Second reading (marker 2). One minute later it said 12,900. The distance between the two dots on the vertical axis is the work done in between.
  3. The slope (marker 3). Rise 900 over run 60 seconds is the rate. If a reading is missed, the line simply draws across a longer gap and the slope is still right.

Why not export the rate directly? If one reading is lost, a stored rate is gone forever. A stored total is not: the next reading includes the missing interval, and the rate over a longer window is still right.

Store totals, compute rates when you ask.

What is the difference between /healthz and /readyz? Can one endpoint do both?

They answer different questions, so they trigger different actions. Liveness asks "is the process stuck?" and failing it restarts the pod. Readiness asks "should this copy get traffic?" and failing it only removes the pod from rotation. One endpoint cannot ask both, because restarting a pod whose only problem is a slow dependency makes things worse.

Liveness against readiness, on the same pod, in the same ten seconds.
MomentProcess state/healthz (liveness)/readyz (readiness)What the platform does
0 sPython just started, loading the model200503Keeps the pod, sends it no traffic
8 sModel loaded200200Starts sending traffic
LaterEvent loop deadlockedno answerno answerThree failed liveness checks: kills and restarts the pod
LaterModel provider is down, process fine200503 if you chose soStops traffic, does not restart (a restart would not help)
/healthz/readyztraffic200 the whole time503200noneflowingmodel loaded: 8 snext check passes: 10 s05101520seconds since the pod started (readiness checked every 5 s)12
Fig. 12b.17 — The first 20 seconds of one pod. The model finishes loading at 8 s, but readiness is only checked every 5 s, so traffic starts at 10 s.
  1. Model loaded (marker 1). Until second 8 the readiness endpoint answers 503, so the platform sends nothing. The liveness endpoint answers 200 all along, so the pod is not killed for being slow.
  2. Traffic starts (marker 2). The check at second 10 is the first to see 200. Two seconds are lost to the check interval. A shorter interval starts traffic sooner but asks the service more often.

Read the last row. If /healthz also checked the model provider, a provider outage would make the platform restart every pod at once. They would come back, fail again, and take down the service by restarting it.

Liveness restarts, readiness routes; never let a dependency's outage fail liveness.

Why does the middleware use the route template instead of the real URL?

Because every different label value creates a new stored series, and a real URL can contain a customer id. The template /predict is one value. /customers/CUST-1234 is a new value for every customer.

  1. Count series with templates. 4 real routes plus "unmatched" = 5 values. Times 3 statuses (200, 422, 503) times 2 versions during a rollout = 30 request-counter series.
  2. Count series with raw URLs. 1,000,000 customers × 3 statuses × 2 versions = 6,000,000 series from one metric.
  3. Why the second is a problem. Prometheus keeps each series in memory. Millions of them make queries slow and the monitoring bill large.
Label = route template5 routes × 3 statuses × 2 versions= 30 seriesLabel = raw URL with customer idnot to scale1,000,000 customers × 3 statuses × 2 versions= 6,000,000 series12
Fig. 12b.19 — Thirty stored series with a route template as the label, against six million with a raw URL that contains the customer id.
  1. Template label (marker 1). Five route values times three statuses times two versions. Thirty small running totals, and the count never grows with traffic.
  2. Raw-URL label (marker 2). Every customer id is a new label value, so every customer gets their own set of series. The red block is not drawn to scale: it would be 200,000 times bigger than the green one.

The rule: a label's possible values must be a short list you could write down. Customer ids, request ids and raw URLs belong in logs, not labels. That is why the request id appears in chunk 4's log line and never in chunk 2's metrics.

Labels are for categories you could list; ids go in logs.

Packaging it: the Dockerfile

Step-by-step: what the Dockerfile does, in plain English
  1. Start from the slim Python 3.12 image, a base that already has Python and little else.
  2. Set PYTHONUNBUFFERED=1 so log lines appear immediately instead of waiting in a buffer.
  3. Copy requirements.txt first and install. Docker caches this layer, so code changes do not reinstall libraries.
  4. Copy app.py, create a non-root user and switch to it. A container that gets hacked then runs without root.
  5. Start uvicorn in exec form (a JSON list). That makes it process 1, so it receives the stop signal and can finish in-flight requests.
Dockerfileruns offline
# Small, non-root image. Build: docker build -t churn-service:dev .
FROM python:3.12-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
RUN useradd -m svc
USER svc
EXPOSE 8000
# Exec form so SIGTERM reaches uvicorn and it can drain in-flight requests.
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

The CI tests from the same folder are four tiny checks: a good request, a bad request, the probes, and "not ready before startup". CI will run exactly this command before it builds anything.

terminalactual output
$ pytest -q
4 passed, 1 warning in 0.31s

Not run here: docker build of this Dockerfile. This machine shares its memory with other work, so the image was not built. The Dockerfile follows the same pattern as Module 12's, which was.

Counter
A number that only goes up. Ask for its rate(). Used for requests and errors.
Histogram
Counts per time bucket. Gives estimated p50, p95, p99. Put edges at your SLO.
Label
A category that splits one metric. Keep values few; never an id.
Liveness (/healthz)
"Is the process stuck?" Failing it restarts the pod.
Readiness (/readyz)
"Should I get traffic?" Failing it only pauses traffic.
Version label
The git SHA from MODEL_VERSION, on metrics, logs and a response header.

04 · AWS for an ML serviceAWS for an ML Service: Roles, a Registry, a Place to Run It, and a Bill

AWS is a rented data centre with a permission system on every door. To run one container you need three decisions: who may do what (IAM roles), where the image lives (ECR), and what runs it (the compute choice). Get the first wrong and you leak keys; get the last wrong and you pay for a cluster you did not need.

Priya has an operable service and the picture of the route. It is Monday morning, she has an empty AWS account, and a company rule: no human types a long-lived key anywhere. She starts with permissions, because everything else will ask about them.

IAM roles, in plain words

IAM (Identity and Access Management) is AWS's list of who may do what. A user with an access key is a permanent key card: whoever holds it can open the door until someone remembers to cancel it. A role is a visitor badge. Something proves who it is at the front desk, gets a badge that expires in about an hour, and the badge opens only the doors listed on it.

Priya needs three roles, because three different things act inside AWS. Look at Fig. 12b.5 before reading on.

GitHub Actions jobtoken says: main branchassumeschurn-github-deployIAM rolemaypush to ECR, update serviceECS (the platform)starts your taskassumeschurn-executionIAM rolemaypull image, write logsYour Python coderunning in the taskassumeschurn-taskIAM rolemaynothing: no AWS calls123
Fig. 12b.5 — Three identities, three roles. The GitHub job and ECS borrow short-lived roles; the application code borrows a role with no permissions.
  1. The deploy role (marker 1). GitHub proves who it is with a signed token that names the repository and branch. AWS lets only that token borrow churn-github-deploy. There is no access key to leak, because nothing long-lived exists.
  2. The execution role (marker 2). ECS itself uses this one to pull the image and write logs. Your code never sees it. People often merge it with the task role, and then a bug in the app gets permission to pull any image.
  3. The task role (marker 3). What your code runs as. Our service calls no AWS API, so this role is empty on purpose. When the service later reads a model from S3, you add exactly that one permission here.

The rule behind the picture is least privilege: each identity gets exactly the permissions its job needs and nothing else. If the pipeline is compromised, the attacker can push an image and update one service. They cannot read other buckets or create servers. The next section shows the pipeline borrowing the deploy role with no secret stored anywhere.

The compute choice: five ways to run one container

Roles settled, Priya now has to choose where the container runs. Her colleague Dev says "Kubernetes, obviously". She wants to make the decision on cost and effort, not on fashion. The facts below were checked in October 2026 and they have moved in the past year.

Where to run a containerised model service on AWS, as of October 2026.
OptionWhat it isStatus and cost noteChoose whenAvoid when
ECS on FargateAWS starts your containers; you never see a serverMature. Billed per vCPU-hour and GB-hour: about $0.04048 and $0.004445 (us-east-1, Linux x86)One to ten services, small team, CPU inferenceYou need GPUs (Fargate has none) or already run Kubernetes
ECS Express ModeOne API call creates a Fargate service, a load balancer with TLS and autoscalingNew. No extra charge; you pay for the parts it creates. AWS names it the replacement path for App RunnerYou want the Fargate setup without writing 300 lines of TerraformYou need custom networking or fine control of every part
App RunnerPush code or an image, get a URLClosed to new customers since April 30, 2026. Existing customers continue; AWS plans no new featuresYou already run it and it worksStarting anything new: use Express Mode instead
Lambda container imageA function whose code is a container image, up to 10 GBBilled per request and duration; scales to zeroBursty or rare traffic, short requests, no always-on billCold starts hurt your p99, or the model is large and slow to load
EKS (Kubernetes)Managed Kubernetes control plane; you add nodes$0.10 per cluster-hour, about $73 a month, before any nodeMany services, GPUs, a team that already knows Kubernetes, portability across cloudsOne small service: the control plane alone costs more than it
SageMaker AI endpointsManaged hosting built for models, with GPU instances and a model registryBilled per instance-hour while the endpoint is upLarge models on GPUs where you want AWS to manage hosting and scalingA small CPU model: you pay instance prices for something Fargate runs for less

Priya picks ECS on Fargate for the churn service: it is a small CPU model, one team runs it, and nobody wants to manage nodes. She writes it by hand in Terraform once, so she can see every part. For her next service she would try Express Mode first.

One honest caution. These services change quickly: App Runner's status changed this spring. The table is a snapshot; check the AWS announcement pages before you promise a design to a client.

"Everyone says Kubernetes is the industry standard. Why would a serious team pick Fargate?"

— Dev, who has run Kubernetes for four years

Because a standard you do not need is a bill. Fargate has fewer parts to break, nothing to patch, and costs nothing when the team is small. Kubernetes is the right answer once you run many services, need GPUs, or want the same setup on three clouds. It is also what many job descriptions ask for, which is why Section 6 teaches it.

The honest downside of Fargate: no GPUs, less control over scheduling, and moving off it later means rewriting the deployment. That is why the pipeline in the next section keeps the image as the portable unit.

Terraform: the whole thing as text

Terraform is a tool where you write what you want AWS to contain, in text files, and it creates or changes things until reality matches. Click-built infrastructure cannot be reviewed, repeated or rolled back. Text in git can. As of October 2026 Terraform is at 1.17; OpenTofu is the open-source fork, and the code in this chapter works with either.

ECR repositoryexecution roletask rolelog grouptask definitionthe recipeECS service2 tasksALB + listenertarget groupautoscaling2 to 6 tasks123
Fig. 12b.16 — How the Terraform resources point at each other. Terraform reads these references and creates things in dependency order.
  1. The task definition (marker 1). It points at the image repository, both roles and the log group, so Terraform builds those four first. Change the image tag and only this box and the service need an update.
  2. The service (marker 2). The last thing created: it needs the recipe, and a target group to register tasks in. That target group needs the load balancer listener first.
  3. Autoscaling (marker 3). It points at the service, not the other way round. Deleting the service deletes the scaling rule with it, and Terraform knows because of this arrow.

Build it in chunks

We build the infrastructure in five chunks, one concern each. HCL is declarative, so chunks run to 50 to 70 lines; every chunk still validates on its own. Not run here: terraform apply, because it needs an AWS account and creates billable resources. Only terraform validate ran.

  1. Chunk 1 — provider, the default network, and the image registry

    Terraform describes the end state; it works out the steps. We start with the two things everything else points at: a place for images and a network to put things in.

    Step-by-step: what tf1 does, in plain English
    1. terraform block: pin Terraform and the AWS provider to a major version, so a new release cannot change behaviour silently.
    2. Two variables: the region, and the image tag the pipeline will set.
    3. The data blocks read existing things (the default network and its subnets); resource blocks create things.
    4. aws_ecr_repository creates the registry. IMMUTABLE stops a tag from being overwritten; scan_on_push scans for known vulnerabilities.
    tf1_base.tfvalidated, not applied
    # Terraform for the churn service on ECS Fargate behind an Application Load Balancer.
    # Validate (no AWS account needed):  terraform init -backend=false && terraform validate
    # Rung 1 of 5: provider, default network, image registry.
    # NOT applied in this course: apply needs an AWS account and costs money (see cost_by_hand.py).
    terraform {
      required_version = ">= 1.9"
      required_providers {
        aws = {
          source  = "hashicorp/aws"
          version = "~> 6.0"
        }
      }
    }
    
    variable "region" {
      type    = string
      default = "us-east-1"
    }
    
    variable "image_tag" {
      type        = string
      description = "Tag of the image in ECR, set by the pipeline to the git SHA"
      default     = "dev"
    }
    
    provider "aws" {
      region = var.region
    }
    
    # --- network: use the default VPC to keep the example short -----------------
    data "aws_vpc" "default" {
      default = true
    }
    
    data "aws_subnets" "public" {
      filter {
        name   = "vpc-id"
        values = [data.aws_vpc.default.id]
      }
    }
    
    # --- registry ---------------------------------------------------------------
    resource "aws_ecr_repository" "churn" {
      name                 = "churn-service"
      image_tag_mutability = "IMMUTABLE" # a tag, once pushed, can never point at different bits
      image_scanning_configuration {
        scan_on_push = true
      }
    }

    resource "aws_ecr_repository" "churn" — "create a thing of this type, call it churn in this file". data — look up something that already exists.

    Run terraform init -backend=false then terraform validate. Validate checks the syntax and the references without an AWS account.

    terminalactual output
    $ terraform init -backend=false && terraform validate   # in a folder holding: tf1_base.tf
    Success! The configuration is valid.
  2. Chunk 2 — two IAM roles, logs, the cluster and the task definition

    The registry exists. Now describe who may do what, and what one running copy of the service looks like.

    Step-by-step: what tf2 does, in plain English
    1. A policy document says "ECS tasks may assume this role". Both roles reuse it.
    2. The execution role gets AWS's ready-made policy for pulling images and writing logs. The task role gets nothing.
    3. A log group keeps 14 days of logs; logs are billed by size, so retention is a cost setting.
    4. The task definition is the recipe: 512 CPU units (half a vCPU), 1024 MB, which image, which port, where logs go.
    5. MODEL_VERSION is set to the image tag, so the metrics label from chunk 5 of the app matches the deployed image.
    tf2_iam_task.tfvalidated, not applied
    # Rung 2 of 5: the two IAM roles, logs, cluster and task definition.
    # --- IAM: two roles with two different jobs ---------------------------------
    data "aws_iam_policy_document" "ecs_tasks_trust" {
      statement {
        actions = ["sts:AssumeRole"]
        principals {
          type        = "Service"
          identifiers = ["ecs-tasks.amazonaws.com"]
        }
      }
    }
    
    # The execution role is used by ECS itself: pull the image, write logs.
    resource "aws_iam_role" "execution" {
      name               = "churn-execution"
      assume_role_policy = data.aws_iam_policy_document.ecs_tasks_trust.json
    }
    
    resource "aws_iam_role_policy_attachment" "execution" {
      role       = aws_iam_role.execution.name
      policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
    }
    
    # The task role is what YOUR code runs as. Empty on purpose: the service needs no AWS APIs.
    resource "aws_iam_role" "task" {
      name               = "churn-task"
      assume_role_policy = data.aws_iam_policy_document.ecs_tasks_trust.json
    }
    
    # --- logs, cluster, task definition -----------------------------------------
    resource "aws_cloudwatch_log_group" "churn" {
      name              = "/ecs/churn-service"
      retention_in_days = 14 # logs are billed per GB stored: do not keep them forever
    }
    
    resource "aws_ecs_cluster" "main" {
      name = "ml-services"
    }
    
    resource "aws_ecs_task_definition" "churn" {
      family                   = "churn-service"
      requires_compatibilities = ["FARGATE"]
      network_mode             = "awsvpc"
      cpu                      = 512  # 0.5 vCPU
      memory                   = 1024 # 1 GB
      execution_role_arn       = aws_iam_role.execution.arn
      task_role_arn            = aws_iam_role.task.arn
    
      container_definitions = jsonencode([{
        name         = "churn"
        image        = "${aws_ecr_repository.churn.repository_url}:${var.image_tag}"
        essential    = true
        portMappings = [{ containerPort = 8000, protocol = "tcp" }]
        environment  = [{ name = "MODEL_VERSION", value = var.image_tag }]
        logConfiguration = {
          logDriver = "awslogs"
          options = {
            awslogs-group         = aws_cloudwatch_log_group.churn.name
            awslogs-region        = var.region
            awslogs-stream-prefix = "churn"
          }
        }
      }])
    }

    jsonencode(...) — builds JSON from HCL values. ${...} — splices a value into a string.

    Validate again with chunks 1 and 2 together. It checks that chunk 2's references to chunk 1 resolve.

    terminalactual output
    $ terraform init -backend=false && terraform validate   # in a folder holding: tf1_base.tf tf2_iam_task.tf
    Success! The configuration is valid.
  3. Chunk 3 — security groups and the load balancer

    Users need a front door. The load balancer is also where the readiness probe from the app becomes a real decision: it only sends traffic to tasks whose /readyz answers 200.

    Step-by-step: what tf3 does, in plain English
    1. The ALB security group lets the world in on port 80. The service security group lets in only the ALB on port 8000.
    2. The target group lists the tasks by IP and checks /readyz every 15 seconds. Two passes make a task healthy; three failures make it unhealthy.
    3. The listener forwards port 80 to the target group.
    4. An output prints the public URL after an apply.
    tf3_alb.tfvalidated, not applied
    # Rung 3 of 5: security groups and the Application Load Balancer.
    # --- load balancer ----------------------------------------------------------
    resource "aws_security_group" "alb" {
      name   = "churn-alb"
      vpc_id = data.aws_vpc.default.id
      ingress {
        from_port   = 80
        to_port     = 80
        protocol    = "tcp"
        cidr_blocks = ["0.0.0.0/0"]
      }
      egress {
        from_port   = 0
        to_port     = 0
        protocol    = "-1"
        cidr_blocks = ["0.0.0.0/0"]
      }
    }
    
    resource "aws_security_group" "service" {
      name   = "churn-service"
      vpc_id = data.aws_vpc.default.id
      ingress { # only the load balancer may reach the containers
        from_port       = 8000
        to_port         = 8000
        protocol        = "tcp"
        security_groups = [aws_security_group.alb.id]
      }
      egress {
        from_port   = 0
        to_port     = 0
        protocol    = "-1"
        cidr_blocks = ["0.0.0.0/0"]
      }
    }
    
    resource "aws_lb" "main" {
      name               = "churn-alb"
      load_balancer_type = "application"
      security_groups    = [aws_security_group.alb.id]
      subnets            = data.aws_subnets.public.ids
    }
    
    resource "aws_lb_target_group" "churn" {
      name        = "churn-tg"
      port        = 8000
      protocol    = "HTTP"
      target_type = "ip" # Fargate tasks register by IP address
      vpc_id      = data.aws_vpc.default.id
      health_check {
        path                = "/readyz" # the readiness probe from app.py decides who gets traffic
        healthy_threshold   = 2
        unhealthy_threshold = 3
        interval            = 15
      }
    }
    
    resource "aws_lb_listener" "http" {
      load_balancer_arn = aws_lb.main.arn
      port              = 80
      protocol          = "HTTP"
      default_action {
        type             = "forward"
        target_group_arn = aws_lb_target_group.churn.arn
      }
    }
    
    
    output "service_url" {
      value = "http://${aws_lb.main.dns_name}"
    }

    security_groups = [aws_security_group.alb.id] — "only traffic that comes from that group". A reference replaces a hand-copied id.

    Validate with chunks 1 to 3.

    terminalactual output
    $ terraform init -backend=false && terraform validate   # in a folder holding: tf1_base.tf tf2_iam_task.tf tf3_alb.tf
    Success! The configuration is valid.
  4. Chunk 4 — the service itself, with automatic rollback and autoscaling

    Everything so far is parts. This chunk starts two copies and wires them to the front door.

    Step-by-step: what tf4 does, in plain English
    1. aws_ecs_service keeps desired_count = 2 tasks alive and registers them with the target group.
    2. deployment_circuit_breaker with rollback = true: if new tasks keep failing their health check during a deploy, ECS reverts to the last working task definition on its own.
    3. Public subnets plus a public IP avoid the NAT gateway bill (the trade-off is shown in Fig. 12b.6).
    4. The autoscaling target allows between 2 and 6 tasks; the policy adds tasks when average CPU passes 60%.
    tf4_service.tfvalidated, not applied
    # Rung 4 of 5: the ECS service (with automatic rollback) and autoscaling.
    # --- the service: keeps 2 tasks alive and rolls back a bad deploy -----------
    resource "aws_ecs_service" "churn" {
      name            = "churn-service"
      cluster         = aws_ecs_cluster.main.id
      task_definition = aws_ecs_task_definition.churn.arn
      desired_count   = 2
      launch_type     = "FARGATE"
    
      deployment_circuit_breaker {
        enable   = true
        rollback = true # if new tasks keep failing their health check, ECS reverts by itself
      }
    
      network_configuration {
        subnets          = data.aws_subnets.public.ids
        security_groups  = [aws_security_group.service.id]
        assign_public_ip = true # public subnets: avoids the NAT gateway bill
      }
    
      load_balancer {
        target_group_arn = aws_lb_target_group.churn.arn
        container_name   = "churn"
        container_port   = 8000
      }
    
      depends_on = [aws_lb_listener.http]
    }
    
    resource "aws_appautoscaling_target" "churn" {
      service_namespace  = "ecs"
      resource_id        = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.churn.name}"
      scalable_dimension = "ecs:service:DesiredCount"
      min_capacity       = 2
      max_capacity       = 6
    }
    
    resource "aws_appautoscaling_policy" "cpu" {
      name               = "churn-cpu-60"
      policy_type        = "TargetTrackingScaling"
      service_namespace  = aws_appautoscaling_target.churn.service_namespace
      resource_id        = aws_appautoscaling_target.churn.resource_id
      scalable_dimension = aws_appautoscaling_target.churn.scalable_dimension
      target_tracking_scaling_policy_configuration {
        target_value = 60 # add tasks when average CPU passes 60%
        predefined_metric_specification {
          predefined_metric_type = "ECSServiceAverageCPUUtilization"
        }
      }
    }

    depends_on — says "create the listener first" when Terraform cannot see the order from references alone.

    Validate with chunks 1 to 4.

    terminalactual output
    $ terraform init -backend=false && terraform validate   # in a folder holding: tf1_base.tf tf2_iam_task.tf tf3_alb.tf tf4_service.tf
    Success! The configuration is valid.
  5. Chunk 5 — let GitHub deploy without a stored key

    The pipeline in the next section must call AWS. Instead of an access key in a secret, AWS trusts GitHub's signed identity token, for one repository and one branch.

    Step-by-step: what tf5 does, in plain English
    1. Register GitHub as an identity provider in this AWS account.
    2. The trust policy lets GitHub assume the role only if the token's audience is sts.amazonaws.com and its subject is this repo's main branch.
    3. The role may push to ECR, register and update the service, and pass only the two task roles.
    4. An output prints the role ARN, which goes into a GitHub repository variable.
    tf5_github_oidc.tfvalidated, not applied
    # Rung 5 of 5: let GitHub Actions deploy with a short-lived token, not a stored key.
    variable "github_repo" {
      type        = string
      description = "owner/name of the repository allowed to deploy"
      default     = "saasify/churn-service"
    }
    
    # --- GitHub Actions deploys with a short-lived token, not a stored key ------
    resource "aws_iam_openid_connect_provider" "github" {
      url            = "https://token.actions.githubusercontent.com"
      client_id_list = ["sts.amazonaws.com"]
    }
    
    data "aws_iam_policy_document" "github_trust" {
      statement {
        actions = ["sts:AssumeRoleWithWebIdentity"]
        principals {
          type        = "Federated"
          identifiers = [aws_iam_openid_connect_provider.github.arn]
        }
        condition {
          test     = "StringEquals"
          variable = "token.actions.githubusercontent.com:aud"
          values   = ["sts.amazonaws.com"]
        }
        condition { # only this repository, only its main branch
          test     = "StringEquals"
          variable = "token.actions.githubusercontent.com:sub"
          values   = ["repo:${var.github_repo}:ref:refs/heads/main"]
        }
      }
    }
    
    resource "aws_iam_role" "deploy" {
      name               = "churn-github-deploy"
      assume_role_policy = data.aws_iam_policy_document.github_trust.json
    }
    
    data "aws_iam_policy_document" "deploy" {
      statement {
        actions   = ["ecr:GetAuthorizationToken"]
        resources = ["*"]
      }
      statement {
        actions = ["ecr:BatchCheckLayerAvailability", "ecr:InitiateLayerUpload", "ecr:UploadLayerPart",
        "ecr:CompleteLayerUpload", "ecr:PutImage", "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"]
        resources = [aws_ecr_repository.churn.arn]
      }
      statement {
        actions   = ["ecs:RegisterTaskDefinition", "ecs:DescribeTaskDefinition", "ecs:DescribeServices", "ecs:UpdateService"]
        resources = ["*"]
      }
      statement {
        actions   = ["iam:PassRole"]
        resources = [aws_iam_role.execution.arn, aws_iam_role.task.arn]
      }
    }
    
    resource "aws_iam_role_policy" "deploy" {
      role   = aws_iam_role.deploy.id
      policy = data.aws_iam_policy_document.deploy.json
    }
    
    output "deploy_role_arn" {
      value = aws_iam_role.deploy.arn
    }

    sts:AssumeRoleWithWebIdentity — the AWS call that swaps a signed token for temporary credentials.

    Validate with all five chunks, which is the whole configuration.

    terminalactual output
    $ terraform init -backend=false && terraform validate   # in a folder holding: tf1_base.tf tf2_iam_task.tf tf3_alb.tf tf4_service.tf tf5_github_oidc.tf
    Success! The configuration is valid.

The whole program

Chunk 1 is lines 1–49 (provider, network, ECR). Chunk 2 follows, then the load balancer, then the service, and the GitHub role last. The file below is terraform/main.tf, the five chunk files joined in order.

terraform/main.tfvalidated, not applied
# Terraform for the churn service on ECS Fargate behind an Application Load Balancer.
# Validate (no AWS account needed):  terraform init -backend=false && terraform validate
# Rung 1 of 5: provider, default network, image registry.
# NOT applied in this course: apply needs an AWS account and costs money (see cost_by_hand.py).
terraform {
  required_version = ">= 1.9"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
  }
}

variable "region" {
  type    = string
  default = "us-east-1"
}

variable "image_tag" {
  type        = string
  description = "Tag of the image in ECR, set by the pipeline to the git SHA"
  default     = "dev"
}

provider "aws" {
  region = var.region
}

# --- network: use the default VPC to keep the example short -----------------
data "aws_vpc" "default" {
  default = true
}

data "aws_subnets" "public" {
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.default.id]
  }
}

# --- registry ---------------------------------------------------------------
resource "aws_ecr_repository" "churn" {
  name                 = "churn-service"
  image_tag_mutability = "IMMUTABLE" # a tag, once pushed, can never point at different bits
  image_scanning_configuration {
    scan_on_push = true
  }
}

# Rung 2 of 5: the two IAM roles, logs, cluster and task definition.
# --- IAM: two roles with two different jobs ---------------------------------
data "aws_iam_policy_document" "ecs_tasks_trust" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }
  }
}

# The execution role is used by ECS itself: pull the image, write logs.
resource "aws_iam_role" "execution" {
  name               = "churn-execution"
  assume_role_policy = data.aws_iam_policy_document.ecs_tasks_trust.json
}

resource "aws_iam_role_policy_attachment" "execution" {
  role       = aws_iam_role.execution.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}

# The task role is what YOUR code runs as. Empty on purpose: the service needs no AWS APIs.
resource "aws_iam_role" "task" {
  name               = "churn-task"
  assume_role_policy = data.aws_iam_policy_document.ecs_tasks_trust.json
}

# --- logs, cluster, task definition -----------------------------------------
resource "aws_cloudwatch_log_group" "churn" {
  name              = "/ecs/churn-service"
  retention_in_days = 14 # logs are billed per GB stored: do not keep them forever
}

resource "aws_ecs_cluster" "main" {
  name = "ml-services"
}

resource "aws_ecs_task_definition" "churn" {
  family                   = "churn-service"
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = 512  # 0.5 vCPU
  memory                   = 1024 # 1 GB
  execution_role_arn       = aws_iam_role.execution.arn
  task_role_arn            = aws_iam_role.task.arn

  container_definitions = jsonencode([{
    name         = "churn"
    image        = "${aws_ecr_repository.churn.repository_url}:${var.image_tag}"
    essential    = true
    portMappings = [{ containerPort = 8000, protocol = "tcp" }]
    environment  = [{ name = "MODEL_VERSION", value = var.image_tag }]
    logConfiguration = {
      logDriver = "awslogs"
      options = {
        awslogs-group         = aws_cloudwatch_log_group.churn.name
        awslogs-region        = var.region
        awslogs-stream-prefix = "churn"
      }
    }
  }])
}

# Rung 3 of 5: security groups and the Application Load Balancer.
# --- load balancer ----------------------------------------------------------
resource "aws_security_group" "alb" {
  name   = "churn-alb"
  vpc_id = data.aws_vpc.default.id
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_security_group" "service" {
  name   = "churn-service"
  vpc_id = data.aws_vpc.default.id
  ingress { # only the load balancer may reach the containers
    from_port       = 8000
    to_port         = 8000
    protocol        = "tcp"
    security_groups = [aws_security_group.alb.id]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_lb" "main" {
  name               = "churn-alb"
  load_balancer_type = "application"
  security_groups    = [aws_security_group.alb.id]
  subnets            = data.aws_subnets.public.ids
}

resource "aws_lb_target_group" "churn" {
  name        = "churn-tg"
  port        = 8000
  protocol    = "HTTP"
  target_type = "ip" # Fargate tasks register by IP address
  vpc_id      = data.aws_vpc.default.id
  health_check {
    path                = "/readyz" # the readiness probe from app.py decides who gets traffic
    healthy_threshold   = 2
    unhealthy_threshold = 3
    interval            = 15
  }
}

resource "aws_lb_listener" "http" {
  load_balancer_arn = aws_lb.main.arn
  port              = 80
  protocol          = "HTTP"
  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.churn.arn
  }
}


output "service_url" {
  value = "http://${aws_lb.main.dns_name}"
}

# Rung 4 of 5: the ECS service (with automatic rollback) and autoscaling.
# --- the service: keeps 2 tasks alive and rolls back a bad deploy -----------
resource "aws_ecs_service" "churn" {
  name            = "churn-service"
  cluster         = aws_ecs_cluster.main.id
  task_definition = aws_ecs_task_definition.churn.arn
  desired_count   = 2
  launch_type     = "FARGATE"

  deployment_circuit_breaker {
    enable   = true
    rollback = true # if new tasks keep failing their health check, ECS reverts by itself
  }

  network_configuration {
    subnets          = data.aws_subnets.public.ids
    security_groups  = [aws_security_group.service.id]
    assign_public_ip = true # public subnets: avoids the NAT gateway bill
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.churn.arn
    container_name   = "churn"
    container_port   = 8000
  }

  depends_on = [aws_lb_listener.http]
}

resource "aws_appautoscaling_target" "churn" {
  service_namespace  = "ecs"
  resource_id        = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.churn.name}"
  scalable_dimension = "ecs:service:DesiredCount"
  min_capacity       = 2
  max_capacity       = 6
}

resource "aws_appautoscaling_policy" "cpu" {
  name               = "churn-cpu-60"
  policy_type        = "TargetTrackingScaling"
  service_namespace  = aws_appautoscaling_target.churn.service_namespace
  resource_id        = aws_appautoscaling_target.churn.resource_id
  scalable_dimension = aws_appautoscaling_target.churn.scalable_dimension
  target_tracking_scaling_policy_configuration {
    target_value = 60 # add tasks when average CPU passes 60%
    predefined_metric_specification {
      predefined_metric_type = "ECSServiceAverageCPUUtilization"
    }
  }
}

# Rung 5 of 5: let GitHub Actions deploy with a short-lived token, not a stored key.
variable "github_repo" {
  type        = string
  description = "owner/name of the repository allowed to deploy"
  default     = "saasify/churn-service"
}

# --- GitHub Actions deploys with a short-lived token, not a stored key ------
resource "aws_iam_openid_connect_provider" "github" {
  url            = "https://token.actions.githubusercontent.com"
  client_id_list = ["sts.amazonaws.com"]
}

data "aws_iam_policy_document" "github_trust" {
  statement {
    actions = ["sts:AssumeRoleWithWebIdentity"]
    principals {
      type        = "Federated"
      identifiers = [aws_iam_openid_connect_provider.github.arn]
    }
    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:aud"
      values   = ["sts.amazonaws.com"]
    }
    condition { # only this repository, only its main branch
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:sub"
      values   = ["repo:${var.github_repo}:ref:refs/heads/main"]
    }
  }
}

resource "aws_iam_role" "deploy" {
  name               = "churn-github-deploy"
  assume_role_policy = data.aws_iam_policy_document.github_trust.json
}

data "aws_iam_policy_document" "deploy" {
  statement {
    actions   = ["ecr:GetAuthorizationToken"]
    resources = ["*"]
  }
  statement {
    actions = ["ecr:BatchCheckLayerAvailability", "ecr:InitiateLayerUpload", "ecr:UploadLayerPart",
    "ecr:CompleteLayerUpload", "ecr:PutImage", "ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer"]
    resources = [aws_ecr_repository.churn.arn]
  }
  statement {
    actions   = ["ecs:RegisterTaskDefinition", "ecs:DescribeTaskDefinition", "ecs:DescribeServices", "ecs:UpdateService"]
    resources = ["*"]
  }
  statement {
    actions   = ["iam:PassRole"]
    resources = [aws_iam_role.execution.arn, aws_iam_role.task.arn]
  }
}

resource "aws_iam_role_policy" "deploy" {
  role   = aws_iam_role.deploy.id
  policy = data.aws_iam_policy_document.deploy.json
}

output "deploy_role_arn" {
  value = aws_iam_role.deploy.arn
}

Read the output. Each chunk printed "Success! The configuration is valid." That means the syntax is right and every reference points at something that exists. It does not mean AWS would accept it: names might clash, limits might apply, permissions might be missing. Only a plan against a real account says that, which is why the apply was not run here.

What it costs per month, worked by hand

The Terraform is valid. Viktor's next message, predictably, is "what will this cost?". Priya answers with arithmetic, not a guess.

Sharpen your pencil

Work out the monthly Fargate bill for two tasks of 0.5 vCPU and 1 GB each, running all month (730 hours). Prices: $0.04048 per vCPU-hour, $0.004445 per GB-hour. One row is done. Fill in the rest before opening the answers.

vCPU cost of one task per hour: 0.5 × $0.04048$0.02024
Memory cost of one task per hour: 1 × $0.004445
One task, one hour: add the two
Two tasks, one hour
Two tasks, one month: × 730 hours
Load balancer, fixed charge: $0.0225 × 730
Check your answers
vCPU cost of one task per hour: 0.5 × $0.04048$0.02024
Memory cost of one task per hour: 1 × $0.004445$0.004445. One GB times the GB price.
One task, one hour: add the two$0.024685
Two tasks, one hour$0.04937
Two tasks, one month: × 730 hours$36.04. Compute is billed for every hour tasks run, busy or idle.
Load balancer, fixed charge: $0.0225 × 730$16.43. It is charged whether or not anyone calls the service.

If you got $36.04, you can now price any Fargate service: tasks × (vCPU × price + GB × price) × 730.

Step-by-step: what cost_by_hand.py does, in plain English
  1. Set the hours in a month (730) and the two Fargate prices.
  2. Compute Fargate: tasks × (vCPU × vCPU price + GB × GB price) × hours.
  3. Compute the load balancer: a fixed hourly charge, plus an allowance for capacity units, assumed to average 1.
  4. Add the small items: image storage (2 GB × $0.10) and logs (5 GB ingested × $0.50).
  5. Print a total for public subnets, then the extra a NAT gateway adds if the tasks sit in private subnets.
  6. Print the EKS control plane alone for comparison.
cost_by_hand.pyruns offline
# The monthly bill of a small ECS Fargate service, line by line. Runs offline.
# Prices: us-east-1, Linux x86, on-demand, as of October 2026 (check aws.amazon.com/pricing before you budget).
HOURS = 730                      # hours in an average month
VCPU_HR, GB_HR = 0.04048, 0.004445
tasks, vcpu, mem_gb = 2, 0.5, 1.0

fargate = tasks * (vcpu * VCPU_HR + mem_gb * GB_HR) * HOURS
alb_fixed = 0.0225 * HOURS       # the load balancer exists whether or not anyone calls it
alb_lcu = 0.008 * HOURS * 1.0    # assume 1 load-balancer capacity unit on average
nat = 0.045 * HOURS              # one NAT gateway, only if tasks sit in private subnets
nat_gb = 0.045 * 20              # 20 GB per month of outbound traffic through it
ecr = 0.10 * 2                   # 2 GB of images stored
logs = 0.50 * 5                  # 5 GB of logs ingested

lines = [("Fargate compute (2 tasks x 0.5 vCPU, 1 GB)", fargate), ("Load balancer, fixed hours", alb_fixed),
         ("Load balancer, capacity units", alb_lcu), ("ECR image storage", ecr), ("CloudWatch logs", logs)]
total = sum(v for _, v in lines)
for name, value in lines:
    print(f"{name:45} ${value:7.2f}")
print(f"{'Total, tasks in public subnets':45} ${total:7.2f}")
print(f"{'NAT gateway, fixed hours + 20 GB':45} ${nat + nat_gb:7.2f}")
print(f"{'Total, tasks in private subnets with NAT':45} ${total + nat + nat_gb:7.2f}")
eks = 0.10 * HOURS
print(f"{'EKS control plane alone (no nodes yet)':45} ${eks:7.2f}")
cost_by_hand.py outputactual output
$ python cost_by_hand.py
Fargate compute (2 tasks x 0.5 vCPU, 1 GB)    $  36.04
Load balancer, fixed hours                    $  16.43
Load balancer, capacity units                 $   5.84
ECR image storage                             $   0.20
CloudWatch logs                               $   2.50
Total, tasks in public subnets                $  61.01
NAT gateway, fixed hours + 20 GB              $  33.75
Total, tasks in private subnets with NAT      $  94.76
EKS control plane alone (no nodes yet)        $  73.00

Read the output. The whole service costs about $61 a month with tasks in public subnets, of which the Fargate compute is $36. Putting tasks in private subnets adds a NAT gateway and the bill becomes $94.76. These numbers exclude data transfer, which grows with traffic, and ignore Savings Plans, which can lower the Fargate share. Fig. 12b.6 draws the three bills side by side.

Tasks in public subnetsFargate $36.04ALB $22.27$61.01Tasks in private subnets, one NAT gatewayFargate $36.04ALB $22.27NAT $33.75$94.76EKS control plane alone, no nodes yetcontrol plane $73.00$73.00123
Fig. 12b.6 — Three monthly bills at 730 hours a month, us-east-1 on-demand prices as of October 2026. Two Fargate tasks cost $36.04; a NAT gateway adds $33.75; an EKS control plane alone is $73.
  1. Fargate (marker 1). Two tasks of half a vCPU and one GB each. This highlighted block is the compute you think you are paying for, and it is under 60% of the first bar.
  2. NAT gateway (marker 2). Tasks in private subnets need a NAT gateway to reach the internet, and the gateway costs $0.045 an hour whether or not any traffic flows. For a small service it can cost as much as the compute.
  3. EKS control plane (marker 3). $0.10 an hour is $73 a month before a single node runs. That is more than this whole service on Fargate. Kubernetes earns it back only when you run many services.

Compare this to the hook of Module 12: an $80K model bill dwarfs the $61 of infrastructure. Compute is rarely the expensive part of an LLM service; tokens are. Section 10's third incident is exactly that.

Role
A permission set something borrows for about an hour. Prefer roles to access keys, always.
Execution role
Used by ECS to pull the image and write logs.
Task role
What your code runs as. Keep it empty until the code needs one specific API.
ECR
The image registry. Turn on immutable tags and scan on push.
Default compute
Fargate for a small team and CPU models; EKS for many services or GPUs; Lambda for rare traffic; App Runner is closed to new customers.
Monthly Fargate cost
tasks × (vCPU × $0.04048 + GB × $0.004445) × 730.
Hidden costs
Load balancer (about $16 fixed), NAT gateway ($33 fixed), log storage, data transfer.

05 · CI/CDCI/CD: Every Merge Tests, Builds and Deploys Itself

CI/CD is a robot that runs your checklist on every merge: test the code, build the image, push it, deploy it, and confirm it came up. Without it, deploys depend on one person remembering the steps, and that person is on holiday the day it matters.

The infrastructure is valid text and the roles exist. Viktor's rule was "deployed by the pipeline and not by a person". Priya now writes the robot. She knows the hard part is not the commands, which she can type in her sleep, but giving the robot access to AWS without leaving a key lying around.

CI (continuous integration) means every change is built and tested automatically. CD (continuous delivery or deployment) means a change that passes is released automatically. Fig. 12b.7 shows the five stages Priya wants.

1 testpytest -q2 builddocker build3 pushECR :3f9c1ab4 deploynew task definition5 waittasks healthy?red: stop, no imagered: job fails, ECS rolls back123main branch only: steps 2 to 5. Pull requests stop after step 1.
Fig. 12b.7 — The pipeline in five stages. Pull requests run only the test. A merge to main runs all five, and each stage can stop the line.
  1. Test first (marker 1). The cheapest check runs before the expensive ones. A failing test means no image is built and nothing reaches the registry.
  2. Deploy with the new task definition (marker 2). The job copies the live task definition, swaps in the new image tag, and registers it as a new revision. The old revision stays, which is what makes rollback possible.
  3. Wait for stability (marker 3). Without this step the job turns green the moment the request is sent, even if the new tasks crash. With it, the job stays open until ECS reports the new tasks healthy, and goes red if they never are.

No stored keys: how the robot gets into AWS

The old way was an AWS access key pasted into a GitHub secret. It never expires, it is copied into logs by accident, and nobody remembers to rotate it. OIDC (OpenID Connect) replaces it. GitHub issues each job a signed identity token. AWS checks the signature and hands back keys that last about an hour. Nothing long-lived exists to steal.

GitHub jobGitHub tokenAWS STSECR and ECSrequest a tokensigned token: repo + branchshow token, ask for the deploy roletemporary keys, about 1 hourpush image, update service123
Fig. 12b.8 — OIDC in five arrows. The job never holds a stored AWS key: it shows GitHub's signed token and gets temporary keys back.
  1. Request and receive (marker 1). The job asks GitHub for a token. It carries the claim sub: which repository and branch the job runs for. GitHub signs it, so it cannot be forged.
  2. Show it to AWS (marker 2). AWS checks the signature, then checks the claim against the trust policy from Section 4: only repo:saasify/churn-service:ref:refs/heads/main may borrow the deploy role. A fork or another branch is refused here.
  3. Temporary keys (marker 3). AWS returns keys that expire in about an hour. If someone steals them from a log, they are already worthless the next morning.

Follow the five arrows in Fig. 12b.8. The decisive step is marker 2, where AWS compares the token's sub claim to the trust policy written in Terraform chunk 5. A pull request from a fork has a different claim and is refused.

You do not need to have used GitHub Actions to follow the next three chunks. Each is a short YAML file. YAML is just indented lists and key-value pairs; the step-by-step list above each block explains every line.

Build it in chunks

We build the workflow in three chunks: test, then build and push, then deploy. Not run here: the workflow on GitHub, because it needs a repository and an AWS account. The YAML was parsed and its test step run locally.

  1. Chunk 1 — run the tests on every push and every pull request

    A pipeline that only tests is already useful: nobody can merge a broken change without seeing red. Everything else builds on this job.

    Step-by-step: what chunk 1 does, in plain English
    1. Name the workflow and say when it runs: on every push to main and on every pull request.
    2. Define one job, test, on a fresh Ubuntu machine that GitHub provides.
    3. Check out the repository, install Python 3.12, install the requirements plus the test tools.
    4. Run pytest -q. A non-zero exit fails the job, which fails the check.
    .github/workflows/deploy.yml — chunk 1validated, not applied
    # Chunk 1: run the tests on every push and pull request.
    name: churn-service
    on:
      push:
        branches: [main]
      pull_request:
    
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v7
          - uses: actions/setup-python@v7
            with:
              python-version: "3.12"
          - run: pip install -r requirements.txt pytest httpx
          - run: pytest -q

    on: — what triggers a workflow. uses: actions/checkout@v7 — run a ready-made step published by someone else.

    Parse it and run its test step locally: python check_workflow.py ci_c1.yml, then pytest -q. GitHub itself did not run this file here.

    terminalactual output
    $ python check_workflow.py ci_c1.yml; pytest -q
    ci_c1.yml: parses; triggers=['pull_request', 'push']; jobs=['test']
    4 passed, 1 warning in 0.30s
  2. Chunk 2 — on main, build the image and push it to ECR with no stored key

    A passing test on main should produce a deployable thing. This chunk builds the image, tags it with the commit id, and pushes it using the OIDC role from Section 4.

    Step-by-step: what chunk 2 does, in plain English
    1. Add permissions: id-token: write. Without it, the job cannot ask GitHub for the signed token.
    2. The build job needs: test and runs only on the main branch.
    3. configure-aws-credentials swaps the token for temporary keys, using the role ARN saved as a repository variable (not a secret: an ARN is not sensitive).
    4. Log in to ECR, work out the image name (registry + repository + commit SHA), and write it to the job output.
    5. build-push-action builds from the Dockerfile and pushes with that tag.
    ci_c2.yml — chunk 2: the lines it addsvalidated, not applied
    # Chunk 2: chunk 1 plus build the image and push it to ECR, on main only.
    # ... (unchanged lines omitted) ...
    
    permissions:
      id-token: write   # lets the job ask GitHub for a signed identity token (OIDC)
      contents: read
    
    env:
      AWS_REGION: us-east-1
      ECR_REPO: churn-service
    # ... (unchanged lines omitted) ...
    
      build:
        needs: test                       # no image is built unless the tests passed
        if: github.ref == 'refs/heads/main'
        runs-on: ubuntu-latest
        outputs:
          image: ${{ steps.meta.outputs.image }}
        steps:
          - uses: actions/checkout@v7
          - uses: aws-actions/configure-aws-credentials@v6
            with:
              role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}   # the role from main.tf; no access key anywhere
              aws-region: ${{ env.AWS_REGION }}
          - id: ecr
            uses: aws-actions/amazon-ecr-login@v2
          - id: meta
            run: echo "image=${{ steps.ecr.outputs.registry }}/${{ env.ECR_REPO }}:${{ github.sha }}" >> "$GITHUB_OUTPUT"
          - uses: docker/build-push-action@v7
            with:
              context: .
              push: true
              tags: ${{ steps.meta.outputs.image }}

    needs: — run after another job passes. ${{ github.sha }} — the commit id, used as the image tag.

    Run python check_workflow.py ci_c2.yml. It checks that both jobs exist, that the OIDC permission is present, and that no AWS secret key appears in the file.

    terminalactual output
    $ python check_workflow.py ci_c2.yml
    ci_c2.yml: parses; triggers=['pull_request', 'push']; jobs=['test', 'build']
      OIDC permission present, no stored AWS secret key in the file
  3. Chunk 3 — deploy the new image and wait until it is healthy

    The image sits in ECR but nothing runs it. The deploy job points the service at the new image and refuses to finish until the service is stable.

    Step-by-step: what chunk 3 does, in plain English
    1. The deploy job needs build and uses the production environment, where you can add a required human approval.
    2. Fetch the live task definition from ECS as JSON.
    3. render-task-definition swaps the container's image for the one built in chunk 2 and writes a new task definition.
    4. deploy-task-definition registers it and updates the service. wait-for-service-stability: true holds the job open until the new tasks pass their health checks.
    5. If they never do, the job fails, and the service's own circuit breaker (Section 4, chunk 4) is already reverting.
    deploy.yml — chunk 3: the lines it addsvalidated, not applied
    
      deploy:
        needs: build
        runs-on: ubuntu-latest
        environment: production           # an optional approval gate lives on this environment
        steps:
          - uses: actions/checkout@v7
          - uses: aws-actions/configure-aws-credentials@v6
            with:
              role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
              aws-region: ${{ env.AWS_REGION }}
          - name: Fetch the live task definition
            run: aws ecs describe-task-definition --task-definition churn-service --query taskDefinition > task-def.json
          - id: render
            uses: aws-actions/amazon-ecs-render-task-definition@v1
            with:
              task-definition: task-def.json
              container-name: churn
              image: ${{ needs.build.outputs.image }}
          - uses: aws-actions/amazon-ecs-deploy-task-definition@v2
            with:
              task-definition: ${{ steps.render.outputs.task-definition }}
              service: churn-service
              cluster: ml-services
              wait-for-service-stability: true   # the job fails if the new tasks never become healthy

    environment: production — a named place with its own rules and approvers. outputs — passing a value from one job to the next.

    Run python check_workflow.py workflows/deploy.yml to confirm all three jobs and their needs chain resolve.

    terminalactual output
    $ python check_workflow.py workflows/deploy.yml
    workflows/deploy.yml: parses; triggers=['pull_request', 'push']; jobs=['test', 'build', 'deploy']
      OIDC permission present, no stored AWS secret key in the file

The whole program

Chunk 1 is the test job. Chunk 2 adds permissions, env and the build job. Chunk 3 adds the deploy job. This is workflows/deploy.yml; copy it to .github/workflows/deploy.yml.

.github/workflows/deploy.ymlvalidated, not applied
# Chunk 2: chunk 1 plus build the image and push it to ECR, on main only.
name: churn-service
on:
  push:
    branches: [main]
  pull_request:

permissions:
  id-token: write   # lets the job ask GitHub for a signed identity token (OIDC)
  contents: read

env:
  AWS_REGION: us-east-1
  ECR_REPO: churn-service

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.12"
      - run: pip install -r requirements.txt pytest httpx
      - run: pytest -q

  build:
    needs: test                       # no image is built unless the tests passed
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    outputs:
      image: ${{ steps.meta.outputs.image }}
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}   # the role from main.tf; no access key anywhere
          aws-region: ${{ env.AWS_REGION }}
      - id: ecr
        uses: aws-actions/amazon-ecr-login@v2
      - id: meta
        run: echo "image=${{ steps.ecr.outputs.registry }}/${{ env.ECR_REPO }}:${{ github.sha }}" >> "$GITHUB_OUTPUT"
      - uses: docker/build-push-action@v7
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.image }}

  deploy:
    needs: build
    runs-on: ubuntu-latest
    environment: production           # an optional approval gate lives on this environment
    steps:
      - uses: actions/checkout@v7
      - uses: aws-actions/configure-aws-credentials@v6
        with:
          role-to-assume: ${{ vars.AWS_DEPLOY_ROLE_ARN }}
          aws-region: ${{ env.AWS_REGION }}
      - name: Fetch the live task definition
        run: aws ecs describe-task-definition --task-definition churn-service --query taskDefinition > task-def.json
      - id: render
        uses: aws-actions/amazon-ecs-render-task-definition@v1
        with:
          task-definition: task-def.json
          container-name: churn
          image: ${{ needs.build.outputs.image }}
      - uses: aws-actions/amazon-ecs-deploy-task-definition@v2
        with:
          task-definition: ${{ steps.render.outputs.task-definition }}
          service: churn-service
          cluster: ml-services
          wait-for-service-stability: true   # the job fails if the new tasks never become healthy

Read the output. The checker printed which triggers and jobs each file defines, and confirmed the two safety properties that matter: the OIDC permission is present and no AWS secret key is written in the file. The pytest line in chunk 1 is the real test step, run on this machine. It is the same command the robot runs.

Where the eval gate fits

This workflow tests code. A change to a prompt or a model also needs a different check: does the answer quality still hold? That is the eval gate from Module 07, wired to pull requests in Module 12's CI/CD section. The two fit together: the eval gate is a required check on the pull request, and this pipeline only runs after the merge it allowed.

The honest limit of any pipeline: it proves the new version starts and passes tests. It cannot prove the model is still good for real traffic. Sections 9 and 10 cover what catches that: canary analysis and alerts on the model's own output.

Action versions used above, the newest majors as of October 2026. Check each repository's releases page before copying.
ActionVersion usedWhat it does
actions/checkoutv7Fetches your repository onto the runner
actions/setup-pythonv7Installs the Python version you ask for
aws-actions/configure-aws-credentialsv6Swaps the OIDC token for temporary AWS keys
aws-actions/amazon-ecr-loginv2Logs Docker in to your ECR registry
docker/build-push-actionv7Builds an image and pushes it
aws-actions/amazon-ecs-render-task-definitionv1Puts a new image into a task definition file
aws-actions/amazon-ecs-deploy-task-definitionv2Registers it, updates the service, optionally waits

A security note that senior reviewers expect: pin third-party actions to a full commit SHA, not a moving major tag, because a tag can be repointed. This chapter uses major tags to keep the YAML readable.

CI
Build and test every change automatically.
CD
Release changes that pass, automatically, with a check that they came up healthy.
OIDC
A signed identity token swapped for temporary AWS keys. Needs permissions: id-token: write.
Trust policy
The AWS rule saying which token (repo and branch) may borrow a role.
Image tag
The git SHA. It names exactly what is running and what to roll back to.
wait-for-service-stability
Keeps the deploy job open until tasks are healthy, so a bad deploy turns the job red.

06 · KubernetesKubernetes for ML, in Plain Words

Kubernetes keeps the number of copies of your containers you asked for, on a pool of machines, and replaces any that die. You describe the end state in YAML files; it works to make reality match.

The pipeline is green and Fargate is serving. Then Viktor mentions that SaaSify's next product needs GPUs for an open model, and the data team already runs a Kubernetes cluster. Priya has not run one. She learns the five ideas she will meet in every manifest, using the same churn service, and keeps Fargate for this contract.

Start with the question every Kubernetes object answers: what do I need to know to read a manifest? The objects fall into four groups.

Things that run

Things that route

Things that react

Things that reserve

Deployment churnreplicas: 3Pod churn-7d9f-a250m CPU, 512Mi RAM/readyz: 200Pod churn-7d9f-b250m CPU, 512Mi RAM/readyz: 200Pod churn-7d9f-c250m CPU, 512Mi RAM/readyz: 503 (loading)Service churnport 80 -> 8000no traffic yetpicks pods with label app=churnHPAtarget 60% CPU3 to 10 podssets replicas1234
Fig. 12b.9 — The Kubernetes objects for the churn service. The Deployment keeps three pods; the Service routes only to pods whose readiness probe passes; the autoscaler changes the replica count.
  1. Deployment (marker 1). Says "keep 3 copies of this container running". If a pod dies, the Deployment starts a replacement. When you change the image it replaces pods a few at a time, which is a rolling update.
  2. Service (marker 2). One stable address in front of changing pods. It finds pods by label, and sends traffic only to pods that report ready. The third pod is still loading its model, so it gets none.
  3. Autoscaler (marker 3). The HPA watches average CPU. It compares usage to the 250m each pod requested; above 60% of that (150m) it raises replicas, up to 10.
  4. Requests and the pending pod (marker 4). Each pod asks for 250m CPU and 512Mi memory. The scheduler only places a pod where that much is free. The amber pod is alive but not ready, which is exactly the case liveness and readiness are separate for.

Read Fig. 12b.9 from the left. The Deployment at marker 1 makes three pods. The Service at marker 2 sends requests to the two that are ready and none to the pod still loading. The autoscaler at marker 3 watches CPU and changes the Deployment's replica count.

Build it in chunks

We build the manifest in three chunks. Every chunk is a complete, valid file. Not run here: kubectl apply and kubectl rollout, because there is no cluster on this machine (a local kind cluster was deliberately not started to protect memory) and kubectl --dry-run=client still needs an API server for discovery. The files were checked against the Kubernetes 1.34 schemas with kubeconform instead.

  1. Chunk 1 — the smallest useful Deployment

    Start with only: which image, how many copies, which label ties pods to the Deployment.

    Step-by-step: what chunk 1 does, in plain English
    1. apiVersion and kind say what type of object this is.
    2. replicas: 3 asks for three identical pods.
    3. selector.matchLabels says which pods this Deployment owns; the pod template's labels must match it.
    4. The template holds one container: the ECR image and the port it listens on.
    c1-minimal.yamlvalidated, not applied
    # Chunk 1: the smallest useful Deployment: "keep 3 copies of this container running".
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: churn
      labels: {app: churn}
    spec:
      replicas: 3
      selector:
        matchLabels: {app: churn}     # which pods belong to this Deployment
      template:
        metadata:
          labels: {app: churn}        # must match the selector above
        spec:
          containers:
            - name: churn
              image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/churn-service:GIT_SHA
              ports:
                - containerPort: 8000

    kind: Deployment — "keep N copies of this pod running and replace them on request".

    Check it against Kubernetes' own schema: kubeconform -strict -kubernetes-version 1.34.0 k8s/c1-minimal.yaml.

    terminalactual output
    $ kubeconform -strict -kubernetes-version 1.34.0 -summary k8s/c1-minimal.yaml
    Summary: 1 resource found in 1 file - Valid: 1, Invalid: 0, Errors: 0, Skipped: 0
  2. Chunk 2 — a safe rollout, resource requests and three probes

    Chunk 1 works on a good day. This chunk makes it behave on a bad one: no downtime during a rollout, no pod that hogs the node, and the platform able to tell sick from busy.

    Step-by-step: what chunk 2 does, in plain English
    1. RollingUpdate with maxSurge: 1 and maxUnavailable: 0: start one extra pod, wait for it to be ready, then stop an old one. Never fewer than 3 ready.
    2. Prometheus annotations tell a scraper where /metrics lives.
    3. requests reserve CPU and memory for scheduling. The memory limit kills a pod that leaks past 1 Gi.
    4. The startupProbe gives a slow model load up to 120 seconds before the other probes begin.
    5. Liveness restarts a stuck pod; readiness removes an unready pod from the Service.
    c2-probes-resources.yaml — chunk 2: the lines it addsvalidated, not applied
    # Chunk 2: chunk 1 plus a safe rollout, resource requests and three probes.
    # ... (unchanged lines omitted) ...
        matchLabels: {app: churn}
      strategy:
        type: RollingUpdate
        rollingUpdate:
          maxSurge: 1          # start one extra pod before stopping an old one
          maxUnavailable: 0    # never drop below 3 ready pods during a rollout
    # ... (unchanged lines omitted) ...
          labels: {app: churn}
          annotations:
            prometheus.io/scrape: "true"
            prometheus.io/port: "8000"
            prometheus.io/path: /metrics
    # ... (unchanged lines omitted) ...
          terminationGracePeriodSeconds: 30
    # ... (unchanged lines omitted) ...
              env:
                - name: MODEL_VERSION
                  value: GIT_SHA
              resources:
                requests: {cpu: 250m, memory: 512Mi}   # what the scheduler reserves for the pod
                limits: {memory: 1Gi}                  # over this and the pod is killed (OOM)
              startupProbe:                            # gives a slow model load time before the others start
                httpGet: {path: /healthz, port: 8000}
                periodSeconds: 5
                failureThreshold: 24
              livenessProbe:                           # "is the process stuck?"  failing = restart the pod
                httpGet: {path: /healthz, port: 8000}
                periodSeconds: 10
                failureThreshold: 3
              readinessProbe:                          # "should I get traffic?"  failing = removed from the Service
                httpGet: {path: /readyz, port: 8000}
                periodSeconds: 5
                failureThreshold: 2

    requests against limits: a request is a promise to the scheduler, a limit is a ceiling enforced while running. httpGet probe — Kubernetes calls your URL.

    Check it the same way. Strict mode rejects a misspelt field such as readynessProbe.

    terminalactual output
    $ kubeconform -strict -kubernetes-version 1.34.0 -summary k8s/c2-probes-resources.yaml
    Summary: 1 resource found in 1 file - Valid: 1, Invalid: 0, Errors: 0, Skipped: 0
  3. Chunk 3 — a Service in front, and an autoscaler behind

    Pods come and go and their addresses change. A Service gives clients one address; an autoscaler changes the count when load changes.

    Step-by-step: what chunk 3 does, in plain English
    1. The Service selects pods labelled app: churn and maps port 80 to the container's 8000.
    2. The HorizontalPodAutoscaler targets the Deployment, between 3 and 10 replicas.
    3. It aims for 60% average CPU utilisation, measured against each pod's request (250m), so the target is 150m per pod.
    deployment.yaml — chunk 3: the lines it addsvalidated, not applied
    # Deployment + Service + HPA for the churn service.
    # Image tag is a placeholder: the pipeline replaces it (see ci_c3.yml / deploy.yml).
    # ... (unchanged lines omitted) ...
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: churn
    spec:
      selector: {app: churn}
      ports:
        - port: 80
          targetPort: 8000
    ---
    apiVersion: autoscaling/v2
    kind: HorizontalPodAutoscaler
    metadata:
      name: churn
    spec:
      scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: churn}
      minReplicas: 3
      maxReplicas: 10
      metrics:
        - type: Resource
          resource:
            name: cpu
            target: {type: Utilization, averageUtilization: 60}   # 60% of the *requested* 250m

    kind: Service and kind: HorizontalPodAutoscaler; --- separates objects in one file.

    Validate the three objects together: all three should be valid.

    terminalactual output
    $ kubeconform -strict -kubernetes-version 1.34.0 -summary k8s/deployment.yaml
    Summary: 3 resources found in 1 file - Valid: 3, Invalid: 0, Errors: 0, Skipped: 0

The whole program

Chunk 1 is the pod template and selector. Chunk 2 adds the rolling-update strategy, annotations, requests and probes. Chunk 3 adds the Service and the autoscaler. This is k8s/deployment.yaml.

k8s/deployment.yamlvalidated, not applied
# Deployment + Service + HPA for the churn service.
# Image tag is a placeholder: the pipeline replaces it (see ci_c3.yml / deploy.yml).
apiVersion: apps/v1
kind: Deployment
metadata:
  name: churn
  labels: {app: churn}
spec:
  replicas: 3
  selector:
    matchLabels: {app: churn}
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1          # start one extra pod before stopping an old one
      maxUnavailable: 0    # never drop below 3 ready pods during a rollout
  template:
    metadata:
      labels: {app: churn}
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "8000"
        prometheus.io/path: /metrics
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: churn
          image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/churn-service:GIT_SHA
          ports:
            - containerPort: 8000
          env:
            - name: MODEL_VERSION
              value: GIT_SHA
          resources:
            requests: {cpu: 250m, memory: 512Mi}   # what the scheduler reserves for the pod
            limits: {memory: 1Gi}                  # over this and the pod is killed (OOM)
          startupProbe:                            # gives a slow model load time before the others start
            httpGet: {path: /healthz, port: 8000}
            periodSeconds: 5
            failureThreshold: 24
          livenessProbe:                           # "is the process stuck?"  failing = restart the pod
            httpGet: {path: /healthz, port: 8000}
            periodSeconds: 10
            failureThreshold: 3
          readinessProbe:                          # "should I get traffic?"  failing = removed from the Service
            httpGet: {path: /readyz, port: 8000}
            periodSeconds: 5
            failureThreshold: 2
---
apiVersion: v1
kind: Service
metadata:
  name: churn
spec:
  selector: {app: churn}
  ports:
    - port: 80
      targetPort: 8000
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: churn
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: churn}
  minReplicas: 3
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target: {type: Utilization, averageUtilization: 60}   # 60% of the *requested* 250m

Read the output. Each run reports how many Kubernetes objects it found and how many were valid against the 1.34 schemas. Chunk 3 finds three objects: the Deployment, the Service and the autoscaler. A typo in a field name would show up as an invalid resource. What this does not prove: that the cluster has room for three pods requesting 250m CPU each, or that the image exists.

How the autoscaler decides, with numbers

The autoscaler compares what pods use to what they requested. Its rule, in words: new pod count = current pods × (current average utilisation ÷ target utilisation), rounded up. Suppose load rises and the three pods now average 240m CPU each.

  1. Utilisation. Each pod requested 250m, so 240m ÷ 250m = 96%.
  2. Ratio to target. The target is 60%, so 96 ÷ 60 = 1.6.
  3. New count. 3 pods × 1.6 = 4.8, rounded up to 5 pods.
  4. Check the cap. Between 3 and 10, so 5 is allowed.

Notice the weak point: the measure is CPU. For a model server, requests can pile up in a queue while CPU stays low (waiting on a downstream API, say). Scaling on request rate or queue length is often better for ML, and it needs a metrics adapter such as KEDA, which is outside this chapter.

GPUs: the same objects with three extra lines

A GPU server uses the same Deployment. Three lines change. A node selector steers the pod to GPU machines. A toleration lets it land on nodes that are fenced off for GPU work. And a limits entry asks for whole GPUs. The readiness probe also waits longer, because loading model weights takes minutes.

Step-by-step: what deployment-gpu.yaml does, in plain English
  1. Create a Deployment of one pod running vLLM, the open-model server from Module 11.
  2. nodeSelector restricts it to nodes of a GPU instance type.
  3. The toleration lets it ignore the "GPU nodes only" taint that keeps ordinary pods away.
  4. Requests reserve 4 CPUs and 16 Gi; the limit nvidia.com/gpu: 1 takes one whole GPU. You cannot ask for half.
  5. The readiness probe waits 60 seconds before the first check.
k8s/deployment-gpu.yamlvalidated, not applied
# The same idea for a model that needs a GPU. Needs a cluster with the NVIDIA device plugin installed.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: llm-server
  labels: {app: llm-server}
spec:
  replicas: 1
  selector:
    matchLabels: {app: llm-server}
  template:
    metadata:
      labels: {app: llm-server}
    spec:
      nodeSelector:
        node.kubernetes.io/instance-type: g5.xlarge    # steer the pod to a GPU node
      tolerations:
        - key: nvidia.com/gpu                          # GPU nodes are usually tainted so ordinary pods stay off
          operator: Exists
          effect: NoSchedule
      containers:
        - name: vllm
          image: vllm/vllm-openai:latest
          resources:
            requests: {cpu: "4", memory: 16Gi}
            limits:
              nvidia.com/gpu: 1                        # whole GPUs only; you cannot ask for 0.5
          readinessProbe:
            httpGet: {path: /health, port: 8000}
            initialDelaySeconds: 60                    # loading weights takes minutes, not seconds
            periodSeconds: 10
terminalactual output
$ kubeconform -strict -kubernetes-version 1.34.0 -summary k8s/deployment-gpu.yaml
Summary: 1 resource found in 1 file - Valid: 1, Invalid: 0, Errors: 0, Skipped: 0

Not run: scheduling this on a GPU node. It needs the NVIDIA device plugin and a GPU node group. The file is schema-valid only.

For the depth behind these objects (networking, storage, RBAC, Helm), read the engineering track's Kubernetes chapter; the Docker details are in its Docker chapter. This chapter only needs you to read and write manifests like the ones above.

Pod
The smallest runnable unit: containers that start and stop together.
Deployment
Keeps N pods running; does rolling updates; supports kubectl rollout undo.
Service
A stable address that routes only to ready pods, chosen by label.
Readiness / liveness / startup
Route traffic / restart the pod / wait for a slow start.
HPA
New pods = current pods × (current ÷ target utilisation), rounded up, within min and max.
Request / limit
Scheduler reservation / enforced ceiling. Utilisation is measured against the request.
GPU
nvidia.com/gpu: 1 under limits, plus a node selector and toleration.

07 · ObservabilityObservability: What to Measure and Where to Look

Observability means the running service gives you enough evidence to answer "what is wrong, and since when?" without logging in to it. Without it you find out about an outage from the customer, which is the most expensive way.

It is Tuesday, week two. The service is live on Fargate and the pipeline has deployed it twice. Priya has metrics at /metrics but nobody looks at raw text. She needs to decide which numbers go on one screen so that a half-asleep person can read it at 2 a.m.

The classic answer is three signals, abbreviated RED: Rate (requests per second), Errors (the share that fail) and Duration (how long they take). For a model service you add two more: whether the model is still right, and what each call costs. All five are in the table below, each tied to a metric the code already exports.

Five questions an on-call engineer asks, the metric that answers each, and where it is used later in this chapter.
QuestionSignalMetric in our codeUsed for
How busy is it?Raterate(http_requests_total[5m])Capacity and autoscaling
Is it failing?Errors5xx share of http_requests_totalThe SLO and burn-rate alerts
Is it slow?Durationhistogram_quantile(0.95, ...) on the duration histogram, plus p50 and p99Latency SLO, canary analysis
Is the model right?Prediction driftmean of prediction_score by versionBad-model detection
What does it cost?LLM tokens and dollarsllm_cost_dollars_total by versionThe cost-spike incident

Latency needs one more word. Report it as percentiles, not an average. The p95 is the time that 95 of every 100 requests beat; p99 is the same for 99. An average hides the slow few, and the slow few are the customers who call you. Section 3's follow-up worked out how Prometheus gets them from buckets.

The model-specific rows carry the new idea from Module 12's drift section: a service can be up and wrong. The mean prediction score, split by version, is a cheap drift detector. If a new version moves the average from 0.30 to 0.62 on the same kind of customers, something changed in the model.

One screen: the same panels at two moments

Tuesday 14:00 — healthyTuesday 14:06 — after a bad releaserequests / minute600error ratio0.2%mean prediction score0.30LLM cost / minute$0.24requests / minute600error ratio12.0%mean prediction score0.62LLM cost / minute$0.24123
Fig. 12b.10 — The same four panels at two moments. The bad release moves the error ratio from 0.2% to 12.0% and the mean score from 0.30 to 0.62, while traffic and cost do not move.
  1. Error ratio (marker 1). The share of requests that fail. At 12% against a 0.5% budget this panel is the loud one. It is the only panel a status-code-only dashboard would have.
  2. Mean prediction score (marker 2). The average probability the model returned. It more than doubled. A model that gives wrong answers without errors would move only this panel, which is why it is on the board.
  3. Cost per minute (marker 3). Unchanged at $0.24, so cost is not the cause here. A panel that does not move is useful: it tells you what to stop suspecting.

Look at Fig. 12b.10. The right half is what Priya would see six minutes after a bad deploy. Two panels turned red. Two did not move, and that is information too: traffic is normal, so this is not a load problem, and cost is flat, so no runaway prompt. The dashboard is built from the five-row table above.

The dashboard itself is a JSON file, observability/grafana_dashboard.json, that Grafana imports. It holds five panels: rate, errors, p50/p95/p99, mean score per version, and error budget remaining. Keeping it in git means the dashboard is reviewed and restored like code. The check below parses it and the alert rules, and runs promtool, Prometheus's own linter, on the rules.

terminalactual output
$ python observability/check_observability.py
rules parse: 4 recording rules, 3 alerts -> ['ChurnFastBurn', 'ChurnMediumBurn', 'ChurnSlowLeak']
dashboard parses: 'Churn service — RED + model' with 5 panels
  panel 1: Rate: requests per second  (1 query)
  panel 2: Errors: share of 5xx  (1 query)
  panel 3: Duration: p50, p95, p99 (seconds)  (3 queries)
  panel 4: Model: mean prediction score by version  (1 query)
  panel 5: Error budget remaining (30 days, 99.5% SLO)  (1 query)
terminalactual output
$ promtool check rules observability/slo_alerts.yml
Checking observability/slo_alerts.yml
  SUCCESS: 7 rules found

Read the output. The first block shows the dashboard and the three alert rules parse and have the right shape. The second shows Prometheus's own tool accepts the rules: seven rules, four that precompute error ratios and three alerts. What neither proves is that the queries return sensible numbers; that needs a running Prometheus. They were not run against live data here.

Counting what an LLM call costs

The churn model is cheap per call. An LLM feature is not, and its failure mode is a bill. So the same pattern applies: a counter for tokens and a counter for dollars, labelled by version. The script below uses made-up example prices and three fake calls; the third is a runaway prompt that re-sent its whole history.

Step-by-step: what llm_cost_metrics.py does, in plain English
  1. Create a private metrics registry so the script prints only its own metrics.
  2. Define two counters: tokens (labelled input or output, and version) and dollars (labelled by version).
  3. record_call adds the token counts and the dollar cost, computed from example prices per million tokens.
  4. Record two normal calls (about 1,200 tokens in, 300 out) and one runaway call (48,000 tokens in).
  5. Print the counter lines in the same text format Prometheus reads.
llm_cost_metrics.pyruns offline
# pip install "prometheus-client>=0.21,<1"      Runs offline: three fake model calls, real Prometheus counters.
from prometheus_client import CollectorRegistry, Counter, generate_latest

# Example prices in dollars per million tokens. Replace with your provider's current price list.
PRICE = {"input": 3.00, "output": 15.00}

registry = CollectorRegistry()
TOKENS = Counter("llm_tokens_total", "Tokens used", ["direction", "version"], registry=registry)
COST = Counter("llm_cost_dollars_total", "Money spent on tokens", ["version"], registry=registry)


def record_call(version: str, input_tokens: int, output_tokens: int) -> None:
    TOKENS.labels("input", version).inc(input_tokens)
    TOKENS.labels("output", version).inc(output_tokens)
    COST.labels(version).inc((input_tokens * PRICE["input"] + output_tokens * PRICE["output"]) / 1_000_000)


record_call("3f9c1ab", 1_200, 300)    # a normal helpdesk answer: 1,200 tokens in, 300 out
record_call("3f9c1ab", 1_100, 250)
record_call("3f9c1ab", 48_000, 300)   # a runaway prompt that re-sent its whole history
for line in generate_latest(registry).decode().splitlines():
    if line.startswith(("llm_tokens_total{", "llm_cost_dollars_total{")):
        print(line)
terminalactual output
$ python llm_cost_metrics.py
llm_tokens_total{direction="input",version="3f9c1ab"} 50300.0
llm_tokens_total{direction="output",version="3f9c1ab"} 850.0
llm_cost_dollars_total{version="3f9c1ab"} 0.16365

Read the output. Three calls used 50,300 input tokens and 850 output tokens, costing $0.16365 in total. The runaway call alone cost $0.1485 of that: about 18 times a normal call at $0.0081. In production a rate of llm_cost_dollars_total that jumps like this is the signal for incident 3 in Section 10.

Traces for the LLM calls: Langfuse

Metrics tell you that something is slow or expensive. A trace tells you which prompt, which tool call and which retrieved document. Module 12's observability section explains why the trace, not the log line, is the main object for LLM systems. Here is the smallest working instrument, with an offline stand-in so it runs without a key.

Step-by-step: what langfuse_trace.py does, in plain English
  1. If Langfuse keys are in the environment, import the SDK and wrap the function with @observe, marking it as an LLM generation.
  2. Inside, record the model name and token usage on the current span.
  3. Call the function, then flush() so the trace is sent before the program exits.
  4. Without keys, the else branch builds the same fields as a dictionary and prints them, so you can see what a trace would hold.
langfuse_trace.pyneeds API key
# pip install "langfuse>=3,<5"      needs API key: LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY (and LANGFUSE_HOST if self-hosted)
# Without keys this file runs an offline stand-in that prints what the trace would contain.
import os
import time

if os.environ.get("LANGFUSE_PUBLIC_KEY"):
    from langfuse import get_client, observe

    @observe(as_type="generation")          # one span per call; Langfuse records input, output, timing
    def answer(question: str) -> str:
        get_client().update_current_generation(model="stand-in-model", usage_details={"input": 42, "output": 17})
        return "Your invoice is attached."

    print(answer("Where is my invoice?"))
    get_client().flush()                    # send before the process exits
else:
    def answer(question: str) -> str:
        start = time.perf_counter()
        result = "Your invoice is attached."
        span = {"name": "answer", "input": question, "output": result, "model": "stand-in-model",
                "usage": {"input": 42, "output": 17}, "ms": round((time.perf_counter() - start) * 1000, 2)}
        print("OFFLINE trace:", span)
        return result

    answer("Where is my invoice?")
terminalactual output
$ python langfuse_trace.py
OFFLINE trace: {'name': 'answer', 'input': 'Where is my invoice?', 'output': 'Your invoice is attached.', 'model': 'stand-in-model', 'usage': {'input': 42, 'output': 17}, 'ms': 0.0}

Not run with a real key: the Langfuse branch. The output above is the offline stand-in. Langfuse's Python SDK moved to a new major version in March 2026; if update_current_generation is missing in your version, use the SDK's current generation-update call from its migration guide.

RED
Rate, Errors, Duration: the three signals for any request-driven service.
Percentile
p95 is the time 95% of requests beat. Report p50, p95, p99; never only the average.
Model signal
Mean prediction score by version. Catches wrong answers with 200 status codes.
Cost signal
Tokens and dollars as counters, by version. Catches runaway prompts.
Dashboard as code
Grafana JSON in git. Same review and rollback as the service.
Trace
One request's whole path through prompts and tools (Langfuse). Metrics say where to look; traces say what happened.

08 · SLOs and error budgetsSLOs, Error Budgets and Burn-Rate Alerts, with Real Numbers

An SLO turns "be reliable" into a number you can spend. The error budget is the failure you are allowed. A burn-rate alert tells you how fast you are spending it, so you act before the month is lost.

The dashboard works. Priya now has to decide which of those numbers should wake her up. Her answer must come from the contract: 99.5% of requests succeed over 30 days, and a miss costs $10,000. This is where the promise becomes minutes.

The vocabulary (SLI, SLO, error budget) is defined once in Appendix 2's refresher, including why 99.9% of a month is 43 minutes 49 seconds. Not repeated here. This section uses it: first the arithmetic for our contract, then the alert rule that protects it. One difference to note: A2 uses an average month of 43,830 minutes; the contract here says 30 days, so we use 43,200.

The arithmetic: from a percentage to minutes

slo_math.py outputactual output
$ python slo_math.py
target   allowed failure per 30 days
99.00%     432.0 min  ( 7.20 h)
99.50%     216.0 min  ( 3.60 h)
99.90%      43.2 min  ( 0.72 h)
99.95%      21.6 min  ( 0.36 h)

burn rate  budget lasts   alert rule (long window AND short window)
    14.4      50.0 h       60 min AND   5 min -> 2.0% of budget spent in the long window
       6     120.0 h      360 min AND  30 min -> 5.0% of budget spent in the long window
       1     720.0 h     4320 min AND 360 min -> 10.0% of budget spent in the long window
burn 14.4 means an error rate of 7.20% sustained
burn    6 means an error rate of 3.00% sustained
burn    1 means an error rate of 0.50% sustained

at minute 110: 60-minute average 8.07% (burn 16.1), 5-minute average 0.20% (burn 0.4)
month budget at 600 requests/minute: 129,600 failed requests; one hour of 12% errors spends 4,320 = 3.3%

Read the output. The first table turns each target into allowed failure per 30 days. 99.5% allows 216 minutes; one extra nine (99.9%) allows 43.2. The second table is the new idea: burn rate. A burn rate of 1 spends the budget exactly as fast as the month allows. A burn rate of 14.4 spends it 14.4 times faster, which for 99.5% means a sustained 7.2% error rate.

The last lines work the hour-of-trouble example: at 600 requests a minute, one hour of 12% errors fails 4,320 requests, which is 3.3% of the month's 129,600-request budget.

burn 1 (0.5% errors)720 h (30 days)slow leak: ticketburn 6 (3% errors)120 h = 5 dayspage: 6 h and 30 min windowsburn 14.4 (7.2% errors)50 hpage: 1 h and 5 min windowsburn 24 (12% errors)30 hour bad release12Time until the 30-day error budget is empty, if the failure rate never stops
Fig. 12b.11 — Four burn rates and how long a 99.5% monthly budget survives each: 720 hours, 120 hours, 50 hours and, for a 12% failure, 30 hours.
  1. The 14.4 bar (marker 1). At 7.2% errors the budget is empty in 50 hours. The rule of thumb behind 14.4: it spends 2% of the month's budget in one hour (14.4 ÷ 720 hours = 2%), which is fast enough that a person should be woken.
  2. The 6 bar (marker 2). At 3% errors the budget lasts five days. Nothing is on fire, but it will be spent before the month ends, so a person should look within hours, not days.

Look at Fig. 12b.11. The bad release from the hook has burn rate 24 (12% ÷ 0.5%). At that rate the whole month's budget is gone in 30 hours. That is fast enough to need a page and slow enough that a rehearsed rollback easily beats it. The question is only how quickly the alert fires.

The alert rule: two windows, both over the line

The rule has one trick. An alert fires only when two time windows both exceed the burn threshold: a long one to prove the problem is real, and a short one to prove it is still happening. Fig. 12b.12 shows why with a fault that is already fixed.

0306090120minutes7.2% = burn 14.412% errors12%0%now = minute 110long window: 60 min, average 8.1%short window: 5 min, 0.2%12
Fig. 12b.12 — A fault from minute 60 to 100 is fixed. At minute 110 the long window still averages 8.1% (above 7.2%) but the short window shows 0.2%, so the two-window rule stays quiet.
  1. Long window (marker 1). The last 60 minutes still contain 40 bad minutes, so its average is (40 × 12% + 20 × 0.2%) ÷ 60 = 8.1%, which is burn 16.1. Alone, it would keep the page ringing for another 25 minutes after the fix.
  2. Short window (marker 2). The last 5 minutes were all healthy: 0.2%, burn 0.4. Requiring both windows to be over the line makes alerts start fast and stop fast.
The three alerts for a 99.5% SLO. Long and short windows must both be over the burn rate.
AlertBurn rateLong windowShort windowBudget spent in the long windowAction
Fast burn14.41 hour5 minutes2%Page now
Medium burn66 hours30 minutes5%Page now
Slow leak16 hours (simplified; the full rule uses 3 days)30 minutesabout 10% over 3 daysOpen a ticket

This is the multiwindow, multi-burn-rate method from Google's SRE workbook. The three numbers (14.4, 6, 1) are choices, not laws: they say "page when 2% or 5% of the budget disappears in an hour or six, ticket when it leaks". Here is the first one written for Prometheus.

Anatomy of the fast-burn alert — the one expression to write from memory
job:error_ratio:rate1h 1> (14.4 * 0.005) 2and 3job:error_ratio:rate5m > (14.4 * 0.005) 4
  1. The long ratio. The share of requests that failed over the last hour, precomputed by a recording rule so the alert is cheap. People forget to restrict it to the one route that matters, and a health check inflates the numbers.
  2. The threshold. Burn rate times the budget: 14.4 × 0.005 = 0.072, or 7.2% errors. Write the product out; it makes the 99.5% visible in the rule and a reviewer can check it against the contract.
  3. The and. Both sides must be true at once. Using or here would page on every old fault that the long window remembers.
  4. The short ratio. The same threshold over five minutes. It is what lets the page stop soon after the fix. A common mistake is to give it a different, looser threshold.
Step-by-step: what slo_alerts.yml does, in plain English
  1. Four recording rules precompute the error ratio of /predict over 5 minutes, 30 minutes, 1 hour and 6 hours, so the alerts read stored numbers.
  2. ChurnFastBurn pages when the 1-hour and 5-minute ratios both exceed 14.4 × 0.005.
  3. ChurnMediumBurn pages when the 6-hour and 30-minute ratios both exceed 6 × 0.005.
  4. ChurnSlowLeak opens a ticket when both exceed the plain SLO rate of 0.005.
  5. Each alert carries a severity label and a link to the runbook in Section 9.
observability/slo_alerts.ymlvalidated, not applied
# Prometheus rules: the error-ratio SLI, and the multiwindow burn-rate alerts for a 99.5% SLO.
# 0.005 is the error budget (1 - 0.995). 14.4 x 0.005 = 7.2% errors; 6 x 0.005 = 3%.
groups:
  - name: churn-sli
    rules:
      - record: job:error_ratio:rate5m
        expr: sum(rate(http_requests_total{route="/predict",status=~"5.."}[5m])) / sum(rate(http_requests_total{route="/predict"}[5m]))
      - record: job:error_ratio:rate30m
        expr: sum(rate(http_requests_total{route="/predict",status=~"5.."}[30m])) / sum(rate(http_requests_total{route="/predict"}[30m]))
      - record: job:error_ratio:rate1h
        expr: sum(rate(http_requests_total{route="/predict",status=~"5.."}[1h])) / sum(rate(http_requests_total{route="/predict"}[1h]))
      - record: job:error_ratio:rate6h
        expr: sum(rate(http_requests_total{route="/predict",status=~"5.."}[6h])) / sum(rate(http_requests_total{route="/predict"}[6h]))
  - name: churn-slo-burn
    rules:
      - alert: ChurnFastBurn
        expr: job:error_ratio:rate1h > (14.4 * 0.005) and job:error_ratio:rate5m > (14.4 * 0.005)
        labels: {severity: page}
        annotations:
          summary: "2% of the monthly error budget is gone in one hour"
          runbook: "runbook.md#rollback"
      - alert: ChurnMediumBurn
        expr: job:error_ratio:rate6h > (6 * 0.005) and job:error_ratio:rate30m > (6 * 0.005)
        labels: {severity: page}
        annotations:
          summary: "5% of the monthly error budget is gone in six hours"
          runbook: "runbook.md#rollback"
      - alert: ChurnSlowLeak
        expr: job:error_ratio:rate6h > 0.005 and job:error_ratio:rate30m > 0.005
        labels: {severity: ticket}
        annotations:
          summary: "errors are above the SLO rate and have been for hours"

The rules were checked with promtool in Section 7. The chapter's lab drill (Section 10) implements the same two-window logic in Python so you can watch it fire and stop on simulated traffic.

BE the alert

Play Prometheus. For each moment, you are given the 1-hour burn rate and the 5-minute burn rate. The page rule is: both must be above 14.4. Decide page or no page for each, then open the answers.

  1. (a) 1-hour burn 16.1, 5-minute burn 20.0
  2. (b) 1-hour burn 16.1, 5-minute burn 0.4 (the fault was just fixed)
  3. (c) 1-hour burn 3.0, 5-minute burn 25.0 (a two-minute blip)
  4. (d) 1-hour burn 14.5, 5-minute burn 14.5
  5. (e) 1-hour burn 14.0, 5-minute burn 30.0

Which of the five wake Priya? Write the letters.

Check your answer

Page: (a) and (d). In both, the long window proves the trouble is real and the short window proves it is still happening.

(b) stays quiet because the short window is clear: the fault is over, even though the hour still remembers it (this is Fig. 12b.12). (c) stays quiet because the long window is far below 14.4: a short blip has not spent enough budget. (e) is the near miss: the short window is alarming but the long one, at 14.0, is just under the line, so it waits a few more minutes. The rule trades a few minutes of delay for far fewer false pages.

Questions you might be asking now

Four questions that come up the first time you meet error budgets. They use the contract's numbers: a 99.5% target, a 30-day month of 43,200 minutes, and 600 requests a minute. Every figure comes from slo_math.py above.

What does "burn rate 14.4" actually mean?

It means you are failing 14.4 times faster than the contract allows. At that speed the whole month's error budget is gone in about 50 hours instead of 720.

  1. The allowed error rate. 100% − 99.5% = 0.5%, written 0.005.
  2. The observed rate for burn 14.4. 14.4 × 0.005 = 0.072, or 7.2% of requests failing.
  3. How long the budget lasts. A month is 720 hours. 720 ÷ 14.4 = 50 hours.
  4. Why 14.4 was chosen. In one hour at that burn, you spend 14.4 ÷ 720 = 2% of the month's budget. That is the amount someone decided is worth waking a person for.

Burn rate is "how many times faster than allowed"; multiply it by the allowed error rate to get the error rate you are seeing.

Why two windows? Isn't one window enough?

No. One long window keeps alerting after the fault is fixed. One short window alerts on every two-minute blip. Two windows together alert quickly and stop quickly.

Three alert designs on the fault of Fig. 12b.12, looked at in two moments.
DesignMinute 70 (fault running)Minute 110 (fixed 10 minutes ago)A 2-minute blip
Long window only (1 h)Fires late: needs about 36 bad minutes firstStill fires: 8.1% is above 7.2%Does not fire
Short window only (5 min)Fires within minutesStops: 0.2%Fires: a false page
Both, with andFires once the long window passes the lineStops: the short window is clearDoes not fire

The honest limit of the combination: it is still slow for a mild but real fault. A 12% failure takes about 36 minutes to trip the one-hour window, which the drill in Section 10 shows. That gap is exactly why canary analysis (Section 9) exists.

Long window to prove it is real, short window to prove it is still happening.

How do I turn 99.5% into minutes, and is 99.9% much harder?

Multiply the failure share by the minutes in the window. 0.5% of 43,200 minutes is 216 minutes. 99.9% is five times stricter, and each extra nine costs far more than the one before it.

  1. Failure share. 100% − 99.5% = 0.5% = 0.005.
  2. Window. 30 days × 24 hours × 60 minutes = 43,200 minutes.
  3. Budget. 0.005 × 43,200 = 216 minutes, which is 3.6 hours a month of total failure.
  4. One more nine. 0.001 × 43,200 = 43.2 minutes, and 25,920 failed requests at 600 a minute.

Now price one incident against both. The drill in Section 10 has a bad release with an improvised 25-minute rollback that fails 4,485 requests. Against 99.5% (129,600 allowed) that is 3.5%. Against 99.9% (25,920 allowed) it is 17.3%. The same incident is a shrug or a serious dent, depending on the promise. That is why the SLO is a business decision, not a virtue.

Budget in minutes = (1 − target) × minutes in the window.

Why not promise 100%? Wouldn't that be safest?

No. 100% is impossible to deliver and impossible to keep, because every release, every provider and every cloud region sometimes fails. A budget above zero is what lets you deploy at all.

The budget is also permission. While budget remains, the team ships. When the month's budget is nearly gone, the team stops feature work and fixes reliability. Zero allowed failure would mean never deploying, since every deploy carries some risk.

The honest limit: an SLO measures what you measured. If the SLI counts only HTTP status codes, a model that returns confident wrong answers can meet 99.5% while failing customers. That is why the mean-score panel in Section 7 exists.

An error budget is the amount of risk you are allowed to take.

The formulas behind the budget, the burn rate and the autoscaler — optional depth

Every number in this section comes from six short formulas. Read each aloud in words first.

Budget share: B = 1 − T. Read: "the allowed failure share is one minus the target." For T = 0.995, B = 0.005.

Budget in minutes: M = B × W. Read: "allowed failure share times the window length." For W = 43,200 minutes, M = 0.005 × 43,200 = 216.

Burn rate: r = E ÷ B. Read: "the error ratio you see, divided by the one you are allowed." For E = 0.12, r = 0.12 ÷ 0.005 = 24.

Time to empty: tempty = W ÷ r. For r = 14.4 and W = 720 hours, tempty = 50 hours.

Budget spent in one window: S = r × w ÷ W. Read: "burn rate times the window, over the month." For r = 14.4, w = 1 hour, W = 720 hours: S = 14.4 ÷ 720 = 2%.

Autoscaler: Nnew = ⌈N × u ÷ utarget⌉. Read: "current pods times current utilisation over target utilisation, rounded up." For N = 3, u = 96%, utarget = 60%: ⌈4.8⌉ = 5.

Symbol key: T (the SLO target, for example 0.995); B (the error budget as a share of requests); W (the window, 43,200 minutes or 720 hours); M (the budget in minutes); E (the observed error ratio); r (burn rate); w (a shorter window, for example 1 hour); S (the share of the month's budget spent in that window); N (the number of pods); u (current CPU utilisation as a share of the request); ⌈ ⌉ (round up to the next whole number); × (multiply); ÷ (divide).

Why these and not others: the burn rate is simply the ratio of two rates, so it has no units and one threshold works for any SLO. The same 14.4 means "2% of the month in an hour" whether the target is 99.5% or 99.99%. That is why the alert rule can be copied between services.

Error budget
(1 − SLO) × window. For 99.5% over 30 days: 216 minutes, or 129,600 failed requests at 600 a minute.
Burn rate
Observed error rate ÷ allowed error rate. 1 = on pace, 14.4 = empty in 50 hours.
Fast burn
14.4 on 1 h and 5 min, both. Page.
Medium burn
6 on 6 h and 30 min, both. Page.
Slow leak
1 on a long and a short window. Ticket.
Why two windows
Long proves it is real; short proves it is current, so the page also stops quickly.
Limit
Burn alerts take about 36 minutes to see a 12% fault. Canaries catch it sooner.

09 · Canary and rollbackCanary Releases and the Rehearsed Rollback

A canary release shows a new version to a small slice of users first and checks it against the old version before anyone else sees it. A rollback is the pre-agreed way back. The goal is that a bad release costs a few minutes of budget, not a night.

Priya has an alert that pages at 14.4 times burn, but the last section showed it needs about 36 minutes to notice a 12% failure. That is long. She wants the bad version stopped before most customers meet it, and she wants the way back to be a script she has run before, not an idea she has in her head.

Canary: let 10% find the problem first

Send 10% of traffic to the new version. Compare its error rate and its mean score with the old version's over the same minutes. If it is clearly worse, send it back to 0%. If not, widen to 50%, then 100%. Fig. 12b.13 shows the three steps and the exit.

1 canary: 10%60 of 600 requests/min2 half: 50%300 of 600 requests/min3 everyone: 100%600 of 600 requests/minanalysis:pause 5 minerrors < 1%?noabort: new version back to 0%v1 serves all traffic (minute 5 in the drill)123
Fig. 12b.13 — A canary release. 10% of traffic goes to the new version while an automatic check compares it with the old one; a failed check sends the new version back to 0%.
  1. The canary (marker 1). Only 60 of the 600 requests a minute meet the new version. If it is bad, 90% of customers never see it. The filled part of each bar is the new version's share.
  2. The gate (marker 2). The analysis compares the new version's error rate with the old one's on the same minutes. One rule: fail if the canary's error rate is above 1% and more than three times the baseline's.
  3. The abort path (marker 3). The decision is automatic and takes one minute in the drill. No human had to be awake to decide. That is the point of testing small first.

On Kubernetes, Argo Rollouts does this declaratively. A Rollout replaces the Deployment and lists the steps; an AnalysisTemplate holds the check, written as a Prometheus query. As of October 2026 the current release is 1.10. On ECS the same idea is available through AWS CodeDeploy, or you script it, as the drill in Section 10 does.

Step-by-step: what rollout.yaml does, in plain English
  1. An AnalysisTemplate named churn-canary-check asks Prometheus for the error share of the canary pods only, using the pod-template hash Argo adds to tell old pods from new.
  2. It checks once a minute, five times, and tolerates one bad reading (failureLimit: 1). The check passes when the error share is under 1%.
  3. The Rollout has five replicas and the same container as the Deployment.
  4. Step 1 sends 10% to the new pods. Step 2 runs the analysis. If it fails, Argo aborts and returns to the old version by itself.
  5. Steps 3 to 5 widen to 50%, wait five minutes, then go to 100%.
k8s/rollout.yamlvalidated, not applied
# Argo Rollouts: canary 10% -> 50% -> 100%, with an automatic metric check between steps.
# Needs the Argo Rollouts controller and CRDs installed in the cluster.
apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
  name: churn-canary-check
spec:
  args:
    - name: canary-hash
  metrics:
    - name: error-rate
      interval: 1m
      count: 5
      failureLimit: 1                  # one bad reading is tolerated, two abort the rollout
      successCondition: result[0] < 0.01
      provider:
        prometheus:
          address: http://prometheus.monitoring:9090
          query: |
            sum(rate(http_requests_total{status=~"5..",rollouts_pod_template_hash="{{args.canary-hash}}"}[2m]))
            /
            sum(rate(http_requests_total{rollouts_pod_template_hash="{{args.canary-hash}}"}[2m]))
---
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: churn
spec:
  replicas: 5
  selector:
    matchLabels: {app: churn}
  template:
    metadata:
      labels: {app: churn}
    spec:
      containers:
        - name: churn
          image: 123456789012.dkr.ecr.us-east-1.amazonaws.com/churn-service:GIT_SHA
          ports:
            - containerPort: 8000
          readinessProbe:
            httpGet: {path: /readyz, port: 8000}
  strategy:
    canary:
      steps:
        - setWeight: 10
        - analysis:
            templates:
              - templateName: churn-canary-check
            args:
              - name: canary-hash
                valueFrom:
                  podTemplateHashValue: Latest
        - setWeight: 50
        - pause: {duration: 5m}
        - setWeight: 100
terminalactual output
$ kubeconform -summary (Kubernetes + Argo CRD schemas) k8s/rollout.yaml
Summary: 2 resources found in 1 file - Valid: 2, Invalid: 0, Errors: 0, Skipped: 0

Not run: this Rollout in a cluster. It needs Argo Rollouts installed and a Prometheus at the address shown. The file was checked against both the Kubernetes and the Argo CRD schemas: two objects, both valid.

Fireside chat

Tonight's talk: the canary analysis and the burn-rate alert argue over which one should have caught the bad release.

Canary analysis
Burn-rate alert

I compare the new version with the old one, minute against minute. In the drill I caught a 13.7% error rate against 0.1% in four minutes, with 90% of customers untouched. You needed 35 minutes and every customer was already on the bad version.

The canary looks at a small slice and compares it to the old version, so it reacts very early. It is the early warning shown at marker 2 of Fig. 12b.13.

You only run when somebody deploys. I watch all day. A provider outage at 3 p.m., a data feed that quietly changes, a slow memory leak: none of those ride in on a release, and you are asleep for all of them.

The canary only sees changes you push. The alert sees everything that hurts users, whatever caused it.

Fair. But I cost nothing to be wrong about. If I fail a good release, a human re-runs it. If you page falsely, someone loses sleep, and people start ignoring pages.

A canary false alarm is cheap; a false page is expensive because it wears out the on-call person. This is why the alert needs two windows, as Fig. 12b.12 showed.

And I am the one tied to the contract. You judge a release against the old version; I judge the month against 99.5%. A release can pass you and still spend the budget.

The canary compares two versions to each other. The alert compares the service to the promise made to the customer. Different questions.

We will keep arguing, then, and Priya will keep both of us. We'll revisit this when an incident gets past one of us.

In practice you run both: the canary for releases, the alert for everything else.

Rollback criteria: decide before the incident

A canary decides for one release. For everything else Priya wants a short list of triggers, written down and agreed with Viktor before the first page, so that nobody argues at 2 a.m. The rule is: if any trigger fires within 30 minutes of a deploy, roll back first and debug afterwards.

Rollback triggers for the churn service. Any one, within 30 minutes of a deploy, means roll back.
SignalThresholdSustained forWhy this number
Error ratioabove 3%5 minutesThat is burn 6: 5% of the month's budget in six hours
p99 latencyabove 1.5 seconds10 minutesFive times the healthy p99; customers time out
Mean prediction scoremoves more than 0.10 from the 24-hour baseline10 minutesThe bad version moved it by 0.32 (0.30 to 0.62)
Canary analysisabortedimmediatelyAutomation did not finish the rollback

The rehearsed rollback

The runbook below is the whole procedure on one page. Its value is not the commands, which you could look up, but that Priya has typed them against a staging copy before the night she needs them. Rehearsal is a calendar event, quarterly, with a stopwatch. A rollback you have never run is a rumour.

runbook.mdnot run here: needs AWS / cluster
# Runbook: roll back the churn service

Owner: on-call engineer. Rehearsed: every quarter, on a staging copy. Target: under 5 minutes from decision to healthy.

## When to use this (decide in 60 seconds)
Roll back FIRST, debug later, if ANY of these is true within 30 minutes of a deploy:
- error ratio above 3% for 5 minutes (burn rate above 6)
- p99 latency above 1.5 s for 10 minutes
- mean prediction score moved by more than 0.10 from the 24-hour baseline
- the canary analysis aborted and automation did not finish the rollback

## Rollback (ECS Fargate)
1. Find the last good revision:   aws ecs describe-services --cluster ml-services --services churn-service --query 'services[0].deployments'
2. Point the service back:        aws ecs update-service --cluster ml-services --service churn-service --task-definition churn-service:<LAST_GOOD>
3. Wait for stability:            aws ecs wait services-stable --cluster ml-services --services churn-service
4. Confirm: error ratio and score panels back to baseline; x-model-version header shows the old SHA.

## Rollback (Kubernetes)
1. kubectl rollout undo deployment/churn        (Argo Rollouts: kubectl argo rollouts abort churn)
2. kubectl rollout status deployment/churn --timeout=120s

## After
Post in the incident channel: "Rolled back to <SHA> at <time>." Keep the bad image in the registry (do not delete evidence). Open a postmortem within 24 hours.

Not run here: the AWS and kubectl commands in the runbook, since there is no AWS account or cluster on this machine. Section 10 rehearses the same decision in simulation.

"Rollback is just redeploying the previous commit. Why does it need a runbook?"

— a senior engineer, Friday afternoon

Because "redeploy the previous commit" runs the whole pipeline: tests, a build, a push, a deploy. That can take 15 minutes while the service is failing. The runbook's ECS command skips all of that by pointing the service back at an image that already exists and already passed. In the drill, the difference between an improvised 25-minute rollback and a rehearsed 3-minute one was 1.3 percentage points of the monthly budget.

The honest downside: a quick rollback is only safe if the old version still works with today's data. If the bad release also ran a database migration, rolling back the code alone can break things. Migrations need their own backward-compatible plan.

Canary
Send 10% to the new version, compare it with the old on the same minutes, then widen or abort.
Analysis gate
An automatic check, for example canary error rate under 1%. Failing it aborts the release.
Argo Rollouts
Kubernetes: a Rollout with steps and an AnalysisTemplate. ECS: CodeDeploy or a script.
Rollback trigger
A pre-agreed threshold (error ratio over 3% for 5 min, p99 over 1.5 s, score moved over 0.10).
Roll back first
Within 30 minutes of a deploy, revert before debugging.
Rehearse
Run the rollback on staging every quarter, timed. Keep the old image in the registry.

10 · Incident responseIncident Response: Severity, Roles, a Timeline, and Three Injected Incidents

An incident is any event that spends your error budget faster than planned. Incident response is the agreed way of noticing it, naming it, fixing it, and learning from it, so that people do not invent the process during the emergency.

On day 17, Priya is on call. In one day the service has three incidents. At 02:07 a new model version goes out and starts failing. At 11:40 the language-model provider goes down. At 16:15 a prompt change makes every request cost 40 times more. She has an alert, a canary, a runbook and a breaker. This section is what each of them is for, and how to tell what was worth building.

Severity, roles and a timeline

Three tools turn panic into a procedure. First, severity levels, so everyone shares one word for "how bad". Second, roles, so one person decides and nobody works in silence. Third, a timeline, written while it happens, which becomes the postmortem.

Severity levels for the churn service, tied to the SLO.
LevelWhat it means hereResponse
SEV1Fast-burn page (burn above 14.4), or the service is down. The contract is at risk this week.Page on-call now; open an incident channel; tell the customer-facing lead within 15 minutes
SEV2Medium burn (above 6), or a degraded mode is on (fallback answers, cost cap tripped).Page on-call; fix within hours; no customer message unless it grows
SEV3Slow leak or a failing non-critical part. The budget will be short by month end.Ticket; fix in the working week
Roles in an incident. On a small team one person may hold two, but never all four.
RoleDoesDoes not
Incident commanderDecides, keeps the checklist, asks "what is the mitigation?"Debug the code
Ops leadRuns the rollback, the breaker, the cap: the hands on the keyboardDecide alone to try something risky
Comms leadPosts updates to the channel and the customer, on a timerGuess at causes in public
ScribeWrites the timeline as it happensJoin the debugging

The timeline has five stamps: fault began, detected (a signal fired), declared (someone named a severity), mitigated (users are no longer hurt, even if the cause is unknown), resolved (root cause fixed). The goal of the first hour is only mitigation. Finding the cause can wait. Rolling back or switching to a fallback is mitigation; understanding is not.

big bang, improvisedfixed at minute 60detected 35big bang, rehearsedfixed at minute 38detected 3510% canaryfixed at minute 5detected 40204060minutes after the bad version starts serving (red = customers exposed)123
Fig. 12b.20 — One bad release, three handlings. Red is how long customers were exposed; the dot is when it was detected.
  1. Canary (marker 1). Detected at minute 4 and fixed at minute 5, with only 10% of traffic exposed. The red bar is barely visible, which is the point.
  2. Rehearsed rollback (marker 2). Detected at minute 35 by the burn-rate page and fixed 3 minutes later, because the commands were written and practised.
  3. Improvised rollback (marker 3). The same detection at minute 35, but 25 minutes of working out what to do. The only difference between these two bars is preparation.

The drill: three incidents you can run on your laptop

Priya cannot practise on production. So she writes a simulator: fake traffic, the real alert rule, and each of the three incidents injected at a known minute. This is also the chapter's lab. It is standard library only and finishes in seconds.

Build it in chunks

We build incident_drill.py in five chunks, one for the traffic, one for the alert, and one per incident. Each chunk is a file (drill_c1.py to drill_c5.py) that imports the earlier ones, so each runs on its own. It needs no cloud account and no network: the standard library only.

  1. Chunk 1 — fake traffic, with a dial for each fault

    Everything in this drill needs traffic to react to. We make the smallest honest simulation: one function that serves a minute of requests and returns counts.

    Step-by-step: what chunk 1 does, in plain English
    1. Set the promise (99.5%), the traffic (600 requests a minute) and the normal cost per request.
    2. VERSIONS holds two models: v1 fails 0.2% of requests; v2 fails 12% and returns higher scores.
    3. Minute is a small record: requests, errors, cost, mean score.
    4. serve flips a weighted coin for each request to decide if it fails, and adds a little noise to the score.
    5. The seeded random.Random(7) makes every run identical.
    drill_c1.py — chunk 1runs offline
    # Chunk 1: fake traffic. One call = one minute of requests, with a dial for each fault.
    import random
    from dataclasses import dataclass
    
    SLO = 0.995            # promise: 99.5% of requests succeed
    RPM = 600              # requests per minute (10 per second)
    COST_PER_REQ = 0.0004  # dollars of LLM tokens per normal request
    
    VERSIONS = {"v1": dict(err=0.002, score=0.30),   # the good model
                "v2": dict(err=0.120, score=0.62)}   # the bad release: crashes often, scores shift
    
    
    @dataclass
    class Minute:
        requests: int
        errors: int
        cost: float
        score: float   # average churn score the model returned this minute
    
    
    def serve(rng: random.Random, n: int, err=0.002, cost_x=1.0, score=0.30) -> Minute:
        errors = sum(rng.random() < err for _ in range(n))
        return Minute(n, errors, n * COST_PER_REQ * cost_x, score + rng.gauss(0, 0.01))
    
    
    if __name__ == "__main__":
        rng = random.Random(7)
        for version in ("v1", "v2"):
            m = serve(rng, RPM, **VERSIONS[version])
            print(f"{version}: {m.requests} requests, {m.errors} errors, ${m.cost:.3f}, mean score {m.score:.2f}")

    @dataclass — a class that is just named fields. random.Random(7) — a random generator with a fixed seed.

    Run python drill_c1.py. v1 fails about 3 of 600; v2 about 78 of 600 (12% would be 72, plus noise).

    terminalactual output
    $ python drill_c1.py
    v1: 600 requests, 3 errors, $0.240, mean score 0.30
    v2: 600 requests, 78 errors, $0.240, mean score 0.63
  2. Chunk 2 — turn minutes into burn rates and the two-window alert

    Section 8 made the rule on paper. Here it is code, run against the fake traffic, so you can watch it fire and how long it takes.

    Step-by-step: what chunk 2 does, in plain English
    1. Window keeps the last N minutes and computes the burn rate: error share divided by the allowed 0.5%.
    2. Alerts holds four windows (5, 30, 60, 360 minutes). fired applies the rules: 14.4 on 60 and 5 pages; 6 on 360 and 30 pages; 1 on 360 and 30 opens a ticket.
    3. warmed_up feeds six healthy hours first, as a real alert engine would already have.
    4. budget_spent_pct converts failed requests to a share of the 129,600 allowed.
    5. The demo starts a 12% failure at minute 60 and prints each new alert state.
    drill_c2.py — chunk 2: the lines it addsruns offline
    # Chunk 2: turn minutes into burn rates and the two-window alert rule.
    from collections import deque
    
    from drill_c1 import RPM, SLO, Minute, serve  # chunk 1 (in the whole file these are one file)
    # ... (unchanged lines omitted) ...
    class Window:
        """The last N minutes of traffic."""
    
        def __init__(self, minutes: int):
            self.buf: deque[Minute] = deque(maxlen=minutes)
    
        def burn(self) -> float:
            req = sum(m.requests for m in self.buf)
            err = sum(m.errors for m in self.buf)
            # burn rate 1.0 = spending the budget exactly as fast as the month allows
            return (err / req) / (1 - SLO) if req else 0.0
    # ... (unchanged lines omitted) ...
    class Alerts:
        def __init__(self):
            self.w = {n: Window(n) for n in (5, 30, 60, 360)}
    
        def add(self, m: Minute) -> None:
            for w in self.w.values():
                w.buf.append(m)
    
        def fired(self) -> str | None:
            b = {n: w.burn() for n, w in self.w.items()}
            if b[60] > 14.4 and b[5] > 14.4:     # fast burn: 2% of the month's budget gone in an hour
                return "PAGE"
            if b[360] > 6 and b[30] > 6:         # medium burn: 5% gone in six hours
                return "PAGE"
            if b[360] > 1 and b[30] > 1:         # slow leak: wake nobody, open a ticket
                return "TICKET"
            return None
    
    
    def warmed_up(rng: random.Random) -> Alerts:
        """An alert engine that has already watched six healthy hours, like a real one."""
        alerts = Alerts()
        for _ in range(360):
            alerts.add(serve(rng, RPM))
        return alerts
    
    
    def budget_spent_pct(errors: int) -> float:
        return 100 * errors / (RPM * 43200 * (1 - SLO))   # 43,200 minutes in 30 days
    # ... (unchanged lines omitted) ...
        alerts = warmed_up(rng)
        seen = set()
        for minute in range(130):
            alerts.add(serve(rng, RPM, err=0.12 if minute >= 60 else 0.002))   # failure starts at minute 60
            state = alerts.fired()
            if state and state not in seen:
                seen.add(state)
                print(f"minute {minute}: {state}  burn(5m)={alerts.w[5].burn():.1f}  burn(60m)={alerts.w[60].burn():.1f}")
            if state == "PAGE":
                break

    collections.deque(maxlen=N) — a list that forgets its oldest item, so it is a sliding window.

    Run python drill_c2.py. Expect a ticket at minute 69 and the page at minute 96, 36 minutes after the failure began.

    terminalactual output
    $ python drill_c2.py
    minute 69: TICKET  burn(5m)=24.2  burn(60m)=4.1
    minute 96: PAGE  burn(5m)=23.4  burn(60m)=14.7
  3. Chunk 3 — incident 1: a bad model version, handled three ways

    Now the first incident. The same bad release is shipped three ways, and we measure the budget each one spends.

    Step-by-step: what chunk 3 does, in plain English
    1. canary_verdict compares canary and baseline over the same minutes and rolls back if the canary error rate is above 1% and above three times the baseline, or if the mean score moved more than 0.10.
    2. bad_release serves old and new traffic each minute; share is the new version's portion (1.0 = big bang, 0.1 = canary).
    3. In a canary run, after five minutes of canary data the verdict is taken automatically; a rollback happens rollback_minutes later.
    4. In a big-bang run only the burn-rate page can detect it, and then a human needs rollback_minutes (25 improvised, 3 rehearsed).
    5. It returns errors, detection and fix minutes, and budget spent.
    drill_c3.py — chunk 3: the lines it addsruns offline
    # Chunk 3: incident 1, a bad model version. Compare three ways of handling the same release.
    # ... (unchanged lines omitted) ...
    from drill_c1 import RPM, VERSIONS, Minute, serve
    from drill_c2 import budget_spent_pct, warmed_up
    # ... (unchanged lines omitted) ...
    def canary_verdict(base: list, canary: list) -> tuple[str, str]:
        """The automatic analysis step: compare the new version with the old one, same minutes."""
        b_err = sum(m.errors for m in base) / sum(m.requests for m in base)
        c_err = sum(m.errors for m in canary) / sum(m.requests for m in canary)
        shift = abs(sum(m.score for m in canary) / len(canary) - sum(m.score for m in base) / len(base))
        if c_err > max(0.01, 3 * b_err):
            return "ROLLBACK", f"canary error rate {c_err:.1%} vs baseline {b_err:.1%}"
        if shift > 0.10:
            return "ROLLBACK", f"mean score moved by {shift:.2f}"
        return "PROMOTE", "canary looks like baseline"
    # ... (unchanged lines omitted) ...
    def bad_release(share: float, rollback_minutes: int, seed: int = 1) -> dict:
        """share=1.0 is a big-bang deploy; share=0.1 is a canary. Minute 0 is the deploy."""
        rng, alerts = random.Random(seed), warmed_up(random.Random(seed))
        errors, base_hist, canary_hist, fixed_at, why = 0, [], [], None, ""
        for minute in range(120):
            if fixed_at is not None and minute >= fixed_at:
                share = 0.0                                  # rolled back: everyone is on v1 again
            n_new = round(RPM * share)
            new = serve(rng, n_new, **VERSIONS["v2"]) if n_new else None
            old = serve(rng, RPM - n_new, **VERSIONS["v1"])
            both = [m for m in (new, old) if m]
            errors += sum(m.errors for m in both)
            base_hist.append(old)
            if new:
                canary_hist.append(new)
            total = Minute(sum(m.requests for m in both), sum(m.errors for m in both), 0, old.score)
            alerts.add(total)
            if fixed_at is None and share < 1.0 and len(canary_hist) >= 5:   # canary: analyse automatically
                verdict, why = canary_verdict(base_hist[-5:], canary_hist[-5:])
                if verdict == "ROLLBACK":
                    fixed_at = minute + rollback_minutes
            if fixed_at is None and alerts.fired() == "PAGE":                  # big bang: a human is paged
                fixed_at, why = minute + rollback_minutes, "burn-rate PAGE"
        return {"errors": errors, "detected": fixed_at - rollback_minutes, "fixed": fixed_at,
                "budget_pct": budget_spent_pct(errors), "why": why}
    # ... (unchanged lines omitted) ...
        runs = [("big bang, improvised rollback (25 min)", 1.0, 25),
                ("big bang, rehearsed rollback (3 min)", 1.0, 3),
                ("10% canary, automatic rollback (1 min)", 0.1, 1)]
        for label, share, mins in runs:
            r = bad_release(share, mins)
            print(f"{label:42} detected min {r['detected']:>3}  fixed min {r['fixed']:>3}  "
                  f"errors {r['errors']:>5}  budget {r['budget_pct']:.1f}%  [{r['why']}]")

    A function that takes a parameter (share) that changes the whole behaviour — one simulation, three scenarios.

    Run python drill_c3.py. Three lines, one per scenario.

    terminalactual output
    $ python drill_c3.py
    big bang, improvised rollback (25 min)     detected min  35  fixed min  60  errors  4485  budget 3.5%  [burn-rate PAGE]
    big bang, rehearsed rollback (3 min)       detected min  35  fixed min  38  errors  2897  budget 2.2%  [burn-rate PAGE]
    10% canary, automatic rollback (1 min)     detected min   4  fixed min   5  errors   212  budget 0.2%  [canary error rate 13.7% vs baseline 0.1%]
  4. Chunk 4 — incident 2: the provider is down, with and without a breaker

    The second incident has no deploy to blame. A dependency fails, and the only defence is code that stops calling it.

    Step-by-step: what chunk 4 does, in plain English
    1. The provider is down for minutes 30 to 69. While down, 90% of calls fail.
    2. Breaker.observe records each minute's error rate. Three minutes in a row above 50% opens it.
    3. While open, requests go to a fallback that answers 99.8% of requests and uses no tokens.
    4. Breaker.probe tries once every five minutes; if the provider is up, the breaker closes.
    5. provider_outage runs the same 100 minutes with the breaker on and off.
    drill_c4.py — chunk 4: the lines it addsruns offline
    # Chunk 4: incident 2, the LLM provider goes down for 40 minutes. A circuit breaker plus a fallback.
    # ... (unchanged lines omitted) ...
    from collections import deque
    # ... (unchanged lines omitted) ...
    from drill_c1 import RPM, serve
    from drill_c2 import budget_spent_pct
    
    OUTAGE = range(30, 70)   # the provider is down during these minutes
    # ... (unchanged lines omitted) ...
    class Breaker:
        """Stop calling a dependency that is failing; try one probe every 5 minutes."""
    
        def __init__(self):
            self.recent: deque[float] = deque(maxlen=3)
            self.opened_at: int | None = None
    
        @property
        def open(self) -> bool:
            return self.opened_at is not None
    
        def observe(self, minute: int, error_rate: float) -> None:
            self.recent.append(error_rate)
            if not self.open and len(self.recent) == 3 and min(self.recent) > 0.5:
                self.opened_at = minute            # three bad minutes in a row: open
    
        def probe(self, minute: int, provider_up: bool) -> None:
            if self.open and minute > self.opened_at and (minute - self.opened_at) % 5 == 0 and provider_up:
                self.opened_at, self.recent = None, deque(maxlen=3)   # probe succeeded: close
    # ... (unchanged lines omitted) ...
    def provider_outage(use_breaker: bool, seed: int = 2) -> dict:
        rng, breaker, errors, opened, closed, fallback_requests = random.Random(seed), Breaker(), 0, None, None, 0
        for minute in range(100):
            up = minute not in OUTAGE
            if use_breaker and breaker.open:
                m = serve(rng, RPM, err=0.002, cost_x=0.0, score=0.30)     # fallback: rule-based answer, no tokens
                fallback_requests += m.requests
                breaker.probe(minute, up)
                closed = minute if not breaker.open and closed is None else closed
            else:
                m = serve(rng, RPM, err=0.002 if up else 0.90)             # timeouts and 5xx while it is down
                if use_breaker:
                    breaker.observe(minute, m.errors / m.requests)
                    opened = breaker.opened_at if opened is None else opened
            errors += m.errors
        return {"errors": errors, "opened": opened, "closed": closed, "fallback": fallback_requests,
                "budget_pct": budget_spent_pct(errors)}
    # ... (unchanged lines omitted) ...
        for label, flag in (("no breaker", False), ("breaker + fallback", True)):
            r = provider_outage(flag)
            print(f"{label:20} errors {r['errors']:>6}  budget {r['budget_pct']:.1f}%  "
                  f"breaker opened min {r['opened']}  closed min {r['closed']}  fallback answers {r['fallback']}")

    @property — a method used like an attribute (breaker.open). A deque of length 3 is the "last three minutes".

    Run python drill_c4.py. The breaker opens at minute 32 and closes at minute 72.

    terminalactual output
    $ python drill_c4.py
    no breaker           errors  21695  budget 16.7%  breaker opened min None  closed min None  fallback answers 0
    breaker + fallback   errors   1725  budget 1.3%  breaker opened min 32  closed min 72  fallback answers 24000
  5. Chunk 5 — incident 3: a prompt loop, a cost alert and a hard cap; then the report

    The third incident fails nothing: every request succeeds and the bill climbs. No error alert can see it. Cost has to be its own signal.

    Step-by-step: what chunk 5 does, in plain English
    1. From minute 20 each request costs 40 times more, as if a retry loop re-sent the whole history.
    2. The cost alert fires when this minute's cost is five times the median of the previous 15 minutes. That alert pages a human, who needs 25 minutes to find and revert the prompt.
    3. The cap is automatic: if the last 60 minutes cost more than $25 (normal is $14.40), serve cheap cached answers at 5% of the cost.
    4. summary re-runs all three incidents and prints one row each: signal, mitigation, cost.
    drill_c5.py — chunk 5: the lines it addsruns offline
    # Chunk 5: incident 3, a prompt loop multiplies tokens 40x. A cost alert and a hard budget cap.
    # ... (unchanged lines omitted) ...
    from statistics import median
    # ... (unchanged lines omitted) ...
    LOOP_FROM = 20          # a bad prompt starts re-sending its own history on every retry
    HOURLY_CAP = 25.0       # dollars per rolling hour; normal traffic costs about $14.40
    # ... (unchanged lines omitted) ...
    def prompt_loop(use_cap: bool, human_minutes: int = 25, seed: int = 3) -> dict:
        rng, spent, hist, alert_at, fixed_at, capped = random.Random(seed), 0.0, deque(maxlen=60), None, None, 0
        for minute in range(120):
            looping = minute >= LOOP_FROM and (fixed_at is None or minute < fixed_at)
            degraded = use_cap and sum(hist) > HOURLY_CAP     # cap tripped: cheap cached answers only
            if degraded:
                m = serve(rng, RPM, cost_x=0.05)
                capped += 1
            else:
                m = serve(rng, RPM, cost_x=40.0 if looping else 1.0)
            recent = list(hist)[-15:]
            if alert_at is None and len(recent) == 15 and m.cost > 5 * median(recent):
                alert_at = minute                              # cost per minute is 5x its recent median
                fixed_at = minute + human_minutes              # a human finds and reverts the prompt
            hist.append(m.cost)
            spent += m.cost
        return {"spent": spent, "alert_at": alert_at, "fixed_at": fixed_at, "capped_minutes": capped}
    # ... (unchanged lines omitted) ...
    def summary() -> None:
        from drill_c3 import bad_release
        from drill_c4 import provider_outage
    
        a = bad_release(0.1, 1)
        b = provider_outage(True)
        c = prompt_loop(True)
        rows = [("1 bad model version", a["why"], "automatic rollback", f"{a['budget_pct']:.1f}% of budget"),
                ("2 provider outage", "3 minutes of >50% errors", "breaker opens, fallback answers", f"{b['budget_pct']:.1f}% of budget"),
                ("3 prompt loop", "cost/minute 5x recent median", "hourly cap degrades to cache", f"${c['spent']:.0f} spent")]
        print(f"{'incident':22}{'detection signal':42}{'mitigation':34}cost of the incident")
        for r in rows:
            print(f"{r[0]:22}{r[1]:42}{r[2]:34}{r[3]}")
    # ... (unchanged lines omitted) ...
        for label, cap in (("no cap", False), ("hourly cap", True)):
            r = prompt_loop(cap)
            print(f"{label:11} spent ${r['spent']:>8.2f}  alert min {r['alert_at']}  human fixed min {r['fixed_at']}  capped minutes {r['capped_minutes']}")
        print()
        summary()

    statistics.median — the middle value, which one spike cannot move. A rolling sum is the cap's memory.

    Run python drill_c5.py. The cap run spends $43.66; the no-cap run $262.80.

    terminalactual output
    $ python drill_c5.py
    no cap      spent $  262.80  alert min 20  human fixed min 45  capped minutes 0
    hourly cap  spent $   43.66  alert min 20  human fixed min 45  capped minutes 58
    
    incident              detection signal                          mitigation                        cost of the incident
    1 bad model version   canary error rate 13.7% vs baseline 0.1%  automatic rollback                0.2% of budget
    2 provider outage     3 minutes of >50% errors                  breaker opens, fallback answers   1.3% of budget
    3 prompt loop         cost/minute 5x recent median              hourly cap degrades to cache      $44 spent

The whole program

Chunk 1 is the traffic faker, chunk 2 the windows and alert rule, chunk 3 canary_verdict and bad_release, chunk 4 the Breaker and provider_outage, chunk 5 prompt_loop and the report. Every chunk starts with a # ── chunk n ── comment. Chunks 1 to 5 joined into one file: incident_drill.py.

incident_drill.pyruns offline
# pip install nothing: standard library only. Run: python incident_drill.py
import random
from collections import deque
from dataclasses import dataclass
from statistics import median


# ── chunk 1: fake traffic ──
SLO = 0.995            # promise: 99.5% of requests succeed
RPM = 600              # requests per minute (10 per second)
COST_PER_REQ = 0.0004  # dollars of LLM tokens per normal request

VERSIONS = {"v1": dict(err=0.002, score=0.30),   # the good model
            "v2": dict(err=0.120, score=0.62)}   # the bad release: crashes often, scores shift


@dataclass
class Minute:
    requests: int
    errors: int
    cost: float
    score: float   # average churn score the model returned this minute


def serve(rng: random.Random, n: int, err=0.002, cost_x=1.0, score=0.30) -> Minute:
    errors = sum(rng.random() < err for _ in range(n))
    return Minute(n, errors, n * COST_PER_REQ * cost_x, score + rng.gauss(0, 0.01))


# ── chunk 2: burn rates and alert rule ──
class Window:
    """The last N minutes of traffic."""

    def __init__(self, minutes: int):
        self.buf: deque[Minute] = deque(maxlen=minutes)

    def burn(self) -> float:
        req = sum(m.requests for m in self.buf)
        err = sum(m.errors for m in self.buf)
        # burn rate 1.0 = spending the budget exactly as fast as the month allows
        return (err / req) / (1 - SLO) if req else 0.0


class Alerts:
    def __init__(self):
        self.w = {n: Window(n) for n in (5, 30, 60, 360)}

    def add(self, m: Minute) -> None:
        for w in self.w.values():
            w.buf.append(m)

    def fired(self) -> str | None:
        b = {n: w.burn() for n, w in self.w.items()}
        if b[60] > 14.4 and b[5] > 14.4:     # fast burn: 2% of the month's budget gone in an hour
            return "PAGE"
        if b[360] > 6 and b[30] > 6:         # medium burn: 5% gone in six hours
            return "PAGE"
        if b[360] > 1 and b[30] > 1:         # slow leak: wake nobody, open a ticket
            return "TICKET"
        return None


def warmed_up(rng: random.Random) -> Alerts:
    """An alert engine that has already watched six healthy hours, like a real one."""
    alerts = Alerts()
    for _ in range(360):
        alerts.add(serve(rng, RPM))
    return alerts


def budget_spent_pct(errors: int) -> float:
    return 100 * errors / (RPM * 43200 * (1 - SLO))   # 43,200 minutes in 30 days


# ── chunk 3: incident 1: bad model version ──
def canary_verdict(base: list, canary: list) -> tuple[str, str]:
    """The automatic analysis step: compare the new version with the old one, same minutes."""
    b_err = sum(m.errors for m in base) / sum(m.requests for m in base)
    c_err = sum(m.errors for m in canary) / sum(m.requests for m in canary)
    shift = abs(sum(m.score for m in canary) / len(canary) - sum(m.score for m in base) / len(base))
    if c_err > max(0.01, 3 * b_err):
        return "ROLLBACK", f"canary error rate {c_err:.1%} vs baseline {b_err:.1%}"
    if shift > 0.10:
        return "ROLLBACK", f"mean score moved by {shift:.2f}"
    return "PROMOTE", "canary looks like baseline"


def bad_release(share: float, rollback_minutes: int, seed: int = 1) -> dict:
    """share=1.0 is a big-bang deploy; share=0.1 is a canary. Minute 0 is the deploy."""
    rng, alerts = random.Random(seed), warmed_up(random.Random(seed))
    errors, base_hist, canary_hist, fixed_at, why = 0, [], [], None, ""
    for minute in range(120):
        if fixed_at is not None and minute >= fixed_at:
            share = 0.0                                  # rolled back: everyone is on v1 again
        n_new = round(RPM * share)
        new = serve(rng, n_new, **VERSIONS["v2"]) if n_new else None
        old = serve(rng, RPM - n_new, **VERSIONS["v1"])
        both = [m for m in (new, old) if m]
        errors += sum(m.errors for m in both)
        base_hist.append(old)
        if new:
            canary_hist.append(new)
        total = Minute(sum(m.requests for m in both), sum(m.errors for m in both), 0, old.score)
        alerts.add(total)
        if fixed_at is None and share < 1.0 and len(canary_hist) >= 5:   # canary: analyse automatically
            verdict, why = canary_verdict(base_hist[-5:], canary_hist[-5:])
            if verdict == "ROLLBACK":
                fixed_at = minute + rollback_minutes
        if fixed_at is None and alerts.fired() == "PAGE":                  # big bang: a human is paged
            fixed_at, why = minute + rollback_minutes, "burn-rate PAGE"
    return {"errors": errors, "detected": fixed_at - rollback_minutes, "fixed": fixed_at,
            "budget_pct": budget_spent_pct(errors), "why": why}


# ── chunk 4: incident 2: provider outage ──
OUTAGE = range(30, 70)   # the provider is down during these minutes


class Breaker:
    """Stop calling a dependency that is failing; try one probe every 5 minutes."""

    def __init__(self):
        self.recent: deque[float] = deque(maxlen=3)
        self.opened_at: int | None = None

    @property
    def open(self) -> bool:
        return self.opened_at is not None

    def observe(self, minute: int, error_rate: float) -> None:
        self.recent.append(error_rate)
        if not self.open and len(self.recent) == 3 and min(self.recent) > 0.5:
            self.opened_at = minute            # three bad minutes in a row: open

    def probe(self, minute: int, provider_up: bool) -> None:
        if self.open and minute > self.opened_at and (minute - self.opened_at) % 5 == 0 and provider_up:
            self.opened_at, self.recent = None, deque(maxlen=3)   # probe succeeded: close


def provider_outage(use_breaker: bool, seed: int = 2) -> dict:
    rng, breaker, errors, opened, closed, fallback_requests = random.Random(seed), Breaker(), 0, None, None, 0
    for minute in range(100):
        up = minute not in OUTAGE
        if use_breaker and breaker.open:
            m = serve(rng, RPM, err=0.002, cost_x=0.0, score=0.30)     # fallback: rule-based answer, no tokens
            fallback_requests += m.requests
            breaker.probe(minute, up)
            closed = minute if not breaker.open and closed is None else closed
        else:
            m = serve(rng, RPM, err=0.002 if up else 0.90)             # timeouts and 5xx while it is down
            if use_breaker:
                breaker.observe(minute, m.errors / m.requests)
                opened = breaker.opened_at if opened is None else opened
        errors += m.errors
    return {"errors": errors, "opened": opened, "closed": closed, "fallback": fallback_requests,
            "budget_pct": budget_spent_pct(errors)}


# ── chunk 5: incident 3: prompt loop, and the report ──
LOOP_FROM = 20          # a bad prompt starts re-sending its own history on every retry
HOURLY_CAP = 25.0       # dollars per rolling hour; normal traffic costs about $14.40


def prompt_loop(use_cap: bool, human_minutes: int = 25, seed: int = 3) -> dict:
    rng, spent, hist, alert_at, fixed_at, capped = random.Random(seed), 0.0, deque(maxlen=60), None, None, 0
    for minute in range(120):
        looping = minute >= LOOP_FROM and (fixed_at is None or minute < fixed_at)
        degraded = use_cap and sum(hist) > HOURLY_CAP     # cap tripped: cheap cached answers only
        if degraded:
            m = serve(rng, RPM, cost_x=0.05)
            capped += 1
        else:
            m = serve(rng, RPM, cost_x=40.0 if looping else 1.0)
        recent = list(hist)[-15:]
        if alert_at is None and len(recent) == 15 and m.cost > 5 * median(recent):
            alert_at = minute                              # cost per minute is 5x its recent median
            fixed_at = minute + human_minutes              # a human finds and reverts the prompt
        hist.append(m.cost)
        spent += m.cost
    return {"spent": spent, "alert_at": alert_at, "fixed_at": fixed_at, "capped_minutes": capped}


def summary() -> None:
    a = bad_release(0.1, 1)
    b = provider_outage(True)
    c = prompt_loop(True)
    rows = [("1 bad model version", a["why"], "automatic rollback", f"{a['budget_pct']:.1f}% of budget"),
            ("2 provider outage", "3 minutes of >50% errors", "breaker opens, fallback answers", f"{b['budget_pct']:.1f}% of budget"),
            ("3 prompt loop", "cost/minute 5x recent median", "hourly cap degrades to cache", f"${c['spent']:.0f} spent")]
    print(f"{'incident':22}{'detection signal':42}{'mitigation':34}cost of the incident")
    for r in rows:
        print(f"{r[0]:22}{r[1]:42}{r[2]:34}{r[3]}")


if __name__ == "__main__":
    for label, cap in (("no cap", False), ("hourly cap", True)):
        r = prompt_loop(cap)
        print(f"{label:11} spent ${r['spent']:>8.2f}  alert min {r['alert_at']}  human fixed min {r['fixed_at']}  capped minutes {r['capped_minutes']}")
    print()
    summary()
terminalactual output
$ python incident_drill.py
no cap      spent $  262.80  alert min 20  human fixed min 45  capped minutes 0
hourly cap  spent $   43.66  alert min 20  human fixed min 45  capped minutes 58

incident              detection signal                          mitigation                        cost of the incident
1 bad model version   canary error rate 13.7% vs baseline 0.1%  automatic rollback                0.2% of budget
2 provider outage     3 minutes of >50% errors                  breaker opens, fallback answers   1.3% of budget
3 prompt loop         cost/minute 5x recent median              hourly cap degrades to cache      $44 spent

Read the output. The first two lines compare the prompt-loop incident with and without a cap: $262.80 against $43.66 over two hours. The table is the whole drill in three rows. Each row has a different detection signal. The first is a canary comparing two versions. The second is three bad minutes in a row. The third is a cost jump, because no request failed. No single alert would have caught all three, which is the lesson of this section.

1 Bad model versionBig bang, improvised: 3.5%Big bang, rehearsed: 2.2%10% canary: 0.2%2 Provider outageNo breaker: 16.7%Breaker + fallback: 1.3%3 Prompt loopNo cap: $262.80Hourly cap: $43.66Budget spent = % of the 30-day error budget (incidents 1 and 2); dollars spent in two hours (incident 3).123
Fig. 12b.14 — The three drill incidents, each handled two ways. Preparation cut incident 1 from 3.5% to 0.2% of the budget, incident 2 from 16.7% to 1.3%, and incident 3 from $262.80 to $43.66.
  1. The canary bar (marker 1). Tiny because the fault met only 10% of traffic for 5 minutes before the automatic rollback. The other two bars in panel 1 are the same fault with 100% of traffic exposed.
  2. The breaker bar (marker 2). Without a breaker, 40 minutes of provider outage fail 21,695 requests, a sixth of the monthly budget. With one, only the first 2 minutes fail; the rest are answered by the fallback.
  3. The cap bar (marker 3). The loop makes each request cost 40 times more. The cap stops it after a few minutes by switching to cheap cached answers, so the damage is $44 instead of $263.

Read Fig. 12b.14 one panel at a time. In panel 1 the same bad release costs 3.5% of the month's budget when rolled back by improvisation, 2.2% when rehearsed, and 0.2% when a canary stops it at 10% traffic. Panel 2 shows the breaker's value: 16.7% against 1.3%. Panel 3 shows the cap's value in dollars.

providerbreakererrors, no breakererrors, with breakerdownopen: fallback answers90% of requests fail2 minutes, then fallback03070100minutes12
Fig. 12b.15 — Incident 2 minute by minute. The provider is down from minute 30 to 70. The breaker opens at minute 32 and closes at minute 72, after a probe finds the provider back.
  1. Breaker opens (marker 1). Three one-minute readings in a row with more than half the requests failing: minutes 30, 31, 32. The breaker opens at 32 and sends every request to the fallback, a rule-based answer that costs no tokens.
  2. Breaker closes (marker 2). While open, it tries one probe every five minutes. At minute 72 the probe succeeds (the provider came back at 70), so it closes and normal answers resume. It waits for a probe so it never stampedes a recovering provider.

The outage timeline in Fig. 12b.15 is why the breaker has a probe. It closes only when a real call succeeds, at marker 2. The cost of that caution is two extra minutes of fallback answers. That is cheap compared with hammering a provider that is trying to recover.

The three incidents: how each is detected, mitigated and what it cost in the drill.
IncidentDetection signalMitigationCost in the drillIf it had no defence
1 Bad model versionCanary: error rate 13.7% against 0.1%; or mean score moved 0.32; or burn-rate page after about 35 minutesRollback to the last good image (automatic in the canary)0.2% of budget with canary; 2.2% rehearsed; 3.5% improvisedPage at minute 35; every customer affected until someone acts
2 Provider outageError rate over 50% for three minutes in a row; provider status pageCircuit breaker opens; rule-based fallback answers1.3% of budget16.7% of budget: 21,695 failed requests
3 Prompt loopCost per minute at five times its recent median; no errors at allHourly cost cap switches to cached answers; human reverts the prompt$43.66 in two hours$262.80 in two hours; $9.60 a minute, which is $414,720 a 30-day month

The last figure deserves a sentence. If nobody had acted, $9.60 a minute for 43,200 minutes is $414,720. That is five times the $80K surprise in Module 12's hook, from one prompt change, with every request returning 200.

Learning from it: the blameless postmortem

A postmortem asks what the system allowed to happen, not who erred. If the answer is "Sam forgot", the fix is "tell Sam", which fixes nothing. If the answer is "nothing stops a prompt change from multiplying tokens", the fix is a cost cap, which does. Blame teaches people to hide mistakes; blamelessness teaches them to report them early.

Step-by-step: what postmortem_template.md does, in plain English
  1. A one-line header with date, duration, severity, and the impact in the units that matter: failed requests and the share of the error budget spent.
  2. A detection line: which signal fired and how many minutes after the fault began. This is the number to improve next time.
  3. A timeline table with one row per event, written during the incident by the scribe.
  4. What went well, what went badly, and where you got lucky. Luck is the hidden risk.
  5. Root cause and contributing factors: keep asking why until you reach a system, not a person.
  6. Action items, each with a type (prevent, detect or mitigate), an owner and a date. Without owners and dates they do not happen.
postmortem_template.mdruns offline
# Postmortem: <short title>   (blameless: we describe what the system allowed, not who erred)

- Date / duration / severity:
- Impact: who was affected, how many requests failed, how much error budget was spent (% of 30-day budget)
- Detection: which signal fired, at what minute after the fault began; or how a human found out

## Timeline (UTC, one line per event)
| time | event | who/what |
|---|---|---|

## What went well / what went badly / where we got lucky

## Root cause and contributing factors (ask "why" five times; stop at a system, not a person)

## Action items (each has an owner and a date)
| action | type (prevent / detect / mitigate) | owner | due |
|---|---|---|---|
Boardroom translation

For Viktor: "The Lumen contract is a $10,000 penalty and a 216-minute budget. We made the three likeliest bad nights cost 0.2%, 1.3% and $44 instead of 3.5%, 16.7% and $263, by writing the response down and practising it. The infrastructure runs about $61 a month. A single avoided incident pays for years of it."

SEV1 / SEV2 / SEV3
Page now / page and fix in hours / ticket. Tie them to burn rate.
Roles
Incident commander decides; ops lead acts; comms lead informs; scribe records.
Mitigate first
Stop users being hurt (rollback, fallback, cap) before understanding why.
Circuit breaker
Stop calling a failing dependency after 3 bad minutes; probe every 5; use a fallback meanwhile.
Cost cap
A hard dollar limit per rolling hour that degrades service instead of spending without bound.
Three signals
Canary or score for a bad version; error streak for an outage; cost jump for a loop.
Blameless
Ask what the system allowed. Action items need an owner and a date.

11 · The whole stackThe Whole Stack, and Why

Every tool in this chapter was one choice among several. This table puts the choices side by side with the rule for changing your mind, so you can defend them in a design review or an interview.

The three incidents are over. Viktor asks the question that closes every project: "Why these tools?". Priya answers with a table, because the real answer is different for every team.

The stack, and why

The one question that decides it: how many services will you run, and does anyone already know Kubernetes?

What this chapter uses, what else you could use, and when to switch. As of October 2026.
LayerWe useAlternativesWhy this oneSwitch when
CloudAWSGCP, AzureWidest service range, the one most job specs name, and the registry, roles and compute used here all sit in one account. Bad at: pricing is hard to predict and the console is large.Your data and ML platform already live on GCP (BigQuery, Vertex), or a contract requires Azure OpenAI; or a committed-spend discount elsewhere beats 20%.
ComputeECS on FargateEKS, Lambda container image, SageMaker endpoints, App Runner (closed to new customers since April 30, 2026), ECS Express ModeNo servers or control plane to run; about $36 a month for two tasks. Bad at: no GPUs, and moving off it later means rewriting the deployment.More than about 10 services, or any GPU model: EKS. Fewer than about 1 request a second on average with long idle gaps: Lambda. A one-click simple service: Express Mode.
Infrastructure as codeTerraform 1.17OpenTofu, AWS CDK, Pulumi, CloudFormationLargest community and module library; reviewed as plain text. Bad at: state files must be stored and locked, and its licence is not open source.You need an open-source licence: OpenTofu. The team writes TypeScript and is AWS-only: CDK. You want general-purpose languages across clouds: Pulumi.
CI/CDGitHub ActionsGitLab CI, Jenkins, AWS CodePipelineLives next to the code, and OIDC to AWS needs no stored key. Bad at: hosted minutes are billed, and third-party actions are a supply-chain risk.The code is on GitLab: GitLab CI. You already run 100 or more Jenkins pipelines: Jenkins. Policy forbids any external identity provider in the account: CodePipeline.
Progressive deliveryArgo Rollouts 1.10 (Kubernetes); a scripted canary for ECSFlagger, AWS CodeDeployDeclarative steps plus a Prometheus-based check. Bad at: Kubernetes only, so the ECS path here is a script.ECS only and no Kubernetes: CodeDeploy canary. You already use Flux or a service mesh: Flagger.
Metrics and dashboardsPrometheus + GrafanaCloudWatch, DatadogOpen, portable, and the burn-rate rules in Section 8 are plain PromQL. Bad at: someone must run and store it.Fewer than about 5 services and nobody to run Prometheus: CloudWatch or Amazon Managed Prometheus. The company already pays for Datadog and wants logs and APM in one place: Datadog.
LLM tracingLangfuse (Python SDK 4)LangSmithOpen source and self-hostable, so prompts stay in your account. Bad at: you run the database if self-hosting.Data residency is not a concern and you are all-in on LangChain or LangGraph: LangSmith.
Container registryECRGHCR (GitHub Container Registry)Same account and IAM as the runtime; immutable tags and scan on push. Bad at: AWS-only access.You deploy to more than one cloud, or want images next to the code on GitHub: GHCR.

For one small model service and one small team, Fargate, Terraform, GitHub Actions and Prometheus is the boring default; every row has a clear signal for when to leave it.

12 · The labDefine the SLOs, Run the Drill, Rehearse the Rollback

LAB 12b — Operate a service through three incidents

Mission: take the chapter's churn service and the drill, and turn them into a portfolio piece that shows you can run a model in production: an SLO document, a rollback procedure you have timed, and a drill report. Everything below runs on your laptop; the AWS and Kubernetes parts are written and validated, not applied.

  • Write SLO.md for the churn service: two SLIs (success ratio and p99 latency), targets, the monthly budget in minutes and in requests, and the three burn-rate alerts with their long and short windows.
  • Write rollback criteria as a table of signal, threshold and duration. Include one criterion based on the model's own output (the mean score), not only status codes.
  • Run python incident_drill.py and capture the output. Then change one number (the canary share to 0.05, or the cap to $20 an hour) and report how the budget spent changes.
  • Add a fourth incident to the drill: a bad deploy that only raises latency, not errors. Write the detector (p99 over 1.5 s for 10 minutes) and the mitigation. Show it fires.
  • terraform validate passes on the provided files; kubeconform passes on the manifests; pytest -q passes.
  • Rehearse the runbook on paper with a timer: read each step aloud and write down how long each command would take. Report the total against a 5-minute target.
  • README documents: the budget table, three failure modes you found while changing the drill, and one thing the simulation cannot tell you that production would.

Stretch goal: deploy the Dockerfile to a free-tier AWS account with the Terraform provided, set the budget alert first, run one real canary, and write the postmortem for anything that goes wrong. Destroy it the same day.

13 · Interview radarHow This Shows Up in Interviews

Interview radar

Production questions are graded on one thing: do you talk about failure before it happens? Strong answers name a number, a signal, and the action that follows.

"Walk me through how you would deploy a containerised ML model on AWS."

The real test Whether you describe a pipeline with a rollback, or just a deploy.

Strong answer I build an image in CI and tag it with the git commit. I push it to ECR using an OIDC role, so no access key is stored. I run it on ECS Fargate behind a load balancer whose health check is the readiness endpoint, with two tasks minimum. The ECS circuit breaker rolls back automatically if new tasks fail. A burn-rate alert tells me if it is healthy, and the previous image stays in the registry. A small CPU model costs roughly $60 a month.

Land it The deploy is the easy part; the answer is the rollback and the signal that triggers it.

"What is an error budget, and how do you use it?"

Strong answer It is the failure the SLO allows. For 99.5% over 30 days that is 0.5% of 43,200 minutes, which is 216 minutes. It turns reliability into something the team can spend. While budget remains, we ship. When it is nearly gone, we freeze features and fix reliability. I also alert on how fast it burns: a burn rate of 14.4 means the whole month would be gone in 50 hours.

Land it An error budget is permission to take risk, with a number attached.

"Your model service returns 200 on every request, but customers say the predictions are wrong. What do you do?"

The real test Do you know that "up" is not "right" for ML?

Strong answer I check the model's own signals first, not the status codes. I compare the mean prediction score and its distribution, per version, against the 24-hour baseline. If a recent deploy moved it, I roll back to the last good version first and investigate afterwards. Then I look at input drift and at the labelled eval set. To catch this next time I would add a score-shift rollback trigger and run new versions as a canary.

Land it Mitigate by rolling back, then diagnose from the model's output, because the status codes never moved.

"When would you choose Kubernetes over ECS Fargate, or Lambda over both?"

The real test Vendor-agnostic judgment, with conditions instead of preferences.

Strong answer I would choose by conditions:

  • Fargate for a small team with a few CPU services, since it has no nodes to manage.
  • Kubernetes when there are many services (roughly ten or more), GPUs, or a need to run the same setup on several clouds. The control plane alone is about $73 a month.
  • Lambda for bursty or rare traffic where scale-to-zero matters, provided cold starts do not break the p99.

I would not start a new service on App Runner; AWS closed it to new customers in April 2026.

Land it Pick the simplest platform whose limit you have not reached.

"Explain multiwindow burn-rate alerting. Why two windows?"

Strong answer The burn rate is the observed error ratio divided by the allowed one. I page when a long window and a short window both exceed a threshold. For 99.5%, that is 14.4 over one hour and five minutes. The long window proves it is real, so a blip does not page. The short window proves it is still happening, so the page stops soon after the fix. With only the long window, an hour-old fault keeps paging.

Land it Long window for confidence, short window for currency.

"How do you let a CI pipeline deploy to AWS safely?"

Strong answer I avoid stored access keys. GitHub issues each job a signed OIDC token, and an IAM role trusts that token only for one repository and branch. The job swaps the token for credentials that last about an hour. The role can push to one registry and update one service, nothing else. If a log leaks the credentials, they expire before anyone can use them.

Land it Short-lived, narrowly scoped, and tied to the repository identity.

"Describe how you would run an incident for a production ML API."

The real test Roles, mitigation before diagnosis, and learning afterwards.

Strong answer I name an incident commander, an ops lead, a comms lead and a scribe. I assign a severity from the burn rate. The first goal is mitigation: roll back, switch to a fallback, or cap spending, whichever stops user harm fastest, before finding the cause. The scribe keeps a timeline. Afterwards a blameless postmortem asks what the system allowed, and each action item gets an owner and a date.

Land it Stop the harm first, understand it second, and fix the system, not the person.

There are no dumb questions

If the canary catches bad releases, why keep the burn-rate alert?
The canary only sees changes you ship. The alert sees everything that hurts users, including a provider outage or a data change. The drill used both because each caught something the other could not.
Is a fallback answer not just a worse product?
Yes, and that is the trade. A rule-based answer for 40 minutes is better than errors for 40 minutes. The breaker and fallback spent 1.3% of the budget in the drill against 16.7% without them.
Do I really need Terraform for one service?
You can click through the console once. You cannot review it, repeat it, or see what changed when it breaks. For one service, ECS Express Mode is a fair shortcut. The moment you need a second environment, text wins.
Why simulate the incidents instead of testing in production?
A simulation is repeatable and costs nothing. It cannot tell you whether the real provider recovers in 40 minutes. Do both: simulate to design the response, then run game days on staging to check the real commands.

14 · RecapWhat You Can Do Now

  • You can draw the path from laptop to cloud and name what moves at each stage: the image, the registry, the runtime
  • You can instrument a model service with counters, histograms, probes, JSON logs and a version label, and explain why a label must never hold an id
  • You can choose a compute platform on AWS with conditions, and price a Fargate service by hand
  • You can read and write Terraform for a Fargate service with roles, a load balancer and automatic rollback, and validate it without an account
  • You can build a CI/CD pipeline that tests, builds, pushes and deploys using OIDC instead of stored keys
  • You can read Kubernetes manifests: Deployment, Service, probes, requests, HPA, a GPU request, and a canary Rollout
  • You can turn a 99.5% promise into 216 minutes, set three burn-rate alerts, and explain why they use two windows
  • You can run and defend three incident responses: canary rollback, circuit-breaker fallback and a cost cap, with numbers
🧠 Flex your memory

From this chapter: from memory, sketch the five pipeline stages in Fig. 12b.7 and say which one turns the job red when new tasks never become healthy. Then write the fast-burn alert expression and say what number 14.4 × 0.005 is in percent.

From an earlier module: in Module 07 you built an eval gate. Say where in this chapter's pipeline it sits, what it catches that pytest cannot, and what it still cannot catch that the canary and the score panel can.

Reveal the answers

Stages: test, build, push, deploy, wait for stability. The wait step turns the job red. 14.4 × 0.005 = 0.072, or 7.2% errors. The eval gate runs on the pull request, before merge: it catches quality regressions in answers that unit tests do not. It cannot see live traffic, so a model that passes the eval set but behaves differently on real inputs is caught only by the canary or the mean-score panel.