What You Will Add
The API from the last lesson answers predictions. A cluster that runs it
needs answers to three other questions, repeatedly and automatically: is the
process alive, is it ready to take requests, and what has it been doing?
In this lesson you add three small endpoints that answer them: /healthz
for liveness, /readyz for readiness and /metrics for a running count and
latency of predictions, plus a log line that says when the model loaded and
how long it took. These endpoints change nothing for callers of /predict,
and they are what the Kubernetes probes, autoscaling and observation lessons
rely on. The file you finish here is the one the Dockerfile lesson packages.
Two Questions That Must Not Share an Answer
A model service fails in two different ways, and a platform reacts to each differently.
- The process may be broken: stuck in a deadlock, out of memory, unable to respond at all. The right reaction is to restart it. The check for this is called liveness.
- The process may be not ready: alive and responsive, but still loading the model, or temporarily unable to serve because something it needs is missing. The right reaction is to stop sending it requests until it is ready again, without restarting it, because a restart would only start the loading over. The check for this is called readiness.

Read the two columns as two different questions asked of the same process. Liveness is deliberately shallow: it says 200 whenever the server can answer at all, because the only thing a failure triggers is a restart, and a restart should be rare. Readiness is specific: it says 200 only when the model is loaded, because a failure merely holds back traffic, which is cheap and reversible. The timeline shows why they must differ: during model loading the process is alive (do not restart it) but not ready (do not send it requests). If one endpoint answered both questions, a slow model load would either be invisible or would cause a restart loop, and the Kubernetes probes lesson shows both outcomes happening.
Metrics and Logs
A log line records an event with its time; a metric is a number you can
read at any moment. The API gets one of each. At startup it logs the model
path, version and load time, which is the first thing to read when a
container is slow to become ready. For metrics it uses prometheus_client,
the Python library for the text format that Prometheus and many other
monitoring systems scrape: a Counter that only goes up, labelled by
outcome, and a Histogram that counts observations into latency buckets.
/metrics renders them as plain text. Nothing scrapes it yet; the
observation lesson reads it by hand and explains what a monitoring stack adds.
The Code
This is the complete app/main.py after this lesson. It replaces the first
version; the additions are the logging setup, the two metric objects, the
load-time log line, /healthz, /readyz, the metric calls inside
predict() and /metrics. The
Dockerfile lesson packages this file unchanged.
"""Inference API for the practice model.
Built up in the lessons build-the-inference-api and health-readiness-and-metrics.
The Dockerfile lesson packages this file unchanged.
"""
import logging
import os
import time
from contextlib import asynccontextmanager
import joblib
import numpy as np
from fastapi import FastAPI, HTTPException, Response
from prometheus_client import CONTENT_TYPE_LATEST, Counter, Histogram, generate_latest
from pydantic import BaseModel, Field
MODEL_PATH = os.environ.get("MODEL_PATH", "models/model.joblib")
STARTUP_DELAY_S = float(os.environ.get("STARTUP_DELAY_S", "0")) # practice only: simulate a slow load
logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"), format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("aim-api")
PREDICTIONS = Counter("aim_predictions_total", "Prediction requests", ["outcome"])
LATENCY = Histogram("aim_prediction_seconds", "Prediction latency in seconds")
state: dict = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
started = time.perf_counter()
if STARTUP_DELAY_S:
time.sleep(STARTUP_DELAY_S)
bundle = joblib.load(MODEL_PATH)
state.update(model=bundle["pipeline"], features=bundle["features"], version=bundle["version"])
log.info("model loaded path=%s version=%s in %.2fs", MODEL_PATH, state["version"], time.perf_counter() - started)
yield
state.clear()
app = FastAPI(title="aim-api", lifespan=lifespan)
class Reading(BaseModel):
temperature_c: float = Field(..., ge=-50, le=200)
vibration_mm_s: float = Field(..., ge=0)
pressure_kpa: float = Field(..., ge=0)
runtime_hours: float = Field(..., ge=0)
load_percent: float = Field(..., ge=0, le=100)
ambient_c: float = Field(..., ge=-50, le=80)
class Prediction(BaseModel):
needs_service: bool
probability: float
model_version: str
@app.get("/healthz")
def healthz():
return {"status": "ok"}
@app.get("/readyz")
def readyz():
if "model" not in state:
raise HTTPException(status_code=503, detail="model not loaded")
return {"status": "ready", "model_version": state["version"]}
@app.post("/predict", response_model=Prediction)
def predict(reading: Reading):
if "model" not in state:
PREDICTIONS.labels("not_ready").inc()
raise HTTPException(status_code=503, detail="model not loaded")
with LATENCY.time():
row = np.array([[getattr(reading, name) for name in state["features"]]], dtype=float)
probability = float(state["model"].predict_proba(row)[0, 1])
PREDICTIONS.labels("ok").inc()
return Prediction(needs_service=probability >= 0.5, probability=round(probability, 4), model_version=state["version"])
@app.get("/metrics")
def metrics():
return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)
Logging the load
logging.basicConfig sets the level from LOG_LEVEL (default INFO) and a
format with a timestamp. The one line that matters is in lifespan: after
the model loads, log.info("model loaded path=%s version=%s in %.2fs", ...)
records where the model came from, which version it is and how long the load
took. In the Dockerfile lesson this line will read about 6.5 seconds inside a
cold container, against a fraction of a second here; that single number is
what the probes lesson sizes its startup probe from. The log never prints request
bodies or secrets: a model API's inputs can be sensitive and logs are widely
readable.
STARTUP_DELAY_S is a practice-only switch. It does nothing unless set, and
the probes lesson sets it to simulate a model that takes 25 seconds to load,
so that you can watch the difference between the two probe kinds without a
multi-gigabyte model.
/healthz
It returns {"status": "ok"} and nothing else. It does not check the model,
the disk or anything downstream, on purpose: if the process can run this
function, the process is alive, and that is the only question liveness
should answer. Every check you add here is a new way to be restarted.
/readyz
It returns 200 with the model version when the model is in state, and
raises HTTPException(503, "model not loaded") otherwise. With the lifespan
pattern the server does not accept connections until the model is loaded, so
in this version state is normally populated by the time anyone can call
/readyz; the 503 path matters when readiness depends on more than the
model, as in this lesson's independent task, and when the probes lesson
holds the server back with a simulated slow load. The
version in the body is a convenience you will use constantly: one curl
tells you which model a Pod serves.
The metric calls
PREDICTIONS = Counter("aim_predictions_total", ..., ["outcome"]) declares a
counter with one label. PREDICTIONS.labels("ok").inc() adds one to the
ok series after a successful prediction; the not_ready series counts
requests refused with 503. Labels split one metric into a few series you can
compare; keep their values to a small fixed set, never a user ID or an input
value, or the number of series grows without bound.
LATENCY = Histogram("aim_prediction_seconds", ...) and with LATENCY.time(): measure how long the row building and predict_proba take.
A histogram records each observation into cumulative buckets (the default
bounds run from 5 milliseconds to 10 seconds), plus a running sum and count,
which is what lets a monitoring system compute percentiles later.
/metrics
generate_latest() renders every registered metric in the Prometheus text
format and CONTENT_TYPE_LATEST is the matching content type. The endpoint
is plain GET, so you can read it with curl and so can a scraper. Because
the counters live in this process, each uvicorn worker would have its own
numbers; that is one reason the course runs one process per container and
lets the cluster replicate, which the scaling lesson returns to.
Exercise: Add the Endpoints
Goal: replace app/main.py with the version above, prove that the two
health questions get different answers, and read the metrics after a few
predictions.
Starting state: the project folder with the first app/main.py running
or stoppable, the virtual environment and models/model.joblib. Port 18000
free.
-
Replace
app/main.py. The block writes the whole file; copy it whole:cd ~/ai-deploy-practice/aim-api cat > app/main.py <<'EOF' """Inference API for the practice model. Built up in the lessons build-the-inference-api and health-readiness-and-metrics. The Dockerfile lesson packages this file unchanged. """ import logging import os import time from contextlib import asynccontextmanager import joblib import numpy as np from fastapi import FastAPI, HTTPException, Response from prometheus_client import CONTENT_TYPE_LATEST, Counter, Histogram, generate_latest from pydantic import BaseModel, Field MODEL_PATH = os.environ.get("MODEL_PATH", "models/model.joblib") STARTUP_DELAY_S = float(os.environ.get("STARTUP_DELAY_S", "0")) # practice only: simulate a slow load logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"), format="%(asctime)s %(levelname)s %(message)s") log = logging.getLogger("aim-api") PREDICTIONS = Counter("aim_predictions_total", "Prediction requests", ["outcome"]) LATENCY = Histogram("aim_prediction_seconds", "Prediction latency in seconds") state: dict = {} @asynccontextmanager async def lifespan(app: FastAPI): started = time.perf_counter() if STARTUP_DELAY_S: time.sleep(STARTUP_DELAY_S) bundle = joblib.load(MODEL_PATH) state.update(model=bundle["pipeline"], features=bundle["features"], version=bundle["version"]) log.info("model loaded path=%s version=%s in %.2fs", MODEL_PATH, state["version"], time.perf_counter() - started) yield state.clear() app = FastAPI(title="aim-api", lifespan=lifespan) class Reading(BaseModel): temperature_c: float = Field(..., ge=-50, le=200) vibration_mm_s: float = Field(..., ge=0) pressure_kpa: float = Field(..., ge=0) runtime_hours: float = Field(..., ge=0) load_percent: float = Field(..., ge=0, le=100) ambient_c: float = Field(..., ge=-50, le=80) class Prediction(BaseModel): needs_service: bool probability: float model_version: str @app.get("/healthz") def healthz(): return {"status": "ok"} @app.get("/readyz") def readyz(): if "model" not in state: raise HTTPException(status_code=503, detail="model not loaded") return {"status": "ready", "model_version": state["version"]} @app.post("/predict", response_model=Prediction) def predict(reading: Reading): if "model" not in state: PREDICTIONS.labels("not_ready").inc() raise HTTPException(status_code=503, detail="model not loaded") with LATENCY.time(): row = np.array([[getattr(reading, name) for name in state["features"]]], dtype=float) probability = float(state["model"].predict_proba(row)[0, 1]) PREDICTIONS.labels("ok").inc() return Prediction(needs_service=probability >= 0.5, probability=round(probability, 4), model_version=state["version"]) @app.get("/metrics") def metrics(): return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST) EOF -
Start with a wrong model path and watch what happens:
MODEL_PATH=models/missing.joblib .venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 18000Illustrative output, shortened:
INFO: Waiting for application startup. ERROR: Traceback (most recent call last): ... FileNotFoundError: [Errno 2] No such file or directory: 'models/missing.joblib' ERROR: Application startup failed. Exiting.The process exits with an error instead of serving a broken API. That is the right behaviour: a wrong path is a configuration mistake, and a loud exit is what the diagnosis lesson's
CrashLoopBackOffdrill will show you from the cluster's side. -
Start normally and read the log line:
.venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 18000INFO: Waiting for application startup. 2026-10-21 18:52:31,004 INFO model loaded path=models/model.joblib version=1.0.0 in 0.02s INFO: Application startup complete.Note the load time; you will compare it with the container's later.
-
In a second terminal, ask the two questions and make a few predictions:
curl -sS http://127.0.0.1:18000/healthz; echo curl -sS http://127.0.0.1:18000/readyz; echo for i in 1 2 3; do curl -sS -o /dev/null -X POST http://127.0.0.1:18000/predict -H 'content-type: application/json' \ -d '{"temperature_c":71.5,"vibration_mm_s":4.2,"pressure_kpa":310,"runtime_hours":12000,"load_percent":82,"ambient_c":24}' done curl -sS http://127.0.0.1:18000/metrics | grep '^aim_'Expected:
{"status":"ok"},{"status":"ready","model_version":"1.0.0"}, and then the metric lines. Illustrative:aim_predictions_total{outcome="ok"} 3.0 aim_predictions_created{outcome="ok"} 1.7925e+09 aim_prediction_seconds_bucket{le="0.005"} 3.0 aim_prediction_seconds_bucket{le="0.01"} 3.0 ... aim_prediction_seconds_bucket{le="+Inf"} 3.0 aim_prediction_seconds_count 3.0 aim_prediction_seconds_sum 0.0041aim_predictions_total{outcome="ok"} 3.0is the counter after three predictions. The_bucketlines are cumulative: all three predictions took less than 5 ms here, so every bucket already holds 3._countand_sumgive the average when divided. The_createdline is a timestamp the library adds; ignore it. The full output also includes Python process metrics the library exposes by default. -
Stop the server with Ctrl+C.
Success: the wrong path exits with FileNotFoundError; the normal start
logs the load time; /healthz and /readyz answer 200 with the expected
bodies; after three predictions /metrics shows the counter at 3 and the
histogram count at 3.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
ModuleNotFoundError: No module named 'prometheus_client' | The package is missing from the venv | .venv/bin/pip install -r requirements.txt; the pin is in the file from the model lesson |
/metrics lists no aim_ lines | No prediction has been made yet, or grep filtered them | Make a prediction first; counters appear on first use |
The counter shows a fraction such as 3.0 | Normal: the text format prints floats | Nothing to fix |
/readyz returns 503 while /healthz returns 200 | The model did not load but the server is up | Read the startup log; with this version the server exits on a load error, so check which main.py is running |
| The log line is missing | LOG_LEVEL set above INFO, or an older main.py | unset LOG_LEVEL; compare the file with the block above |
| Two servers' metrics look different | Each process has its own counters | Expected; the scaling lesson explains why the course runs one process per container |
Independent task: make /readyz depend on something that can change
after startup. Add a module-level flag DRAINING = False, an endpoint POST /drain that sets it to True, and make /readyz return 503 while it is
set, without touching /healthz. Predict, before testing, what a platform
that probes both endpoints would do to this process after you call /drain.
Then remove your changes, because the Dockerfile lesson packages the file as
written above.
Cleanup: the server is stopped; keep the file as written. If you tried the independent task, restore the file by running step 1 again.
Check Your Understanding
- Why does
/healthznot check whether the model is loaded? - A colleague proposes one endpoint,
/status, returning 200 only when the model is loaded, and using it for both liveness and readiness. What happens during a 40-second model load? - Why are the metric labels limited to
okandnot_readyrather than, say, the predicted class or the caller's ID? - What does
aim_prediction_seconds_bucket{le="0.05"} 3.0mean?
Answer and Reasoning
Independent task
After /drain, a platform probing both endpoints would stop sending the
process requests (readiness 503) but would not restart it (liveness still
200). That is precisely the behaviour you want for taking an instance out of
service gracefully, and it is impossible when one endpoint answers both
questions. The Kubernetes lessons do this with probes rather than code.
Understanding check
- Because the only reaction to a liveness failure is a restart, and a restart does not fix a missing or slow model; it repeats the load. Liveness should fail only when restarting would help: a stuck or dead process.
- The platform would see liveness failures for 40 seconds and restart the process, which starts the load again, which fails liveness again: a restart loop that never serves. Readiness alone would simply hold traffic for 40 seconds.
- Each label value creates a separate series. A small fixed set stays cheap and comparable; a value that varies per request (an ID, a probability) would create unbounded series and defeat the purpose of a counter.
- Three observations so far took 50 milliseconds or less. Buckets are cumulative, so this line counts everything at or under its bound; the difference between neighbouring buckets is how many fell between them.