Skip to main content

Trace requests on custom model serving endpoints

When a request to your endpoint is slow or returns a wrong answer, a trace shows what happened inside your model for that request. It lists each step the request went through, what each step received and returned, and how long each step took.

To trace requests, add tracing to your model's code, turn it on when you create the endpoint, and read the traces from a table in Unity Catalog.

Requirements​

Set up tracing and read the spans​

Trace requests notebook

Run the cells in order, in the same notebook.

Install the packages and set the names​

  1. To install MLflow and the OpenTelemetry exporter package and restart Python, run the following:

    Python
    %pip install -q "mlflow==3.18.0" "opentelemetry-exporter-otlp-proto-http>=1.37.0"
    dbutils.library.restartPython()

    The cell finishes without errors.

  2. Set the names. Replace <catalog> and <schema> with your catalog and schema. ENVIRONMENT_VARS turns on tracing for the served model when you create the endpoint. To set the names, run the following:

    Python
    CATALOG = "<catalog>"
    SCHEMA = "<schema>"
    MODEL_NAME = f"{CATALOG}.{SCHEMA}.traced_model"
    ENDPOINT_NAME = "traced-model"
    PREFIX = "traced_model"
    TABLE_NAMES = {
    "logs_table": f"{CATALOG}.{SCHEMA}.{PREFIX}_otel_logs",
    "metrics_table": f"{CATALOG}.{SCHEMA}.{PREFIX}_otel_metrics",
    "traces_table": f"{CATALOG}.{SCHEMA}.{PREFIX}_otel_spans",
    }
    ENVIRONMENT_VARS = {"ENABLE_MLFLOW_TRACING": "true"}

    The spans go to the traces table. Each request and its response go to the logs table, and the service creates a view over it named {PREFIX}_payload. Later steps call this view the inference table.

    The tables stay after you delete the endpoint, so use a new prefix each time you run the notebook. With an earlier prefix, the queries also find the rows from the earlier run.

Add tracing to your model's code​

A step is a method in your model's code, such as predict and the helper methods it calls. To trace a step, add @mlflow.trace on the line above the method. Each traced step becomes a span, which records the step's name, inputs, outputs, and run time. The spans of one request make up its trace, and MLflow nests a helper's span under the predict span that called it.

In your own model, add the line above predict and above each helper that you want to see. The example model is a small stand-in that shows where the lines go: its predict method calls a helper named double for each input row. To define the example model, run the following:

Python
import mlflow
import pandas as pd


class TracedModel(mlflow.pyfunc.PythonModel):
@mlflow.trace
def double(self, value):
return value * 2

@mlflow.trace
def predict(self, context, model_input, params=None):
return pd.DataFrame({"prediction": [self.double(x) for x in model_input["x"]]})

Each span takes the name of its method. A request with two input rows gives one predict span and two double spans.

To create spans by hand instead of with @mlflow.trace, see Instrument your model code.

Log the model and its exporter package​

Endpoint telemetry receives traces in OpenTelemetry format. OpenTelemetry is an open source framework for sending traces, metrics, and logs. When telemetry is on, the endpoint tells MLflow where to send the spans, and MLflow needs the OpenTelemetry exporter package to send them. Add opentelemetry-exporter-otlp-proto-http to the model's pip_requirements, or no span reaches the traces table. To log and register the model, run the following:

Python
example = pd.DataFrame({"x": [1.0, 5.0]})
mlflow.set_registry_uri("databricks-uc")

with mlflow.start_run():
model_info = mlflow.pyfunc.log_model(
name="model",
python_model=TracedModel(),
input_example=example,
pip_requirements=["mlflow==3.18.0", "pandas", "opentelemetry-exporter-otlp-proto-http>=1.37.0"],
)
registered = mlflow.register_model(model_info.model_uri, MODEL_NAME)
print("Registered", MODEL_NAME, "version", registered.version)

The cell prints the following:

Text
Registered <catalog>.<schema>.traced_model version 1

