Skip to main content

Deploy a demand forecast endpoint with Model Serving

This example deploys a custom demand forecast model to a CPU Model Serving endpoint and sends it one request with four rows, each for one item and one date. The notebook generates synthetic demand data, so you don't need a dataset.

The endpoint answers requests in real time. To score a set of rows in batch, see Deploy models for batch inference and prediction.

Requirements​

Run the example​

To run every step, import the notebook. Run the cells in order, in the same notebook.

Demand forecast endpoint notebook

Install the packages​

To install the packages, run the following:

Python
%pip install -U "mlflow>=3" "databricks-sdk>=0.102.0" scikit-learn==1.9.1 pandas==3.1.1
dbutils.library.restartPython()

The install can print a pip warning that databricks-connect requires pandas below 3. The install still finishes.

Set the model and endpoint names​

A Unity Catalog model name has three levels, catalog.schema.model, as described in Manage model lifecycle in Unity Catalog. Replace <catalog> and <schema> with the catalog and the schema from the requirement above. To set the names, run the following:

Python
# Set these once. Replace the placeholders with your own names.
CATALOG = "<catalog>"
SCHEMA = "<schema>"
MODEL = "demand_forecast_model"
ENDPOINT_NAME = "demand-forecast"
FULL_MODEL_NAME = f"{CATALOG}.{SCHEMA}.{MODEL}"

The endpoint name must be unique across the workspace.

Generate the demand data and define the model​

The cell makes two years of daily demand for three items. Each day's expected demand scales the item's base level by the day of the week (highest on Saturday) and by the season (highest in April). The day's units are drawn at random around that value. Run the following:

Python
import numpy as np
import pandas as pd

# Synthetic daily demand for three items, from 2024-01-01 through 2025-12-31.
# The fixed seed makes the same data on every run.
rng = np.random.default_rng(42)
ITEM_CODES = {"sku-101": 0, "sku-102": 1, "sku-103": 2}
BASE_DEMAND = {"sku-101": 120, "sku-102": 60, "sku-103": 200}
WEEKDAY_FACTOR = np.array([1.0, 0.95, 0.97, 1.0, 1.1, 1.3, 1.2]) # Monday through Sunday

dates = pd.date_range("2024-01-01", "2025-12-31", freq="D")
weekday = np.asarray(dates.dayofweek)
seasonal = 1 + 0.2 * np.sin(2 * np.pi * (np.asarray(dates.month) - 1) / 12)

frames = []
for item_id, base in BASE_DEMAND.items():
mean = base * WEEKDAY_FACTOR[weekday] * seasonal
frames.append(pd.DataFrame({"item_id": item_id, "date": dates, "units": rng.poisson(mean)}))
history = pd.concat(frames, ignore_index=True)

A PythonModel subclass must implement predict. DemandForecastModel turns each row into an item code, a day of the week, and a month, and passes them to the regressor it wraps. To define the class, run the following:

Python
import mlflow


class DemandForecastModel(mlflow.pyfunc.PythonModel):
"""Turns item_id and date rows into calendar features, then calls the regressor."""

def __init__(self, regressor, item_codes):
self.regressor = regressor
self.item_codes = item_codes

@staticmethod
def features(rows, item_codes):
dates = pd.to_datetime(rows["date"])
return pd.DataFrame({
"item_code": rows["item_id"].map(item_codes),
"day_of_week": dates.dt.dayofweek,
"month": dates.dt.month,
})

def predict(self, model_input, params):
return self.regressor.predict(self.features(model_input, self.item_codes))

Train and register the model in Unity Catalog​

To train the regressor and print the number of training rows, run the following:

Python
from sklearn.ensemble import RandomForestRegressor

X_train = DemandForecastModel.features(history, ITEM_CODES)
y_train = history["units"]
regressor = RandomForestRegressor(n_estimators=100, random_state=0).fit(X_train, y_train)
print("Trained on rows:", len(X_train))

The cell prints the following:

Text
Trained on rows: 2193

To set the registry to Unity Catalog and log the model, run the following:

Python
import mlflow
from mlflow.models import infer_signature

mlflow.set_registry_uri("databricks-uc")
model = DemandForecastModel(regressor, ITEM_CODES)

