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
textcolumn. The notebook registers an example model that returns each text unchanged and raises an error on the textboom. - 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.
-
Install the packages, and restart Python.
Python%pip install -U "databricks-sdk" "mlflow>=3" pandasdbutils.library.restartPython()The cell installs
databricks-sdk,mlflow, andpandas, and prints pip dependency warnings that don't stop the install. -
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.
-
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.Pythonimport mlflowimport pandas as pdfrom mlflow.models import infer_signatureclass 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_inputmlflow.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:
TextRegistered <catalog>.<schema>.requests_demo_model version 1If a model of that name already exists, the cell adds a version to it.
-
Import the client, and define a helper that reads an endpoint and one that waits for READY.
Pythonimport jsonimport timefrom databricks.sdk import WorkspaceClientfrom databricks.sdk.errors import DatabricksError, NotFoundw = 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, Falsewhile 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 = currentif current[1] == "IN_PROGRESS":seen_update = Trueif current == ("READY", "NOT_UPDATING"):return time.time() - start, seen_updateif time.time() - start > timeout_s:raise TimeoutError(f"{endpoint} was not READY after {timeout_s} seconds")time.sleep(every_s) -
Create the endpoint. The request goes to
POST /api/2.0/serving-endpoints, and it setstelemetry_configwith the three telemetry table names and aninference_table_configwithsampling_fractionset to 1.0.Pythoncreate_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:
TextCreated endpoint: requests-demo -
Wait for the endpoint to report READY, and then print its telemetry config. The wait prints each change of state.
Pythonwait_until_ready(ENDPOINT_NAME)print("telemetry_config on the endpoint:", json.dumps(get_endpoint(ENDPOINT_NAME).get("telemetry_config")))The cell prints the following:
Textstate.ready=NOT_READY state.config_update=IN_PROGRESSstate.ready=READY state.config_update=NOT_UPDATINGtelemetry_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_confignames the payload view and showssampling_fractionas 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_spansare 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_idholds the request identifier that you can set in the request body.databricks_request_idholds a request identifier that Databricks generates and attaches to each Model Serving request.status_codeholds the HTTP status code that the model returned.logging_error_codeslists the errors that occurred when the data couldn't be logged.requestandresponsehold the raw JSON body that was sent to the endpoint, and the raw JSON body that the endpoint returned.request_timeis the time when the model server received the request.sampling_fractionholds the rate that applied to the row.- The other columns are
request_date,execution_duration_ms,served_entity_id, andrequester.
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.
-
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.Pythondef 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.") -
Send five requests with the cell below. Three return replies, and two return errors.
PythonREQUESTS = [("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:
Textrr-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_text0 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-001failed because the model was missing itstextinput, and the request sentnot_textinstead. The requestrr-model-error-001failed because the model raised an error while it evaluated the request, and the endpoint returned that error as a BadRequest. -
Wait for the rows. The cell polls the payload view with
spark.sqluntil each client ID has a row, or until a time limit passes, and then prints how many client IDs have a row.PythonPAYLOAD_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:breaktime.sleep(30)print("Client IDs with a row:", len(found))The cell prints the following:
TextClient IDs with a row: 5All five client IDs have a row.
-
Query the row for
rr-001withspark.sql, and print it as a dict.Pythonfor 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_codeof 200, and itsrequestandresponsehold 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.
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:
{'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.
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:
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.
w.serving_endpoints.delete(ENDPOINT_NAME)
print("Deleted endpoint:", ENDPOINT_NAME)
The cell prints the following:
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.