MLflow also prints a link to the logged model and a link to the new version.

Create the endpoint with tracing and telemetry​

Create the endpoint in the Serving UI or from the notebook. Both turn on the same two settings: ENABLE_MLFLOW_TRACING on the served entity, and a telemetry_config that names the traces table.

To create the endpoint in the Serving UI:

  1. On the Create serving endpoint form, select Enable tracing for the served entity.
  2. Under AI Gateway, select Enable inference tables and telemetry, then choose the catalog, schema, and tables, as Enable telemetry on a new endpoint describes.
  3. Optionally, turn on dual export, which also stores each trace in the inference table, by adding the environment variable MLFLOW_TRACE_ENABLE_OTLP_DUAL_EXPORT with the value true to the served entity. See Secrets and credentials for Model Serving endpoints.

To create the endpoint from the notebook:

  1. Optionally, turn on dual export by adding MLFLOW_TRACE_ENABLE_OTLP_DUAL_EXPORT. Without that variable, the spans go to the traces table, and the trace field in each response is null. To add the variable, run the following:

    Python
    ENVIRONMENT_VARS["MLFLOW_TRACE_ENABLE_OTLP_DUAL_EXPORT"] = "true"

    ENVIRONMENT_VARS now holds both variables.

  2. Create the endpoint, and wait until it's ready. Run the following:

    Python
    from datetime import timedelta

    from databricks.sdk import WorkspaceClient

    w = WorkspaceClient()
    body = {
    "name": ENDPOINT_NAME,
    "config": {
    "served_entities": [
    {
    "entity_name": MODEL_NAME,
    "entity_version": str(registered.version),
    "workload_size": "Small",
    "scale_to_zero_enabled": True,
    "environment_vars": ENVIRONMENT_VARS,
    }
    ]
    },
    "telemetry_config": {
    "enabled_telemetry_features": [
    "TELEMETRY_FEATURE_LOGS",
    "TELEMETRY_FEATURE_TRACES",
    "TELEMETRY_FEATURE_METRICS",
    "TELEMETRY_FEATURE_INFERENCE_TABLE",
    ],
    "inference_table_config": {"sampling_fraction": 1},
    "table_names": TABLE_NAMES,
    },
    }
    w.api_client.do("POST", "/api/2.0/serving-endpoints", body=body)
    endpoint = w.serving_endpoints.wait_get_serving_endpoint_not_updating(name=ENDPOINT_NAME, timeout=timedelta(minutes=45))
    print(endpoint.state.ready, endpoint.state.config_update)

    The cell prints the following:

    Text
    EndpointStateReady.READY EndpointStateConfigUpdate.NOT_UPDATING

    The endpoint is ready when state.ready is READY and state.config_update is NOT_UPDATING.

