MLflow Models Serve enables us to expose trained models as production-ready REST APIs with minimal effort while enforcing model signatures and input schemas for reliable, consistent, and validated real-time inference.
It bridges the gap between experimentation and deployment, making model serving, testing, and integration with applications faster, more scalable, and easier to maintain.
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP
π Key Learnings
- From Training to Serving: Why It Matters
- Understanding the MLflow Model Format
- Model Signatures & Input Schemas
- Hands-On: Train, Log & Register the Iris Model
- Serving with
mlflow models serve - Sending Predictions to the Serving Endpoint
- Deep Dive: What Happens Under the Hood
- Advanced Serving Patterns
- MLflow Serve vs Custom FastAPI: When to Use Which
- Troubleshooting Common Issues
π§ Learn here
From Training to Serving: Why It Matters
Training a model is only half the journey. A model locked inside a Jupyter notebook or a .pkl file doesn't deliver business value. Model serving bridges the gap between an ML artifact and a live prediction service that applications can call.
In Day 15, we built a FastAPI service from scratch. Today, we'll see how MLflow Models Serve eliminates most of that boilerplate: no manual deserialization, no custom route definitions, no schema handling. One command, and you have a production-grade REST endpoint.

Understanding the MLflow Model Format
Before we serve, let's understand what we're serving. When you call mlflow.sklearn.log_model(), MLflow creates a standardized directory structure:
model/
βββ MLmodel # Metadata: flavors, signature, environment
βββ model.pkl # Serialized model artifact
βββ conda.yaml # Conda environment specification
βββ python_env.yaml # Python virtualenv specification
βββ requirements.txt # pip dependenciesThe MLmodel File
This YAML file is the heart of MLflow's model format. It describes how to load and serve the model regardless of the ML framework that created it:
artifact_path: model
flavors:
python_function:
env:
conda: conda.yaml
virtualenv: python_env.yaml
loader_module: mlflow.sklearn
model_path: model.pkl
predict_fn: predict
python_version: 3.11.5
sklearn:
code: null
pickled_model: model.pkl
serialization_format: cloudpickle
sklearn_version: 1.4.2
run_id: a1b2c3d4e5f6
signature:
inputs: '[{"name":"sepal_length","type":"double"},...]'
outputs: '[{"type":"long"}]'Key Concept: Flavors
MLflow flavors are the magic that makes mlflow models serve framework-agnostic. Every logged model gets a python_function flavor (the universal loader) plus its native flavor (e.g., sklearn, pytorch, xgboost). The serving infrastructure always uses the python_function flavor.
Model Signatures & Input Schemas
A model signature defines the expected input and output schema for your model. This is critical for serving because it enables automatic input validation, type coercion, and self-documenting APIs.
Why Signatures Matter?
Without a signature: MLflow accepts any JSON payload and passes it directly to the model. If the input shape or types are wrong, you get a cryptic error from scikit-learn deep in the stack.
With a signature: MLflow validates the request before it reaches the model and returns a clear 400 error with details about what's wrong. This is the difference between a toy demo and a production service.
Creating Signatures
There are three ways to create a model signature:
Method 1: Automatic Inference (Recommended)
import mlflow
from mlflow.models import infer_signature
# After training, let MLflow infer from actual data
signature = infer_signature(X_train, model.predict(X_train))
mlflow.sklearn.log_model(
model,
"model",
signature=signature,
input_example=X_train.iloc[:3] # Optional: sample input for docs
)Method 2: Manual Definition
from mlflow.models import ModelSignature
from mlflow.types.schema import Schema, ColSpec
input_schema = Schema([
ColSpec("double", "sepal_length"),
ColSpec("double", "sepal_width"),
ColSpec("double", "petal_length"),
ColSpec("double", "petal_width"),
])
output_schema = Schema([ColSpec("long")])
signature = ModelSignature(
inputs=input_schema,
outputs=output_schema
)Method 3: From a Signature Dict (for complex types)
from mlflow.models import ModelSignature
signature = ModelSignature.from_dict({
"inputs": [
{"name": "sepal_length", "type": "double"},
{"name": "sepal_width", "type": "double"},
{"name": "petal_length", "type": "double"},
{"name": "petal_width", "type": "double"},
],
"outputs": [{"type": "long"}]
})Supported Schema Types
| Type | Python Equivalent | Use Case |
|---|---|---|
boolean | bool | Binary flags, toggle features |
integer | int32 | Categorical codes, counts |
long | int64 | Large IDs, class labels |
float | float32 | General numeric features |
double | float64 | High-precision features |
string | str | Text, categories |
binary | bytes | Images, audio, embeddings |
datetime | datetime64 | Timestamps |

