Sub topic 15
Scaling out with multiple replicas
This chapter assumes you have the FastAPI iris service from the earlier chapters, a Docker image built from it, and a working idea of how Uvicorn handles requests. You should also know the difference between a CPU-bound call and an I/O-bound call. By the end you will know how to run several copies of the service, what makes that safe, and where it stops helping.
Why one process is not enough
A single Uvicorn process runs your Python code in one interpreter. The /predict handler is a plain def, so FastAPI runs it in a thread pool. The Python global interpreter lock (GIL) still allows only one thread to run Python bytecode at a time. Libraries like NumPy and scikit-learn release the lock during heavy computation, so you get some parallelism, but not enough to use many cores well. You also have one machine, one failure point, and one process to restart on each deploy.
There are two ways to get more capacity:
- Scale up (vertical): give the process a bigger machine. This is simple, but it has a ceiling and still leaves a single point of failure.
- Scale out (horizontal): run several identical copies, called replicas, and spread requests across them. Capacity grows by adding copies, and losing one copy does not take the service down.
What makes a service safe to replicate
Replicas are only interchangeable if each request can be handled by any of them. The iris service already has this property for three reasons:
- The model is read-only. Each replica loads its own copy of
model.joblibat startup. No replica modifies it. - The request carries everything needed. A prediction depends only on the four features in the body.
- Nothing is kept between requests. There are no sessions, counters, or caches that a later request depends on.
A service with this property is called stateless. State that you add later breaks it. An in-memory cache, a per-user request counter, or a model that is updated in place all exist in only one replica. A request routed to another replica sees a different answer. If you need shared state, move it out of the process into something all replicas can reach, such as Redis or a database.
The shape of a replicated deployment
A load balancer is a component that receives client requests and forwards each one to a replica. The simplest policy is round robin, which sends requests to replicas in turn. Others pick the replica with the fewest open connections.
Clients only know the load balancer's address. Replicas can be added or removed without clients noticing.
Two ways to get replicas
Multiple worker processes in one container
Uvicorn can start several worker processes on one machine:
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4Each worker is a separate process with its own interpreter and its own call to the lifespan function, so each loads its own copy of the model. This gets around the GIL and uses more cores. It has two costs:
- Memory use is multiplied by the number of workers. A 2 GB model with 4 workers needs about 8 GB.
- All workers share one container. If the container dies, they all die.
Multiple containers behind a load balancer
This is the more common approach in production, and it is the one that scales past one machine. Each container runs one Uvicorn process. An orchestrator starts as many containers as you ask for and replaces any that fail.
Docker Compose lets you try this locally. First, add a small endpoint to main.py so you can see which replica answered:
import os
import socket
@app.get("/whoami")
def whoami():
return {"host": socket.gethostname(), "pid": os.getpid()}Next, create nginx.conf next to your Dockerfile. NGINX is a web server that can act as a load balancer:
events {}
http {
server {
listen 80;
location / {
proxy_pass http://api:8000;
}
}
}Then create docker-compose.yml:
services:
api:
build: .
deploy:
replicas: 3
nginx:
image: nginx:1.27
ports:
- "8080:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
- apiThe api service publishes no ports. Docker's internal DNS returns the addresses of all three containers for the name api, and NGINX rotates through them. Start it and send nine requests:
docker compose up --build -d
for i in $(seq 1 9); do curl -s http://localhost:8080/whoami; echo; doneYou should see three different host values, each appearing about three times.
NGINX resolves the name api once when it starts. If you later change the replica count, restart NGINX so it picks up the new addresses. Orchestrators like Kubernetes avoid this problem by managing the list of replica addresses for you.
Health checks decide who receives traffic
A load balancer needs to know which replicas can take requests. Replicas that are starting up, or that are stuck, must not receive traffic. Orchestrators use two kinds of probe:
- A liveness probe asks whether the process is alive. If it fails repeatedly, the replica is restarted.
- A readiness probe asks whether the replica can serve traffic right now. If it fails, the replica stays running but is removed from the load balancer.
Your lifespan function loads the model before Uvicorn accepts any requests. So /health cannot answer until the model is loaded. This makes it a usable readiness check, and it also makes the model_loaded field a useful second signal. Here is a Kubernetes Deployment that uses it:
apiVersion: apps/v1
kind: Deployment
metadata:
name: iris-api
spec:
replicas: 3
selector:
matchLabels:
app: iris-api
template:
metadata:
labels:
app: iris-api
spec:
containers:
- name: api
image: iris-api:1.0.0
ports:
- containerPort: 8000
env:
- name: OMP_NUM_THREADS
value: "1"
resources:
requests:
cpu: "500m"
memory: 512Mi
limits:
cpu: "1"
memory: 1Gi
readinessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 3
periodSeconds: 5
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 10
periodSeconds: 10The requests values tell the scheduler how much each replica needs to be placed on a node. The limits values cap what it may use. Set the memory limit comfortably above the loaded model size, because a replica that exceeds it is killed.
Sizing replicas: CPU, threads, and memory
Adding replicas does not help if they compete for the same cores. Libraries such as NumPy use their own thread pools through OpenMP or BLAS. If each of 4 replicas starts 8 threads on an 8-core machine, you get 32 threads fighting for 8 cores, and latency gets worse. Setting OMP_NUM_THREADS=1, as in the manifest above, gives each replica one compute thread. Then you control parallelism by the replica count. If you want to use a model's own parallelism instead, run fewer replicas and give each more CPU.
A rough capacity estimate is:
total throughput ≈ replicas × (1 / seconds per request per replica)Measure the per-replica number with a load test before you trust it. Leave headroom of about 30 to 40 percent, because latency rises sharply as a replica nears full utilization.
Autoscaling
An autoscaler changes the replica count in response to load. Common signals are CPU utilization, requests per second per replica, and request queue length. CPU is the easiest to set up and works well for CPU-bound models. Keep these points in mind:
- Set a minimum of at least two replicas so one failure or deploy does not remove all capacity.
- Set a maximum, because every replica loads a full copy of the model and costs memory.
- Scale-up is not instant. A new replica has to be scheduled, pull the image, start Python, and load the model. For a large model this can take minutes, so scale on a lower threshold than you think you need.
Failure modes and edge cases
- Uneven load. Round robin counts requests, not work. If some requests are much more expensive, such as large batches sent to
/predict/batch, one replica can be overloaded while others are idle. A least-connections policy helps. - Rolling deploys with mixed versions. During an update, old and new replicas answer side by side. If the model or response schema changed, clients may see both versions. Keep changes backward compatible, or include a model version field in the response.
- Thundering restarts. If all replicas start at once and each loads a large file from shared storage, the storage becomes the bottleneck. Bake the model into the image, as the Dockerfile in this tutorial does, or stagger startups.
- Per-replica limits. A rate limit counted in process memory applies to each replica separately. With 3 replicas and a limit of 100 per minute, a client can make about 300. Use a shared store if you need a global limit.
- Local logs and metrics. Each replica has its own logs. Send them to a central place and include the host name, so you can tell which replica produced a slow or failing request.
Summary of decisions
| Situation | Choice |
|---|---|
| Need more cores on one machine, memory is plentiful | Several Uvicorn workers in one container |
| Need availability and growth beyond one machine | One process per container, many containers |
| Replicas slow each other down | Set `OMP_NUM_THREADS=1` and size CPU requests per replica |
| Large model, slow startup | Bake it into the image, keep a minimum replica count, scale early |
| Need a global rate limit or shared cache | Use an external store, not process memory |
Exercise
A service runs 4 Uvicorn workers in one container, and the model takes 1.5 GB of memory once loaded. What is the approximate memory needed for the model alone, and why? Name one reason to run one worker per container instead.
Show answer
About 6 GB, because each worker is a separate process that runs the lifespan function and loads its own copy of the model (4 × 1.5 GB). One worker per container lets the orchestrator add, remove, restart, and health-check each replica independently, and lets you scale across multiple machines, not only the cores of one.
Exercise
You run 3 replicas, and each one enforces a limit of 60 requests per minute per client using a counter held in memory. What limit does a client actually experience, and how would you fix it?
Show answer
Up to about 180 requests per minute, because each replica keeps its own counter and the load balancer spreads the client's requests across all three. To enforce 60 in total, keep the counter in a shared store that every replica uses, such as Redis, or apply the limit at the load balancer or gateway.