Sub topic 16
When to use a dedicated model server
This chapter assumes you have built the FastAPI service from the earlier chapters. That means a saved model.joblib, a typed /predict endpoint, a model loaded at startup, tests, a Docker image, and a basic idea of batching, concurrency, and replicas. The goal here is to decide when that hand-written service stops being the right tool.
What a dedicated model server provides
A dedicated model server is a program built only to host models and answer inference requests. You give it a model artifact and a small configuration file. It supplies the HTTP or gRPC endpoints, the model loading, and the request scheduling.
Common examples:
- NVIDIA Triton Inference Server hosts models from several frameworks (ONNX, TensorRT, PyTorch, TensorFlow) and is built for GPU workloads.
- TensorFlow Serving hosts TensorFlow SavedModels.
- TorchServe hosts PyTorch models.
- MLServer hosts scikit-learn, XGBoost, and other models behind the V2 inference protocol.
- KServe and BentoML are higher-level tools. KServe deploys model servers on Kubernetes, and BentoML packages model code as a service.
Most of these servers share one feature set. They are built to take features off your hands that you would otherwise write yourself:
- Dynamic batching. The server holds incoming requests for a few milliseconds, groups them, and runs one model call.
- Multiple models and versions. One process serves several models, and a model directory can hold numbered versions.
- Hot reload. A new model version loads without restarting the server.
- Standard protocols. Clients use a documented API, such as the V2 inference protocol, instead of your custom schema.
- Built-in metrics. Request counts, latency, and queue time are exported, usually in Prometheus format.
- Hardware management. GPU memory, instance counts per GPU, and CPU thread settings are configured rather than coded.
What your own FastAPI service does better
A dedicated server is not an upgrade in every case. The hand-written service has real strengths.
- Custom logic around the model. Your
/predictcan call a feature store, apply business rules, combine two models, or log to a special system. Model servers can do some of this (Triton ensembles, MLServer custom runtimes), but it is more awkward than writing Python. - Your own contract. The
IrisFeaturesschema gives clients named fields and clear 422 errors. Most model servers expose tensors with names, shapes, and data types, and clients must know that format. - Simplicity. One file, one image, one process. A new teammate can read it in ten minutes.
- Small models. If a prediction takes 2 ms on CPU and traffic is modest, a batching scheduler adds complexity without a visible benefit.
A common pattern combines both. A thin FastAPI layer keeps the public contract, validation, and authentication, and it calls a model server over the internal network.
Signs that you have outgrown the hand-written service
Look for concrete symptoms, not a vague feeling that it should be "more production-grade".
- GPU utilization is low and cost is high. Single-row requests keep an expensive GPU idle. Dynamic batching is the main fix, and writing a correct batching queue yourself (timeouts, error handling per request, back-pressure) is hard.
- Latency is dominated by queuing. Under load, requests wait for each other because the model call blocks a worker. A server with separate model instances and a scheduler handles this more predictably.
- You host many models. Ten models in ten FastAPI images means ten deployments, ten sets of tests, and ten copies of the same boilerplate.
- You need frequent model updates. If data scientists ship new versions weekly, version directories, rollbacks, and hot reload are worth having.
- Models are deep-learning models that need optimization. Converting to ONNX or TensorRT can cut latency substantially, and servers like Triton run those formats natively.
- Operations teams want standard behavior. A common protocol and metrics format means one dashboard and one client library for every model.
The reverse also holds. If none of these apply, a model server adds a new system to learn, deploy, and debug.
A worked example with MLServer
MLServer can serve the same model.joblib from the first chapter without any FastAPI code. Install it with the scikit-learn runtime:
pip install mlserver mlserver-sklearnCreate a model-settings.json file in the same directory as model.joblib. The max_batch_size and max_batch_time settings turn on adaptive batching, so the server groups requests that arrive within 20 ms, up to 32 rows.
{
"name": "iris",
"implementation": "mlserver_sklearn.SKLearnModel",
"max_batch_size": 32,
"max_batch_time": 0.02,
"parameters": {
"uri": "./model.joblib",
"version": "v1"
}
}Start the server from that directory, then send a request that follows the V2 inference protocol:
mlserver start .
curl -X POST http://localhost:8080/v2/models/iris/infer \
-H "Content-Type: application/json" \
-d '{"inputs": [{"name": "input-0", "shape": [1, 4], "datatype": "FP64", "data": [5.1, 3.5, 1.4, 0.2]}]}'The response contains an outputs list. For this model the first output is named predict and holds the class index. Check the exact layout against the MLServer version you install, because details of the response can differ between releases.
Compare this with your FastAPI service:
| Aspect | FastAPI service | Model server (MLServer) |
|---|---|---|
| Request format | Named fields (`sepal_length`, ...) | Tensor with name, shape, datatype, data |
| Validation | Pydantic rules such as `gt=0` | Shape and datatype checks only |
| Batching | You write it | Configured with two settings |
| Health checks | You write `/health` | Built-in `/v2/health/live` and `/v2/health/ready` |
| Custom logic | Plain Python | Custom runtime class |
| Multiple models | One service per model, or code your own registry | One server, many model folders |
Notice what you lose. The friendly contract and the gt=0 check are gone. If you want them back, put a FastAPI layer in front that validates input, builds the tensor payload, and forwards it.
import httpx
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
MODEL_URL = "http://localhost:8080/v2/models/iris/infer"
class IrisFeatures(BaseModel):
sepal_length: float = Field(gt=0)
sepal_width: float = Field(gt=0)
petal_length: float = Field(gt=0)
petal_width: float = Field(gt=0)
@app.post("/predict")
async def predict(features: IrisFeatures):
payload = {
"inputs": [
{
"name": "input-0",
"shape": [1, 4],
"datatype": "FP64",
"data": [
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
],
}
]
}
async with httpx.AsyncClient() as client:
response = await client.post(MODEL_URL, json=payload)
response.raise_for_status()
return {"class_index": int(response.json()["outputs"][0]["data"][0])}This handler is now async and only waits on the network, so it avoids the blocking-work problem from the concurrency chapter. The model server handles the heavy computation and batching.
Trade-offs and failure modes
- Another hop. The extra network call adds a few milliseconds. For models that take 100 ms this is minor, and for models that take 1 ms it can double the latency.
- Another system to operate. You now monitor, upgrade, and secure two services. Authentication, which the FastAPI layer used to handle, must be applied at the right place. A model server on an open port with no authentication is a common mistake.
- Batching delay.
max_batch_timeadds up to that many milliseconds of waiting to a request when traffic is low. Tune it against your latency budget instead of copying a default. - Format lock-in. Some servers want a specific format (SavedModel, ONNX, TorchScript). Converting can change numeric results slightly, so run your comparison tests on the converted model.
- Version mismatches. The server's library versions must match those used for training. A scikit-learn model pickled in one version may fail or behave differently in another, which is the same artifact risk you saw in the saving chapter.
Summary of decision criteria
Stay with FastAPI when the model is small, traffic is moderate, and your own logic and contract matter most. Move to a dedicated model server when you need dynamic batching, GPU efficiency, many models, or fast model rollout. Use both together when you need a custom public contract and high-performance inference behind it.
Exercise
Your team serves one scikit-learn model that takes 3 ms per prediction on CPU, handles about 20 requests per second, and needs a rule that rejects requests from unknown customer IDs before the model runs. Should you move to a dedicated model server? Give two reasons.
Show answer
No. The load is low and the model is fast, so dynamic batching and GPU management would give little benefit. The customer ID rule is custom logic that is simple to write in a FastAPI handler, while a model server would need a custom runtime or an extra front-end service. A single FastAPI service stays simpler to build, test, and operate.
Exercise
You put a FastAPI layer in front of a model server. Name one thing the FastAPI layer should still do, and one thing it should leave to the model server.
Show answer
The FastAPI layer should keep input validation and authentication, for example the Pydantic rule that rejects negative measurements and an API key check. It should leave batching and the model computation to the model server.