Hands-On: Train, Log & Register the Iris Model
Let's start from scratch with a clean training script that logs the model with a proper signature and registers it in the MLflow Model Registry.
Project Structure
iris-mlops/
βββ train_and_register.py # Train, log, register with signature
βββ test_serving.py # Python client for predictions
βββ test_serving.sh # curl-based test script
βββ mlflow.db # tracking + registry data (auto-created)
βββ mlartifacts/ # model artifacts (auto-created)Step-by-Step: Training & Registration Script
#!/usr/bin/env python3
"""
Day 16: Train an Iris classifier and register it in MLflow Registry
with a proper model signature for serving.
"""
import mlflow
import mlflow.sklearn
from mlflow.models import infer_signature
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, f1_score
import pandas as pd
import numpy as np
# ββ 1. Load and prepare data ββ
iris = load_iris(as_frame=True)
X = iris.data # DataFrame with column names
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
print(f"Training set: {X_train.shape[0]} samples")
print(f"Test set: {X_test.shape[0]} samples")
print(f"Features: {list(X.columns)}")
# ββ 2. Set up MLflow ββ
mlflow.set_tracking_uri("http://localhost:5000")
mlflow.set_experiment("iris-classifier")
# ββ 3. Train & log with MLflow ββ
with mlflow.start_run(run_name="rf-best-model") as run:
# Hyperparameters
params = {
"n_estimators": 150,
"max_depth": 5,
"min_samples_split": 3,
"min_samples_leaf": 2,
"random_state": 42,
}
mlflow.log_params(params)
# Train
model = RandomForestClassifier(**params)
model.fit(X_train, y_train)
# Evaluate
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred, average="weighted")
mlflow.log_metrics({
"accuracy": accuracy,
"f1_weighted": f1,
})
print(f"\nAccuracy: {accuracy:.4f}")
print(f"F1 Score: {f1:.4f}")
# ββ 4. Infer model signature from real data ββ
signature = infer_signature(
model_input=X_train,
model_output=model.predict(X_train)
)
print(f"\nModel Signature:")
print(f" Inputs: {signature.inputs}")
print(f" Outputs: {signature.outputs}")
# ββ 5. Log model with signature & input example ββ
mlflow.sklearn.log_model(
sk_model=model,
artifact_path="model",
signature=signature,
input_example=X_test.iloc[:3], # 3 sample rows for docs
registered_model_name="iris-classifier", # Auto-registers!
)
print(f"\n{'='*50}")
print(f"Model registered as 'iris-classifier'")
print(f"Run ID: {run.info.run_id}")
print(f"Model URI: runs:/{run.info.run_id}/model")
print(f"{'='*50}")
# ββ 6. Set model alias (MLflow 2.x+ approach) ββ
from mlflow import MlflowClient
client = MlflowClient()
# Get the latest version number
versions = client.search_model_versions("name='iris-classifier'")
latest_version = max(int(v.version) for v in versions) # versions come back as strings
# Set alias for easy reference when serving
client.set_registered_model_alias(
name="iris-classifier",
alias="champion",
version=latest_version
)
print(f"Alias 'champion' set to version {latest_version}")Prerequisites
Make sure your MLflow tracking server is running before executing the training script. Start it in a separate terminal:
# Terminal 1: Start MLflow tracking server from inside iris-mlops
cd iris-mlops
mlflow server \
--host 0.0.0.0 \
--port 5000 \
--backend-store-uri sqlite:///mlflow.db \
--artifacts-destination ./mlartifacts# Terminal 2: Run training script
cd iris-mlops
python train_and_register.pyExpected output:
Training set: 120 samples
Test set: 30 samples
Features: ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
Accuracy: 1.0000
F1 Score: 1.0000
Model Signature:
Inputs: ['sepal length (cm)': double, 'sepal width (cm)': double,
'petal length (cm)': double, 'petal width (cm)': double]
Outputs: [Tensor('int64', (-1,))]
==================================================
Model registered as 'iris-classifier'
Run ID: a1b2c3d4e5f678901234
Model URI: runs:/a1b2c3d4e5f678901234/model
==================================================
Alias 'champion' set to version 1Serving with mlflow models serve
Now the exciting part. With one command, MLflow spins up a REST API server backed by your registered model.
The mlflow models serve Command
| Flag | Description | Default |
|---|---|---|
-m, --model-uri | Model location (runs:/, models:/, or path) | required |
-p, --port | Port to listen on | 5000 |
-h, --host | Host to bind to | 127.0.0.1 |
-w, --workers | Number of server worker processes | 1 |
--no-conda | Removed in MLflow 2.0; use --env-manager local | false |
--env-manager | Environment manager (local, conda, virtualenv) | virtualenv |
--enable-mlserver | Use MLServer backend (Seldon) | false |
Model URI Formats
MLflow supports several URI formats for specifying which model to serve:
# From a specific run (copy run_id from training output)
mlflow models serve -m "runs:/<run_id>/model" -p 5001
# From Model Registry by name + version
mlflow models serve -m "models:/iris-classifier/1" -p 5001
# From Model Registry by alias (recommended for production)
mlflow models serve -m "models:/iris-classifier@champion" -p 5001
# From a local directory path
mlflow models serve -m "./mlartifacts/<exp_id>/<run_id>/artifacts/model" -p 5001Starting the Server
# Terminal 3: serve the champion model on port 5001
# Use --env-manager=local to skip virtualenv creation (faster for dev)
mlflow models serve \
-m "models:/iris-classifier@champion" \
--port 5001 \
--host 0.0.0.0 \
--env-manager local
# You should see output like:
# ...a log line saying it is listening on http://0.0.0.0:5001
Sending Predictions to the Serving Endpoint
The /invocations endpoint accepts several input formats. Let's explore each one.
REST API Input Formats