# The date column is a string, because callers send dates as text.
EXAMPLE_INPUT = pd.DataFrame({
"item_id": ["sku-101", "sku-102"],
"date": ["2026-12-01", "2026-12-07"],
})
signature = infer_signature(EXAMPLE_INPUT, model.predict(EXAMPLE_INPUT, None))
info = mlflow.pyfunc.log_model(
name="model",
python_model=model,
signature=signature,
input_example=EXAMPLE_INPUT,
registered_model_name=FULL_MODEL_NAME,
)
MODEL_VERSION = str(info.registered_model_version)
print("Registered model:", FULL_MODEL_NAME)
print("Version:", MODEL_VERSION)

The cell prints the following:

Text
Registered model: <catalog>.<schema>.demand_forecast_model
Version: 1

Unity Catalog requires a signature on each new model version. The cell builds the signature with infer_signature from the example input and the model's predictions on that input.

registered_model_name creates the model version under that name, and it creates the registered model too when none exists.

Create the endpoint​

Before you create the endpoint, test the model's predictions offline.

The endpoint serves the version that the log cell registered, as a CPU workload. For the workload sizes and the other endpoint settings, see Create an endpoint for custom models in Model Serving. To create the endpoint and wait for it, run the following:

Python
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import EndpointCoreConfigInput, ServedEntityInput, ServingModelWorkloadType

w = WorkspaceClient()
endpoint = w.serving_endpoints.create_and_wait(
name=ENDPOINT_NAME,
config=EndpointCoreConfigInput(
name=ENDPOINT_NAME,
served_entities=[
ServedEntityInput(
entity_name=FULL_MODEL_NAME,
entity_version=MODEL_VERSION,
workload_type=ServingModelWorkloadType.CPU,
workload_size="Small",
scale_to_zero_enabled=True,
)
],
),
)
print("state.ready:", endpoint.state.ready)
print("state.config_update:", endpoint.state.config_update)

The scale_to_zero_enabled=True argument lets the endpoint scale to zero.

create_and_wait returns when state.config_update becomes NOT_UPDATING, and it doesn't check state.ready. After a successful create, the output below shows READY for state.ready and NOT_UPDATING for state.config_update.

Text
state.ready: EndpointStateReady.READY
state.config_update: EndpointStateConfigUpdate.NOT_UPDATING

Query the endpoint​

To query the endpoint with the item and date pairs in REQUEST_ROWS, run the following:

Python
import time
from databricks.sdk.errors import NotFound
from databricks.sdk.service.serving import DataframeSplitInput

# Each row is one item and one date. The response has one forecast per row.
REQUEST_ROWS = [
["sku-101", "2026-12-01"],
["sku-101", "2026-12-02"],
["sku-102", "2026-12-01"],
["sku-103", "2026-12-07"],
]

# Retry while the endpoint is not accepting requests yet.
for attempt in range(12):
try:
response = w.serving_endpoints.query(
name=ENDPOINT_NAME,
dataframe_split=DataframeSplitInput(columns=["item_id", "date"], data=REQUEST_ROWS),
)
break
except NotFound:
time.sleep(10)
else:
raise TimeoutError("The endpoint didn't accept the request after 12 tries.")

for (item_id, date), forecast in zip(REQUEST_ROWS, response.predictions):
print(f"{item_id} {date} forecast {forecast:.1f}")

Each row is one item and one date. The endpoint returns one prediction per row, and the cell prints each one on its own line.

Text
sku-101 2026-12-01 forecast 100.7
sku-101 2026-12-02 forecast 108.3
sku-102 2026-12-01 forecast 51.2
sku-103 2026-12-07 forecast 179.4

A query sent right after the endpoint reports READY can return HTTP 404 for a short time. The loop makes up to 12 tries, and it waits 10 seconds after each failed try.

Delete the endpoint and the registered model​

Optionally, delete the endpoint and the registered model. You can't undo deleting the endpoint or the registered model. To delete the endpoint, run the following:

Python
w.serving_endpoints.delete(name=ENDPOINT_NAME)
print("Deleted endpoint:", ENDPOINT_NAME)

The cell prints the following:

Text
Deleted endpoint: demand-forecast

To delete the model versions and the registered model with the MLflow client, run the following:

Python
from mlflow import MlflowClient

client = MlflowClient()
# Delete each model version first, then the registered model.
for version in client.search_model_versions(f"name='{FULL_MODEL_NAME}'"):
client.delete_model_version(name=FULL_MODEL_NAME, version=version.version)
client.delete_registered_model(name=FULL_MODEL_NAME)
print("Deleted model:", FULL_MODEL_NAME)

The cell prints the following:

Text
Deleted model: <catalog>.<schema>.demand_forecast_model

Additional resources​