Skip to main content

Log requests and responses for custom model serving endpoints

Inference tables save the requests and responses of a custom model endpoint to a Delta table in Unity Catalog, and you query the payload view over that table. This page turns them on with the API, finds one request's row, and changes the sampling rate.

The examples run on a CPU custom model endpoint. Outputs show placeholders for your catalog, schema, prefix, and user name.

Requirements​

  • Unity Catalog is enabled in the workspace.
  • Serverless compute is enabled in the workspace.
  • A model version registered in Unity Catalog whose input is a required text column. The notebook registers an example model that returns each text unchanged and raises an error on the text boom.
  • For permissions, see the endpoint telemetry requirements.

Turn on inference tables with the API​

Log requests and responses notebook

Create the endpoint with a telemetry_config object. It names the telemetry tables, and its inference_table_config turns on the payload view.

  1. Install the packages, and restart Python.

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

    The cell installs databricks-sdk, mlflow, and pandas, and prints pip dependency warnings that don't stop the install.

  2. Set the catalog, schema, and prefix in your notebook. The table names come from the prefix.

    Python
    # Set these once. Replace the placeholders with your catalog and schema.
    CATALOG = "<catalog>"
    SCHEMA = "<schema>"
    MODEL = "requests_demo_model"
    ENDPOINT_NAME = "requests-demo"
    PREFIX = "<prefix>"
    FULL_MODEL_NAME = f"{CATALOG}.{SCHEMA}.{MODEL}"
    LOGS_TABLE = f"{CATALOG}.{SCHEMA}.{PREFIX}_otel_logs"
    METRICS_TABLE = f"{CATALOG}.{SCHEMA}.{PREFIX}_otel_metrics"
    SPANS_TABLE = f"{CATALOG}.{SCHEMA}.{PREFIX}_otel_spans"
    TABLE_NAMES = {"logs_table": LOGS_TABLE, "metrics_table": METRICS_TABLE, "traces_table": SPANS_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.

  3. Register the example model. It returns each text unchanged and raises an error on the text boom, so one of the later requests fails on purpose.

    Python
    import mlflow
    import pandas as pd
    from mlflow.models import infer_signature


    class EchoModel(mlflow.pyfunc.PythonModel):
    def predict(self, context, model_input):
    if (model_input["text"] == "boom").any():
    raise ValueError("The model raised an error on purpose.")
    return model_input


    mlflow.set_registry_uri("databricks-uc")
    example = pd.DataFrame({"text": ["hello"]})
    with mlflow.start_run():
    info = mlflow.pyfunc.log_model(
    name="model",
    python_model=EchoModel(),
    input_example=example,
    signature=infer_signature(example, example),
    registered_model_name=FULL_MODEL_NAME,
    )
    MODEL_VERSION = str(info.registered_model_version)
    print("Registered", FULL_MODEL_NAME, "version", MODEL_VERSION)

    The cell prints the following:

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

    If a model of that name already exists, the cell adds a version to it.

  4. Import the client, and define a helper that reads an endpoint and one that waits for READY.

    Python
    import json
    import time

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

    w = WorkspaceClient()


    def get_endpoint(endpoint):
    return w.api_client.do("GET", f"/api/2.0/serving-endpoints/{endpoint}")


    def wait_until_ready(endpoint, timeout_s=1200, every_s=15):
    """Waits until the endpoint is READY and no config update is running. Prints each change of state."""
    start, last, seen_update = time.time(), None, False
    while True:
    state = get_endpoint(endpoint).get("state", {})
    current = (state.get("ready"), state.get("config_update"))
    if current != last:
    print(f"state.ready={current[0]} state.config_update={current[1]}")
    last = current
    if current[1] == "IN_PROGRESS":
    seen_update = True
    if current == ("READY", "NOT_UPDATING"):
    return time.time() - start, seen_update
    if time.time() - start > timeout_s:
    raise TimeoutError(f"{endpoint} was not READY after {timeout_s} seconds")
    time.sleep(every_s)
  5. Create the endpoint. The request goes to POST /api/2.0/serving-endpoints, and it sets telemetry_config with the three telemetry table names and an inference_table_config with sampling_fraction set to 1.0.

    Python
    create_body = {
    "name": ENDPOINT_NAME,
    "config": {
    "served_entities": [
    {
    "entity_name": FULL_MODEL_NAME,
    "entity_version": MODEL_VERSION,
    "workload_type": "CPU",
    "workload_size": "Small",
    "scale_to_zero_enabled": True,
    }
    ]
    },
    "telemetry_config": {
    "table_names": TABLE_NAMES,
    "inference_table_config": {"sampling_fraction": 1.0},
    },
    }
    created = w.api_client.do("POST", "/api/2.0/serving-endpoints", body=create_body)
    print("Created endpoint:", created.get("name"))

    The cell prints the following:

    Text
    Created endpoint: requests-demo
  6. Wait for the endpoint to report READY, and then print its telemetry config. The wait prints each change of state.

    Python
    wait_until_ready(ENDPOINT_NAME)
    print("telemetry_config on the endpoint:", json.dumps(get_endpoint(ENDPOINT_NAME).get("telemetry_config")))

    The cell prints the following:

    Text
    state.ready=NOT_READY state.config_update=IN_PROGRESS
    state.ready=READY state.config_update=NOT_UPDATING
    telemetry_config on the endpoint: {"table_names": {"logs_table": "<catalog>.<schema>.<prefix>_otel_logs", "metrics_table": "<catalog>.<schema>.<prefix>_otel_metrics", "traces_table": "<catalog>.<schema>.<prefix>_otel_spans"}, "inference_table_config": {"sampling_fraction": 1.0, "name": "<catalog>.<schema>.<prefix>_payload"}, "enabled_telemetry_features": ["TELEMETRY_FEATURE_LOGS", "TELEMETRY_FEATURE_TRACES", "TELEMETRY_FEATURE_METRICS", "TELEMETRY_FEATURE_INFERENCE_TABLE"]}

    The inference_table_config names the payload view and shows sampling_fraction as 1.0.

To create the endpoint in the UI, see Create an endpoint for custom models.

To turn them on for an existing endpoint, see Enable telemetry on an existing endpoint.

Tables that inference tables create​

Four objects with the prefix are in the schema, and one of them is a view.

  • <prefix>_otel_logs, <prefix>_otel_metrics, and <prefix>_otel_spans are the telemetry tables for logs, metrics, and traces.
  • <prefix>_payload (the payload view) is a view over <prefix>_otel_logs. It selects the request and response rows that are written to the logs table.
  • The telemetry tables are created when telemetry is turned on.

Payload view columns​

The payload view has 12 columns, and the row output under Find one request shows each one.

  • client_request_id holds the request identifier that you can set in the request body.
  • databricks_request_id holds a request identifier that Databricks generates and attaches to each Model Serving request.
  • status_code holds the HTTP status code that the model returned.
  • logging_error_codes lists the errors that occurred when the data couldn't be logged.
  • request and response hold the raw JSON body that was sent to the endpoint, and the raw JSON body that the endpoint returned.
  • request_time is the time when the model server received the request.
  • sampling_fraction holds the rate that applied to the row.
  • The other columns are request_date, execution_duration_ms, served_entity_id, and requester.

Query the payload view​

You can query the payload view from Databricks SQL or a notebook. The steps in this section use a notebook, and each query is a Python cell that calls spark.sql. Run the cells in order in one notebook, because later cells use names that earlier cells define.

Find one request​

Each request has a client_request_id, and its row carries the same value.

  1. Define a helper that sends one request with a client_request_id. A query can get a 404 for a short time after READY, so the helper retries it.

    Python
    def query_endpoint(endpoint, client_request_id, body):
    """Sends one request with a client_request_id. Returns the reply, or the error's type and full text."""
    payload = {"client_request_id": client_request_id, **body}
    for _ in range(12):
    try:
    reply = w.api_client.do("POST", f"/serving-endpoints/{endpoint}/invocations", body=payload)
    return {"status": "ok", "reply": reply}
    except NotFound:
    time.sleep(10)
    except DatabricksError as e:
    return {"status": "error", "type": type(e).__qualname__, "text": str(e)}
    raise TimeoutError(f"{endpoint} returned NotFound for two minutes.")
  2. Send five requests with the cell below. Three return replies, and two return errors.

    Python
    REQUESTS = [
    ("rr-001", {"dataframe_records": [{"text": "hello 1"}]}),
    ("rr-002", {"dataframe_records": [{"text": "hello 2"}]}),
    ("rr-003", {"dataframe_records": [{"text": "hello 3"}]}),
    ("rr-bad-field-001", {"dataframe_records": [{"not_text": "hello"}]}),
    ("rr-model-error-001", {"dataframe_records": [{"text": "boom"}]}),
    ]
    CLIENT_IDS = [cid for cid, _ in REQUESTS]
    for cid, body in REQUESTS:
    result = query_endpoint(ENDPOINT_NAME, cid, body)
    if result["status"] == "ok":
    print(cid, result["status"], json.dumps(result["reply"]))
    else:
    print(cid, result["status"], result["type"], "|", result["text"])

    The cell prints the following:

    Text
    rr-001 ok {"predictions": [{"text": "hello 1"}]}
    rr-002 ok {"predictions": [{"text": "hello 2"}]}
    rr-003 ok {"predictions": [{"text": "hello 3"}]}
    rr-bad-field-001 error BadRequest | Failed to enforce schema of data ' not_text
    0 hello' with schema '['text': string (required)]'. Error: Model is missing inputs ['text']. Note that there were extra inputs: ['not_text'].
    rr-model-error-001 error BadRequest | Encountered an unexpected error while evaluating the model. Verify that the input is compatible with the model for inference. Error 'The model raised an error on purpose.'

    The request rr-bad-field-001 failed because the model was missing its text input, and the request sent not_text instead. The request rr-model-error-001 failed because the model raised an error while it evaluated the request, and the endpoint returned that error as a BadRequest.

  3. Wait for the rows. The cell polls the payload view with spark.sql until each client ID has a row, or until a time limit passes, and then prints how many client IDs have a row.

    Python
    PAYLOAD_TABLE = f"`{CATALOG}`.`{SCHEMA}`.`{PREFIX}_payload`" # Backticks keep names that have a hyphen valid in SQL.
    ID_LIST = ", ".join(f"'{cid}'" for cid in CLIENT_IDS)
    start = time.time()
    while True:
    rows = spark.sql(f"SELECT client_request_id FROM {PAYLOAD_TABLE} WHERE client_request_id IN ({ID_LIST})").collect()
    found = {row.client_request_id for row in rows}
    if len(found) == len(CLIENT_IDS) or time.time() - start > 20 * 60:
    break
    time.sleep(30)
    print("Client IDs with a row:", len(found))

    The cell prints the following:

    Text
    Client IDs with a row: 5

    All five client IDs have a row.

  4. Query the row for rr-001 with spark.sql, and print it as a dict.

    Python
    for row in spark.sql(f"SELECT * FROM {PAYLOAD_TABLE} WHERE client_request_id = 'rr-001'").collect():
    print(row.asDict())

    The cell prints the following:

    Text
    {'databricks_request_id': '<request-id>', 'request_date': datetime.date(2026, 11, 24), 'client_request_id': 'rr-001', 'request_time': datetime.datetime(2026, 11, 24, 22, 52, 27, 303999), 'status_code': 200, 'sampling_fraction': 1.0, 'execution_duration_ms': 2, 'request': '{"client_request_id": "rr-001", "dataframe_records": [{"text": "hello 1"}]}', 'response': '{"predictions": [{"text": "hello 1"}]}', 'served_entity_id': '<served-entity-id>', 'logging_error_codes': [], 'requester': '<user>'}

    The row shows a status_code of 200, and its request and response hold the JSON bodies.

Find failed requests by status code​

To find the requests whose status code isn't 200, run this cell, which calls spark.sql with a status_code != 200 filter. Requests that fail before they reach the model server have no row, so the filter doesn't find them.

Python
for row in spark.sql(f"SELECT client_request_id, status_code, logging_error_codes FROM {PAYLOAD_TABLE} WHERE status_code != 200").collect():
print(row.asDict())

The cell prints the following:

Text
{'client_request_id': 'rr-bad-field-001', 'status_code': 400, 'logging_error_codes': []}
{'client_request_id': 'rr-model-error-001', 'status_code': 400, 'logging_error_codes': []}

In the example, the filter returns two rows, and both have a status_code of 400 and an empty logging_error_codes list. Both rows match the two requests that returned errors in the send step.

Change the sampling rate​

Sampling logs a share of the requests, which lowers the logged volume on high-traffic endpoints and keeps a representative sample of traffic.

For CPU custom model serving endpoints, you can set the fraction of requests that are logged. The fraction is a number from 0 to 1, where 1 keeps every request. The default is 100 percent, so sampling doesn't leave out any request unless you set a lower rate.

Each request is kept with a probability equal to the fraction, so the logged rows are a random subset.

For details, see the sampling section of the inference tables page.

To change only the rate on an endpoint that already has inference tables, send a PATCH to /api/2.0/serving-endpoints/{name}/telemetry-config, where {name} is the endpoint name, and send only the sampling fraction. The cell below sets the rate to 0.5, waits for the update to finish, and reads the rate back.

Python
w.api_client.do(
"PATCH",
f"/api/2.0/serving-endpoints/{ENDPOINT_NAME}/telemetry-config",
body={"telemetry_config": {"inference_table_config": {"sampling_fraction": 0.5}}},
)
wait_until_ready(ENDPOINT_NAME)
print("inference_table_config:", json.dumps(get_endpoint(ENDPOINT_NAME).get("telemetry_config", {}).get("inference_table_config")))

The cell prints the following:

Text
state.ready=READY state.config_update=IN_PROGRESS
state.ready=READY state.config_update=NOT_UPDATING
inference_table_config: {"sampling_fraction": 0.5, "name": "<catalog>.<schema>.<prefix>_payload"}

A change to the rate starts a new deployment.

Delete the endpoint​

Optionally, delete the endpoint with the SDK call below.

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

The cell prints the following:

Text
Deleted endpoint: requests-demo

The four objects with the prefix remain in the schema after the endpoint is deleted.

Limitations​

  • A request that sampling leaves out is not logged.
  • Requests rejected before they reach the model server get no row.
  • The inference table doesn't log CSV requests.
  • Changing the table's schema or name, or deleting the table, can stop logging or corrupt the table.
  • A create request that sets a rate without table names is rejected for an endpoint that has no inference tables yet.

Additional resources​