πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

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:


πŸ“š 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.

The training script logs the model to the MLflow tracking server and registers it; mlflow models serve loads the champion alias from the Model Registry and serves it on port 5001 to curl, Python requests or a web app.
MLflow model serving pipeline β€” from training through registry to live 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 dependencies

The 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:

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

TypePython EquivalentUse Case
booleanboolBinary flags, toggle features
integerint32Categorical codes, counts
longint64Large IDs, class labels
floatfloat32General numeric features
doublefloat64High-precision features
stringstrText, categories
binarybytesImages, audio, embeddings
datetimedatetime64Timestamps

A POST to /invocations is checked against the signature; valid requests reach model.predict and return predictions, invalid ones get 400 Bad Request.
Signatures enable automatic input validation before inference

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.py

Expected 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 1

Serving 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

FlagDescriptionDefault
-m, --model-uriModel location (runs:/, models:/, or path)required
-p, --portPort to listen on5000
-h, --hostHost to bind to127.0.0.1
-w, --workersNumber of server worker processes1
--no-condaRemoved in MLflow 2.0; use --env-manager localfalse
--env-managerEnvironment manager (local, conda, virtualenv)virtualenv
--enable-mlserverUse 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 5001

Starting 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
Startup: resolve the model URI, set up the environment, load the model through pyfunc, start the HTTP server; then GET /health, GET /version and POST /invocations are available on port 5001.
MLflow serve startup sequence and exposed REST endpoints

Sending Predictions to the Serving Endpoint

The /invocations endpoint accepts several input formats. Let's explore each one.

REST API Input Formats

Four input formats for /invocations: dataframe_split (recommended), dataframe_records, instances and CSV.
Four input formats for the /invocations endpoint

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.x
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.py

Deep Dive: What Happens Under the Hood

Understanding the internals helps you debug and optimize your serving setup.

Inside one request: the HTTP layer routes by Content-Type, the parser builds a DataFrame and enforces the signature, pyfunc runs predict, and the serializer returns predictions with HTTP 200; schema failures return 400.
Four-layer request processing inside mlflow models serve

Advanced 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 conda

Multi-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 local

Worker 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

Aspectmlflow models serveCustom FastAPI (Day 15)
Setup timeOne commandWrite routes, schemas, loading logic
Schema validationAutomatic from signatureManual (Pydantic models)
Custom preprocessingVia pyfunc wrapperFull control in route handlers
Multiple endpointsSingle /invocationsUnlimited custom routes
Auth / middlewareNot built-inFull FastAPI middleware stack
Async supportNo (predict runs synchronously)Native async/await
Framework agnosticYes (any MLflow flavor)Manual per framework
Model hot-swapChange alias, restartCustom reload logic needed
Best forQuick deployments, standardized APIs, internal servicesCustom 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 5002

Model 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 local

Production 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.txt in 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:

Share this post