Query the endpoint and read the spans​

  1. Send three requests. A request sent right after the endpoint reports READY can get a 404 for a short time, so the loop retries. If a request gets NotFound, the loop sends all three again. The cell creates its own client, so it works whether you created the endpoint in the Serving UI or in the notebook. Run the following:

    Python
    import time

    from databricks.sdk import WorkspaceClient
    from databricks.sdk.errors import NotFound

    w = WorkspaceClient()
    for attempt in range(12):
    try:
    for i in range(3):
    response = w.api_client.do(
    "POST",
    f"/serving-endpoints/{ENDPOINT_NAME}/invocations",
    body={"dataframe_records": [{"x": 1.0}, {"x": 5.0}]},
    )
    break
    except NotFound:
    time.sleep(10)
    print(response)

    The cell prints the following:

    Text
    {'predictions': [{'prediction': 2.0}, {'prediction': 10.0}]}
  2. Read the spans from the traces table. The query lists each span's name, its trace ID, and its run time in milliseconds. Each part of the table name is in backticks, so names that have a hyphen work. Run the following:

    Python
    spans = spark.sql(f"""
    SELECT name, trace_id, (end_time_unix_nano - start_time_unix_nano) / 1e6 AS duration_ms
    FROM `{CATALOG}`.`{SCHEMA}`.`{PREFIX}_otel_spans`
    ORDER BY start_time_unix_nano
    """)
    spans.show(truncate=False)

    The cell prints the following:

    Text
    +-------+--------------------------------+-----------+
    |name |trace_id |duration_ms|
    +-------+--------------------------------+-----------+
    |predict|<trace-id-1> |6.665476 |
    |double |<trace-id-1> |0.377173 |
    |double |<trace-id-1> |0.244809 |
    |predict|<trace-id-2> |7.06737 |
    |double |<trace-id-2> |0.467795 |
    |double |<trace-id-2> |0.242893 |
    |predict|<trace-id-3> |5.175503 |
    |double |<trace-id-3> |0.299092 |
    |double |<trace-id-3> |0.24008 |
    +-------+--------------------------------+-----------+

    Spans reach the table after the endpoint receives traffic. If the query returns no rows, wait, then run it again.

  3. If you added the dual export variable, read each request's trace from the inference table. The response column holds the body that the endpoint returned, and its databricks_output.trace field holds the trace. Run the following:

    Python
    traces = spark.sql(f"""
    SELECT databricks_request_id, response:databricks_output.trace.info.trace_id AS trace_id
    FROM `{CATALOG}`.`{SCHEMA}`.`{PREFIX}_payload`
    """)
    traces.show(truncate=False)

    The cell prints the following:

    Text
    +------------------------------------+-----------------------------------+
    |databricks_request_id |trace_id |
    +------------------------------------+-----------------------------------+
    |<request-id-1> |tr-<trace-id-1> |
    |<request-id-2> |tr-<trace-id-2> |
    |<request-id-3> |tr-<trace-id-3> |
    +------------------------------------+-----------------------------------+

    Each trace ID in the inference table is the trace ID of that request's spans with the prefix tr-.

    If you didn't add the variable, trace is null in every row.

Delete the endpoint and the model​

Optionally, delete the endpoint and the model. You can't undo deleting the endpoint or the model. The cell deletes the endpoint and the model version that you registered. When no other version of the model is left, the cell also deletes the registered model. To delete them, run the following:

Python
from mlflow import MlflowClient

w.serving_endpoints.delete(name=ENDPOINT_NAME)
client = MlflowClient()
client.delete_model_version(name=MODEL_NAME, version=registered.version)
if not client.search_model_versions(f"name='{MODEL_NAME}'"):
client.delete_registered_model(name=MODEL_NAME)
print("Deleted", ENDPOINT_NAME, "and version", registered.version, "of", MODEL_NAME)

The cell prints the following:

Text
Deleted traced-model and version 1 of <catalog>.<schema>.traced_model

Troubleshooting​

The traces table has no spans​

Check that the model's pip_requirements include opentelemetry-exporter-otlp-proto-http. MLflow needs the exporter package to send spans to the traces table. If the package is missing, add it to the model's pip_requirements as in Log the model and its exporter package. See Update an endpoint's configuration.

Also check that the endpoint's telemetry_config names a traces_table.

The trace field in the response is null​

The field stays null unless dual export is on. It doesn't mean that tracing is off, because the spans still reach the traces table.

Solution: Read the spans from the traces table, as in Query the endpoint and read the spans. To also store each trace in the trace field, add the environment variable MLFLOW_TRACE_ENABLE_OTLP_DUAL_EXPORT with the value true to the served entity, as in Create the endpoint with tracing and telemetry.

The service logs show "Trace not found for request_id"​

The endpoint found no finished trace to return with that request's response. It doesn't mean that tracing is off. With only ENABLE_MLFLOW_TRACING set, the line appears for each request, and the spans are still in the traces table.

Solution: Read the spans from the traces table, as in Query the endpoint and read the spans. To also return each trace in the response, and stop the line from appearing, turn on dual export, as in Create the endpoint with tracing and telemetry.

Additional resources​