Testing with curl
Health Check
# Verify the server is running
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:5001/health
# Response: 200 (the body is empty; 404 if the model failed to load)
curl -s http://localhost:5001/version
# Response: the MLflow version, e.g. 3.x.xFormat 1: dataframe_split (Recommended)
curl -X POST http://localhost:5001/invocations \
-H "Content-Type: application/json" \
-d '{
"dataframe_split": {
"columns": [
"sepal length (cm)",
"sepal width (cm)",
"petal length (cm)",
"petal width (cm)"
],
"data": [
[5.1, 3.5, 1.4, 0.2],
[6.2, 2.9, 4.3, 1.3],
[7.7, 3.0, 6.1, 2.3]
]
}
}'Expected response:
{
"predictions": [0, 1, 2]
}Format 2: dataframe_records
curl -X POST http://localhost:5001/invocations \
-H "Content-Type: application/json" \
-d '{
"dataframe_records": [
{
"sepal length (cm)": 5.1,
"sepal width (cm)": 3.5,
"petal length (cm)": 1.4,
"petal width (cm)": 0.2
}
]
}'Format 3: instances (TF Serving Format)
# Note: No column names, so schema validation is limited
curl -X POST http://localhost:5001/invocations \
-H "Content-Type: application/json" \
-d '{
"instances": [
[5.1, 3.5, 1.4, 0.2],
[6.2, 2.9, 4.3, 1.3]
]
}'CSV Format
curl -X POST http://localhost:5001/invocations \
-H "Content-Type: text/csv" \
-d 'sepal length (cm),sepal width (cm),petal length (cm),petal width (cm)
5.1,3.5,1.4,0.2
6.2,2.9,4.3,1.3
7.7,3.0,6.1,2.3'Testing with Python requests
#!/usr/bin/env python3
"""
Day 16: Test the MLflow model serving endpoint with Python.
"""
import requests
import json
import pandas as pd
from sklearn.datasets import load_iris
SERVE_URL = "http://localhost:5001/invocations"
HEADERS = {"Content-Type": "application/json"}
# Class name mapping for readable output
CLASS_NAMES = {0: "setosa", 1: "versicolor", 2: "virginica"}
def test_health():
"""Check server health."""
resp = requests.get("http://localhost:5001/health")
print(f"Health: HTTP {resp.status_code}") # the body is empty, not JSON
assert resp.status_code == 200
def test_single_prediction():
"""Send a single sample for prediction."""
payload = {
"dataframe_split": {
"columns": [
"sepal length (cm)",
"sepal width (cm)",
"petal length (cm)",
"petal width (cm)",
],
"data": [[5.1, 3.5, 1.4, 0.2]],
}
}
resp = requests.post(SERVE_URL, headers=HEADERS, json=payload)
result = resp.json()
pred = result["predictions"][0]
print(f"\nSingle Prediction:")
print(f" Input: [5.1, 3.5, 1.4, 0.2]")
print(f" Class: {pred} ({CLASS_NAMES[pred]})")
assert pred == 0, "Expected setosa (0)"
def test_batch_prediction():
"""Send a batch of samples."""
# Use real test data from the iris dataset
iris = load_iris(as_frame=True)
X_sample = iris.data.sample(10, random_state=42)
payload = {
"dataframe_split": {
"columns": X_sample.columns.tolist(),
"data": X_sample.values.tolist(),
}
}
resp = requests.post(SERVE_URL, headers=HEADERS, json=payload)
result = resp.json()
print(f"\nBatch Prediction ({len(result['predictions'])} samples):")
for i, pred in enumerate(result["predictions"]):
print(f" Sample {i+1}: class {pred} ({CLASS_NAMES[pred]})")
def test_invalid_input():
"""Send invalid data to see schema validation in action."""
# Wrong number of features
payload = {
"dataframe_split": {
"columns": ["sepal length (cm)", "sepal width (cm)"],
"data": [[5.1, 3.5]],
}
}
resp = requests.post(SERVE_URL, headers=HEADERS, json=payload)
print(f"\nInvalid Input Test:")
print(f" Status: {resp.status_code}")
print(f" Response: {resp.text[:200]}")
def test_with_pandas():
"""Build request from a pandas DataFrame."""
df = pd.DataFrame({
"sepal length (cm)": [5.9, 6.9],
"sepal width (cm)": [3.0, 3.1],
"petal length (cm)": [5.1, 5.4],
"petal width (cm)": [1.8, 2.1],
})
# Convert DataFrame to split format automatically
payload = {"dataframe_split": df.to_dict(orient="split")}
resp = requests.post(SERVE_URL, headers=HEADERS, json=payload)
result = resp.json()
print(f"\nPandas DataFrame Prediction:")
for i, pred in enumerate(result["predictions"]):
print(f" {df.iloc[i].to_dict()} β {CLASS_NAMES[pred]}")
if __name__ == "__main__":
print("=" * 60)
print(" MLflow Model Serving - Test Suite")
print("=" * 60)
test_health()
test_single_prediction()
test_batch_prediction()
test_invalid_input()
test_with_pandas()
print(f"\n{'='*60}")
print(" All tests passed!")
print(f"{'='*60}")# Run the test suite
python test_serving.pyDeep Dive: What Happens Under the Hood
Understanding the internals helps you debug and optimize your serving setup.

