Many models reach users through a small Python web service: FastAPI for the HTTP layer, Pydantic for request and response schemas, and a model loaded into memory. Serving well means loading the model once, keeping slow inference off the event loop, batching requests, sizing workers to memory, separating liveness from readiness, and measuring latency per stage. This lesson serves a text classifier to production traffic, and shows the two mistakes that make a fast model slow: loading it per request, and blocking the event loop with inference.
Difficulty: Advanced · Know this first: Lesson 64, Lesson 254
This bar adds up milliseconds for one request at peak. It is a worked example, not a measurement. The loading and async hops decide whether the service is as fast as its model.
Set the inference time and the number of concurrent requests. With a blocked event loop, requests wait for each other one by one; with a thread pool, they share the workers.
Blocked: every request, and the health check, waits for every prediction before it
Three questions. No score is saved anywhere — this is just you against the material.
Serving models grows in four levels: a working endpoint, a correct service, a fast service, and serving at scale.
At the basic level a model answers HTTP requests.
@app.post, uvicorn app:app./docs for the generated API page.curl -X POST -H "Content-Type: application/json" -d '{"text": "..."}'.Where it breaks: loading the model inside the handler, which makes every request take seconds.
Try it: Basic
Requests take 3 seconds though the model predicts in 30 ms. What is the first thing to check?
Now do it: Add timing logs around loading and prediction in one service.
At the intermediate level the service behaves under load.
lifespan loading; plain def or run_in_threadpool for inference.Try it: Intermediate
Pods are restarted under load although they are healthy, just busy. What is the likely fix?
Now do it: Load-test a service while polling /livez every 100 ms.
At the advanced level throughput and latency are engineered.
Try it: Advanced
p99 latency is high but model time is steady at 30 ms. Where is the time going?
Now do it: Add a histogram for time between arrival and the start of inference.
At the master level serving is a platform.
Trade-off: a hand-written FastAPI service is simple and fully under your control; a model server brings batching, multi-model hosting, and metrics, and another system to learn and run.
Try it: Master
When is moving from FastAPI to a dedicated model server worth it?
Now do it: List what your service does that Triton or KServe would give you for free.
A complete service with loading at start-up, inference in a thread pool, separate health checks, and timing. The "model" is a tiny scorer, so it runs anywhere; replace load_model with a real one. Install with pip install fastapi uvicorn.
import time
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.concurrency import run_in_threadpool
from pydantic import BaseModel, Field
MODEL_VERSION = "ticket-clf-2026.11.1"
def load_model():
time.sleep(2) # stands in for loading weights
words = {"refund": "billing", "invoice": "billing", "password": "login", "crash": "bug"}
def predict(texts):
time.sleep(0.03) # stands in for 30 ms of CPU inference
out = []
for t in texts:
hits = [label for w, label in words.items() if w in t.lower()]
out.append((hits[0] if hits else "other", 0.9 if hits else 0.5))
return out
return predict
@asynccontextmanager
async def lifespan(app):
app.state.model = load_model() # once, at start-up
yield
app = FastAPI(lifespan=lifespan)
class Req(BaseModel):
text: str = Field(min_length=1, max_length=20_000)
class Resp(BaseModel):
label: str
score: float
model_version: str
model_ms: float
@app.get("/livez")
def livez():
return {"ok": True} # trivial: never blocks
@app.get("/readyz")
def readyz():
if not hasattr(app.state, "model"):
raise HTTPException(503, "loading")
return {"ready": True}
@app.post("/classify", response_model=Resp)
async def classify(req: Req):
t = time.perf_counter()
(label, score), = await run_in_threadpool(app.state.model, [req.text]) # off the event loop
return Resp(label=label, score=score, model_version=MODEL_VERSION, model_ms=round((time.perf_counter() - t) * 1000, 1))
# run: uvicorn serve:app --port 8000
# try: curl -s -X POST localhost:8000/classify -H "Content-Type: application/json" -d '{"text": "Please refund my invoice"}'
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A product launch turned a healthy model service into a restart loop.
A load test with concurrent requests and health polling runs in CI, inference is micro-batched in a thread pool, readiness gates traffic on model loading, and dashboards separate queue time from model time.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A virtual environment: python3 -m venv ~/py-lab && . ~/py-lab/bin/activate. Then pip install fastapi uvicorn for the commands.
Type each one, read what it prints, and compare it with the note above it.
A tiny service with a blocking and a non-blocking endpoint.
cat > /tmp/svc.py <<'EOF'
import time
from fastapi import FastAPI
app = FastAPI()
@app.get("/livez")
def livez():
return {"ok": True}
@app.get("/blocking")
async def blocking():
time.sleep(0.5) # CPU-style work on the event loop
return {"done": True}
@app.get("/pooled")
def pooled():
time.sleep(0.5) # plain def: FastAPI runs it in a thread pool
return {"done": True}
EOF
cd /tmp && (uvicorn svc:app --port 8077 >/dev/null 2>&1 &) && sleep 2 && cd - >/dev/nullTen concurrent calls to the blocking endpoint, while timing the health check.
for i in $(seq 10); do curl -s -o /dev/null localhost:8077/blocking & done; sleep 0.1; curl -s -o /dev/null -w "livez took %{time_total}s\n" localhost:8077/livez; waitThe same with the pooled endpoint: the health check stays fast; then stop the server.
for i in $(seq 10); do curl -s -o /dev/null localhost:8077/pooled & done; sleep 0.1; curl -s -o /dev/null -w "livez took %{time_total}s\n" localhost:8077/livez; wait; pkill -f "uvicorn svc:app"; rm -f /tmp/svc.pyevent_loop_sim.pyThis program models an event loop with a virtual clock: requests arrive together with a health check, and the inference either runs on the loop (blocking it) or in a pool of worker threads. The Linux commands above show the same thing with a real server. Save it as event_loop_sim.py, then run it.
# event_loop_sim.py
import math
def simulate(mode, requests, work_ms=50, threads=8, health_due_ms=10):
if mode == "on the loop":
# the loop runs each request to completion; nothing else can run meanwhile
done = [work_ms * (i + 1) for i in range(requests)]
health = max(health_due_ms, done[-1]) # the probe waits for a free loop
else:
# the loop only hands work to threads, so it stays free for the probe
done = [work_ms * (i // threads + 1) for i in range(requests)]
health = health_due_ms
return health, max(done)
PROBE_TIMEOUT_MS = 1000
for requests in (10, 60):
for mode in ("on the loop", "thread pool"):
health, total = simulate(mode, requests)
verdict = "PROBE TIMES OUT: pod restarted" if health > PROBE_TIMEOUT_MS else "probe ok"
print(f"{requests:>2} requests, {mode:<11}: health check after {health:>5} ms, "
f"all done after {total:>5} ms -> {verdict}")
Run it, and you should see this output:
$ python3 event_loop_sim.py 10 requests, on the loop: health check after 500 ms, all done after 500 ms -> probe ok 10 requests, thread pool: health check after 10 ms, all done after 100 ms -> probe ok 60 requests, on the loop: health check after 3000 ms, all done after 3000 ms -> PROBE TIMES OUT: pod restarted 60 requests, thread pool: health check after 10 ms, all done after 400 ms -> probe ok
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/serving-models-from-python-with-fastapi && cd ~/labs/serving-models-from-python-with-fastapi) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Serving Models from Python with FastAPI", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'A tiny service with a blocking and a non-blocking endpoint.'
'Ten concurrent calls to the blocking endpoint, while timing the health check.'
'The same with the pooled endpoint: the health check stays fast; then stop the server.'
)
step_1() {
cat > /tmp/svc.py <<'EOF'
import time
from fastapi import FastAPI
app = FastAPI()
@app.get("/livez")
def livez():
return {"ok": True}
@app.get("/blocking")
async def blocking():
time.sleep(0.5) # CPU-style work on the event loop
return {"done": True}
@app.get("/pooled")
def pooled():
time.sleep(0.5) # plain def: FastAPI runs it in a thread pool
return {"done": True}
EOF
cd /tmp && (uvicorn svc:app --port 8077 >/dev/null 2>&1 &) && sleep 2 && cd - >/dev/null
}
step_2() {
for i in $(seq 10); do curl -s -o /dev/null localhost:8077/blocking & done; sleep 0.1; curl -s -o /dev/null -w "livez took %{time_total}s\n" localhost:8077/livez; wait
}
step_3() {
for i in $(seq 10); do curl -s -o /dev/null localhost:8077/pooled & done; sleep 0.1; curl -s -o /dev/null -w "livez took %{time_total}s\n" localhost:8077/livez; wait; pkill -f "uvicorn svc:app"; rm -f /tmp/svc.py
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
curl, rm, cat, cd, Redirection, Loops, If...Else, Here documents.Serve an image-moderation model for an upload service: 300 uploads a second at peak, a 150 ms p99 budget, on CPU nodes.
How is the model loaded and how long does it take? Where does inference run so the service stays responsive? How big are batches, and how many workers and pods? How do probes behave during a slow start and under load? What do you measure?
Say 60 ms per image on 4 CPU cores, 1.2 GB of memory per model copy, 8 cores and 8 GB per node, and start-up of 20 seconds.
One worker per pod with 4 threads; the model loaded in the lifespan; inference micro-batched (up to 8 images or 10 ms) in a thread pool; readiness after loading with a 60-second start-up probe and a trivial liveness check; about 12 to 16 pods at peak with an HPA on requests per second; metrics for queue time, model time, and batch size; the model baked into a pinned image released by canary.
Larger batches raise throughput and add queueing delay, which eats the latency budget; small batches are faster per request and need more pods. CPU serving avoids GPU cost and scheduling, and needs more replicas.