mlflow models serveAdvanced Serving Patterns
Custom Python Model (pyfunc)
When you need to add pre/post-processing (like returning class names instead of numeric labels), wrap your model in a custom PythonModel:
custom_model.py
import mlflow
import mlflow.pyfunc
import pandas as pd
import numpy as np
class IrisModelWrapper(mlflow.pyfunc.PythonModel):
"""Custom wrapper that returns class names and probabilities."""
CLASS_NAMES = ["setosa", "versicolor", "virginica"]
def load_context(self, context):
"""Load the underlying sklearn model from artifacts."""
import pickle
with open(context.artifacts["model_path"], "rb") as f:
self.model = pickle.load(f)
def predict(self, context, model_input: pd.DataFrame) -> pd.DataFrame:
"""Return predictions with class names and confidence."""
predictions = self.model.predict(model_input)
probabilities = self.model.predict_proba(model_input)
return pd.DataFrame({
"class_id": predictions,
"class_name": [self.CLASS_NAMES[p] for p in predictions],
"confidence": np.max(probabilities, axis=1).round(4),
})
# Log it (save the trained sklearn model to model.pkl first):
# with mlflow.start_run():
# mlflow.pyfunc.log_model(
# "model",
# python_model=IrisModelWrapper(),
# artifacts={"model_path": "model.pkl"},
# )
Serving with Environment Isolation
# Full virtualenv isolation (creates env from model's requirements.txt)
mlflow models serve \
-m "models:/iris-classifier@champion" \
--port 5001 \
--env-manager virtualenv
# Conda isolation (uses conda.yaml from model artifacts)
mlflow models serve \
-m "models:/iris-classifier@champion" \
--port 5001 \
--env-manager condaMulti-Worker Production Setup
# Production serving with multiple workers and timeout
# MLflow 3.x serves with uvicorn: set the request timeout here
export MLFLOW_SCORING_SERVER_REQUEST_TIMEOUT=120
# MLflow 2.x used gunicorn on Linux/macOS, which also reads its own flags
export GUNICORN_CMD_ARGS="--timeout 120 --keep-alive 5 --log-level info"
mlflow models serve \
-m "models:/iris-classifier@champion" \
--port 5001 \
--host 0.0.0.0 \
--workers 4 \
--env-manager localWorker Count Rule of Thumb
For CPU-bound models like scikit-learn, start with one worker per CPU core; gunicorn's (2 * CPU_CORES) + 1 rule is meant for I/O-bound web apps, not inference. For GPU models, typically 1 worker per GPU. Too many workers on a memory-constrained system will cause OOM kills since each worker loads a full copy of the model.
MLflow Serve vs Custom FastAPI: When to Use Which
| Aspect | mlflow models serve | Custom FastAPI (Day 15) |
|---|---|---|
| Setup time | One command | Write routes, schemas, loading logic |
| Schema validation | Automatic from signature | Manual (Pydantic models) |
| Custom preprocessing | Via pyfunc wrapper | Full control in route handlers |
| Multiple endpoints | Single /invocations | Unlimited custom routes |
| Auth / middleware | Not built-in | Full FastAPI middleware stack |
| Async support | No (predict runs synchronously) | Native async/await |
| Framework agnostic | Yes (any MLflow flavor) | Manual per framework |
| Model hot-swap | Change alias, restart | Custom reload logic needed |
| Best for | Quick deployments, standardized APIs, internal services | Custom APIs, complex pipelines, public-facing services |
Port Already in Use
# Find and kill the process using port 5001
lsof -ti:5001 | xargs kill -9
# Or use a different port
mlflow models serve -m "models:/iris-classifier@champion" -p 5002Model Not Found in Registry
# Verify tracking URI matches your training setup
export MLFLOW_TRACKING_URI=http://localhost:5000
# List registered models (there is no "mlflow models list" command)
python -c "from mlflow import MlflowClient; print([m.name for m in MlflowClient().search_registered_models()])"
# Check specific model versions
python -c "
from mlflow import MlflowClient
client = MlflowClient()
for v in client.search_model_versions('name=\"iris-classifier\"'):
print(f'Version {v.version}, Aliases: {v.aliases}')
"Schema Mismatch Errors
# Inspect the model's expected signature
python -c "
import mlflow
model = mlflow.pyfunc.load_model('models:/iris-classifier@champion')
print('Signature:', model.metadata.signature)
print('Input schema:', model.metadata.signature.inputs)
"Dependency Conflicts
# Check what the model expects
python -c "import mlflow; print(open(mlflow.pyfunc.get_model_dependencies('models:/iris-classifier@champion')).read())"
# Use local env manager to skip isolation (for debugging)
mlflow models serve -m "models:/iris-classifier@champion" --env-manager localProduction Serving Checklist
Before deploying your MLflow model server to production, validate these items:
- Model has a proper signature with all input columns and types defined
- Input example is logged (enables auto-generated API docs in MLflow UI)
- Model is registered in Model Registry with a meaningful alias (e.g.,
champion) - Health endpoint (
GET /health) returns 200 before routing traffic requirements.txtin model artifacts pins all dependency versions- Worker count is tuned for your hardware (CPU cores, available RAM)
- MLFLOW_SCORING_SERVER_REQUEST_TIMEOUT (or GUNICORN_CMD_ARGS on MLflow 2.x) covers your model's inference time
- Load test verifies latency under expected concurrency (p50, p95, p99)
- Schema validation catches malformed requests before they hit the model
- Logging captures request count, latency, and error rates for monitoring
- API gateway or reverse proxy handles TLS, auth, and rate limiting
- Graceful shutdown script kills workers without dropping in-flight requests
Quick Reference: Key Commands
#Cheat Sheet
# ββ Start MLflow Tracking Server ββ
mlflow server --host 0.0.0.0 --port 5000 \
--backend-store-uri sqlite:///mlflow.db
# ββ Train & Register (Python) ββ
mlflow.sklearn.log_model(model, "model",
signature=infer_signature(X, model.predict(X)),
registered_model_name="iris-classifier")
# ββ Set Alias ββ
client.set_registered_model_alias("iris-classifier", "champion", version)
# ββ Serve Model ββ
mlflow models serve -m "models:/iris-classifier@champion" \
--port 5001 --host 0.0.0.0 --env-manager local
# ββ Test Endpoint ββ
curl -X POST http://localhost:5001/invocations \
-H "Content-Type: application/json" \
-d '{"dataframe_split":{"columns":["sepal length (cm)","sepal width (cm)","petal length (cm)","petal width (cm)"],"data":[[5.1,3.5,1.4,0.2]]}}'
# ββ Inspect Model Signature ββ
python -c "import mlflow; m=mlflow.pyfunc.load_model('models:/iris-classifier@champion'); print(m.metadata.signature)"Model serving is the point where machine learning starts delivering real business value.
By mastering MLflow Models Serve, you can deploy trained models as production-ready APIs in minutes instead of building custom serving infrastructure from scratch.
Understanding model signatures and input schemas ensures reliable, consistent, and error-free predictions across applications. These skills form the foundation for scalable, maintainable, and production-grade ML systems.
With MLflow model serving in your toolkit, you're one step closer to building end-to-end MLOps pipelines that confidently take models from training to real-world impact.
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP

Member discussion