---
title: Serve feature tables
description: Serve feature tables from Unity Catalog for real-time access using Feature Serving endpoints backed by a FeatureSpec, for models and applications.
canonical_url: https://docs.databricks.com/gcp/en/machine-learning/feature-store/feature-function-serving
---

# Serve feature tables

Feature tables can be served in two ways:

* **Model serving**: Deploy a model that was trained on feature tables. The same endpoint is used for both feature lookup and model inference. The endpoint [looks up or computes feature values automatically](https://docs.databricks.com/gcp/en/machine-learning/feature-store/automatic-feature-lookup.md), using the lineage tracked when the model was logged. Use this to serve model predictions.
* **Feature Serving**: Deploy a [`FeatureSpec`](https://docs.databricks.com/gcp/en/machine-learning/feature-store/concepts.md#featurespec) that references feature tables directly, without a model. The endpoint returns the requested feature outputs. Use this when an application needs feature values rather than model predictions. If you ultimately are using features for model inference, Databricks recommends using model serving directly.

Both approaches support precomputed and on-demand features.

## <a id="requirement" />Requirements

* Databricks Runtime 14.2 ML or above.
* To use the Python API, Feature Serving requires `databricks-feature-engineering` version 0.1.2 or above, which is built into Databricks Runtime 14.2 ML. For earlier Databricks Runtime ML versions, manually install the required version using `%pip install databricks-feature-engineering>=0.1.2`. If you are using a Databricks notebook, you must then restart the Python kernel by running this command in a new cell: `dbutils.library.restartPython()`.
* To use the Databricks SDK, Feature Serving requires `databricks-sdk` version 0.18.0 or above. To manually install the required version, use `%pip install databricks-sdk>=0.18.0`. If you are using a Databricks notebook, you must then restart the Python kernel by running this command in a new cell: `dbutils.library.restartPython()`.

Databricks Feature Serving provides a UI and several programmatic options for creating, updating, querying, and deleting endpoints. This article includes instructions for each of the following options:

* Databricks UI
* REST API
* Python API
* Databricks SDK

To use the REST API or MLflow Deployments SDK, you must have a Databricks API token.

## Authentication for Feature Serving

For information about authentication, see [Authorize access to Databricks resources](https://docs.databricks.com/gcp/en/dev-tools/auth/index.md).

## <a id="create-a-featurespec" />Create a `FeatureSpec`

A `FeatureSpec` is a user-defined set of features and functions. You can combine features and functions in a `FeatureSpec`. `FeatureSpecs` are stored in and managed by Unity Catalog and appear in Catalog Explorer.

The tables specified in a `FeatureSpec` must be published to an online feature store or a third-party online store. See [Databricks Online Feature Stores](https://docs.databricks.com/gcp/en/machine-learning/feature-store/online-feature-store.md).

Create a `FeatureSpec` with the `databricks-feature-engineering` package, as the following example does, or declare one in a bundle. See [feature\_spec](https://docs.databricks.com/gcp/en/dev-tools/bundles/resources.md#feature_specs).

First, define the function:

```python
from unitycatalog.ai.core.databricks import DatabricksFunctionClient

client = DatabricksFunctionClient()

CATALOG = "main"
SCHEMA = "default"

def difference(num_1: float, num_2: float) -> float:
  """
  A function that accepts two floating point numbers, subtracts the second one
  from the first, and returns the result as a float.

  Args:
      num_1 (float): The first number.
      num_2 (float): The second number.

  Returns:
      float: The resulting difference of the two input numbers.
  """
  return num_1 - num_2

client.create_python_function(
  func=difference,
  catalog=CATALOG,
  schema=SCHEMA,
  replace=True
)
```

Then you can use the function in a `FeatureSpec`:

```python
from databricks.feature_engineering import (
  FeatureFunction,
  FeatureLookup,
  FeatureEngineeringClient,
)

fe = FeatureEngineeringClient()

features = [
  # Lookup column `average_yearly_spend` and `country` from a table in UC by the input `user_id`.
  FeatureLookup(
    table_name="main.default.customer_profile",
    lookup_key="user_id",
    feature_names=["average_yearly_spend", "country"]
  ),
  # Calculate a new feature called `spending_gap` - the difference between `ytd_spend` and `average_yearly_spend`.
  FeatureFunction(
    udf_name="main.default.difference",
    output_name="spending_gap",
    # Bind the function parameter with input from other features or from request.
    # The function calculates num_1 - num_2.
    input_bindings={"num_1": "ytd_spend", "num_2": "average_yearly_spend"},
  ),
]

# Create a `FeatureSpec` with the features defined above.
# The `FeatureSpec` can be accessed in Unity Catalog as a function.
fe.create_feature_spec(
  name="main.default.customer_features",
  features=features,
)
```

### Specify default values

To specify default values for features, use the `default_values` parameter in the `FeatureLookup`. See the following example:

```python
feature_lookups = [
    FeatureLookup(
        table_name="ml.recommender_system.customer_features",
        feature_names=[
            "membership_tier",
            "age",
            "page_views_count_30days",
        ],
        lookup_key="customer_id",
        default_values={
          "age": 18,
          "membership_tier": "bronze"
        },
    ),
]
```

If the feature columns are renamed using the `rename_outputs` parameter, `default_values` must use the renamed feature names.

```python
FeatureLookup(
  table_name = 'main.default.table',
  feature_names = ['materialized_feature_value'],
  lookup_key = 'id',
  rename_outputs={"materialized_feature_value": "feature_value"},
  default_values={
    "feature_value": 0
  }
)
```

## <a id="python-dependencies" />Add Python dependencies

If a user-defined function (UDF) imports Python packages, declare them when you create the `FeatureSpec`. The `extra_pip_requirements` parameter requires `databricks-feature-engineering` version 0.17.0 or above. Feature Serving installs the MLflow and `databricks-feature-lookup` packages automatically.

For example, if a UDF in your feature spec imports NumPy, add the requirement to the spec:

```python
fe.create_feature_spec(
    name="main.default.customer_features_with_dependencies",
    features=features,
    extra_pip_requirements=["numpy==1.26.4"],
)
```

Use `main.default.customer_features_with_dependencies` as the spec name when you [create the endpoint](https://docs.databricks.com/gcp/en/machine-learning/feature-store/feature-function-serving.md#create-an-endpoint).

Each entry in `extra_pip_requirements` must be a PyPI requirement string, such as `numpy==1.26.4`, or a path to a `.whl` file in a Unity Catalog volume. For example, use `/Volumes/main/libraries/wheels/custom_features-1.0.0-py3-none-any.whl` for a wheel you have uploaded. The endpoint creator must have `READ VOLUME` on the volume and `USE CATALOG` and `USE SCHEMA` on its parent catalog and schema.

For packages from a private repository, configure the [workspace default package repository](https://docs.databricks.com/gcp/en/admin/workspace-settings/default-package-repositories.md). Do not put pip command options, such as `--index-url`, in `extra_pip_requirements`.

Dependencies in a Unity Catalog UDF's `ENVIRONMENT` clause apply to offline SQL execution. Feature Serving does not copy them automatically. Declare every package needed by the UDFs, including UDFs in upstream features, in the feature spec's requirements.

If endpoint deployment fails, inspect the build logs for package installation errors, version conflicts, or wheel access failures. See [Monitor model quality and endpoint health](https://docs.databricks.com/gcp/en/machine-learning/model-serving/monitor-diagnose-endpoints.md).

For an example with `CustomUDF` and `FeatureViewSource`, see [Serve CustomUDF features and their dependencies](https://docs.databricks.com/gcp/en/machine-learning/feature-store/serve-declarative-features.md#serve-derived-features). For model serving dependencies, see [Custom UDF dependencies](https://docs.databricks.com/gcp/en/machine-learning/feature-store/train-with-declarative-features.md#custom-udf-dependencies).

## Create an endpoint

The `FeatureSpec` defines the endpoint. For more information, see [Create custom model serving endpoints](https://docs.databricks.com/gcp/en/machine-learning/model-serving/create-manage-serving-endpoints.md), [the Python API documentation](https://api-docs.databricks.com/python/feature-engineering/latest/ml_features.endpoint_core_config.html), or the [Databricks SDK documentation](https://github.com/databricks/databricks-sdk-py/blob/e290be90ac0bcf8d01207f8186bc757890c75a09/databricks/sdk/service/serving.py#L159) for details.

> [!NOTE]
>
> For workloads that are latency sensitive or require high queries per second, Model Serving offers route optimization on custom model serving endpoints, see [Route optimization on serving endpoints](https://docs.databricks.com/gcp/en/machine-learning/model-serving/route-optimization.md).

### Databricks SDK - Python

```python
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import EndpointCoreConfigInput, ServedEntityInput

workspace = WorkspaceClient()

# Create endpoint
workspace.serving_endpoints.create(
  name="my-serving-endpoint",
  config = EndpointCoreConfigInput(
    served_entities=[
    ServedEntityInput(
        entity_name="main.default.customer_features",
        scale_to_zero_enabled=True,
        workload_size="Small"
      )
    ]
  )
)
```

### Python API

```python
from databricks.feature_engineering.entities.feature_serving_endpoint import (
  ServedEntity,
  EndpointCoreConfig,
)

fe.create_feature_serving_endpoint(
  name="customer-features",
    config=EndpointCoreConfig(
    served_entities=ServedEntity(
      feature_spec_name="main.default.customer_features",
             workload_size="Small",
             scale_to_zero_enabled=True,
             instance_profile_arn=None,
    )
  )
)
```

### REST API

```bash
curl -X POST -u token:$DATABRICKS_API_TOKEN ${WORKSPACE_URL}/api/2.0/serving-endpoints \
    -H 'Content-Type: application/json' \
    -d '"name": "customer-features",
   "config": {
       "served_entities": [
           {
               "entity_name": "main.default.customer_features",
               "workload_size": "Small",
               "scale_to_zero_enabled": true
           }
       ]
   }'
```

To see the endpoint, click **Serving** in the left sidebar of the Databricks UI. When the state is **Ready**, the endpoint is ready to respond to queries. To learn more about Model Serving, see [Model Serving](https://docs.databricks.com/gcp/en/machine-learning/model-serving/index.md).

## Get an endpoint

You can use the Databricks SDK or the Python API to get the metadata and status of an endpoint.

### Databricks SDK - Python

```python
from databricks.sdk import WorkspaceClient
workspace = WorkspaceClient()

endpoint = workspace.serving_endpoints.get(name="customer-features")
# print(endpoint)
```

### Python API

```python
endpoint = fe.get_feature_serving_endpoint(name="customer-features")
# print(endpoint)
```

## Get the schema of an endpoint

You can use the Databricks SDK or the REST API to get the schema of an endpoint. For more information about the endpoint schema, see [Get a model serving endpoint schema](https://docs.databricks.com/gcp/en/machine-learning/model-serving/manage-serving-endpoints.md#get-schema).

### Databricks SDK - Python

```python
from databricks.sdk import WorkspaceClient
workspace = WorkspaceClient()

# Create endpoint
endpoint = workspace.serving_endpoints.get_open_api(name="customer-features")
```

### REST API

```bash
ACCESS_TOKEN=<token>
ENDPOINT_NAME=<endpoint name>

curl "https://example.databricks.com/api/2.0/serving-endpoints/$ENDPOINT_NAME/openapi" -H "Authorization: Bearer $ACCESS_TOKEN" -H "Content-Type: application/json"
```

## <a id="query-an-endpoint" />Query an endpoint

You can use the REST API, the MLflow Deployments SDK, or the Serving UI to query an endpoint.

The following code shows how to set up credentials and create the client when using the MLflow Deployments SDK.

```
  # Set up credentials
  export DATABRICKS_HOST=...
  export DATABRICKS_TOKEN=...
```

```python
  # Set up the client
  import mlflow.deployments

  client = mlflow.deployments.get_deploy_client("databricks")
```

> [!NOTE]
>
> As a security best practice, when you authenticate with automated tools, systems, scripts, and apps, Databricks recommends that you use personal access tokens belonging to [service principals](https://docs.databricks.com/gcp/en/admin/users-groups/service-principals.md) instead of workspace users. To create tokens for service principals, see [Manage tokens for a service principal](https://docs.databricks.com/gcp/en/admin/users-groups/manage-service-principals.md#tokens).

### Query an endpoint using APIs

This section includes examples of querying an endpoint using the REST API or the MLflow Deployments SDK.

#### MLflow Deployments SDK

> [!IMPORTANT]
>
> The following example uses the `predict()` API from the [MLflow Deployments SDK](https://mlflow.org/docs/latest/python_api/mlflow.deployments.html#mlflow.deployments.DatabricksDeploymentClient.predict). This API is [Experimental](https://docs.databricks.com/gcp/en/release-notes/release-types.md) and the API definition might change.

```python
import mlflow.deployments

client = mlflow.deployments.get_deploy_client("databricks")
response = client.predict(
    endpoint="test-feature-endpoint",
    inputs={
        "dataframe_records": [
            {"user_id": 1, "ytd_spend": 598},
            {"user_id": 2, "ytd_spend": 280},
        ]
    },
)
```

#### REST API

```bash
curl -X POST -u token:$DATABRICKS_API_TOKEN $ENDPOINT_INVOCATION_URL \
  -H 'Content-Type: application/json' \
  -d '{"dataframe_records": [
          {"user_id": 1, "ytd_spend": 598},
          {"user_id": 2, "ytd_spend": 280}
      ]}'
```

### Query an endpoint using the UI

You can query a serving endpoint directly from the Serving UI. The UI includes generated code examples that you can use to query the endpoint.

1. In the left sidebar of the Databricks workspace, click **Serving**.

2. Click the endpoint you want to query.

3. In the upper-right of the screen, click **Query endpoint**.

   ![query endpoint button](https://docs.databricks.com/gcp/en/images/machine-learning/feature-store/query-endpoint-button.png)

4. In the **Request** box, type the request body in JSON format.

5. Click **Send request**.

```json
// Example of a request body.
{
  "dataframe_records": [
    { "user_id": 1, "ytd_spend": 598 },
    { "user_id": 2, "ytd_spend": 280 }
  ]
}
```

The **Query endpoint** dialog includes generated example code in curl, Python, and SQL. Click the tabs to view and copy the example code.

![query endpoint dialog](https://docs.databricks.com/gcp/en/images/machine-learning/feature-store/query-endpoint-dialog.png)

To copy the code, click the copy icon in the upper-right of the text box.

![copy button in query endpoint dialog](https://docs.databricks.com/gcp/en/images/machine-learning/feature-store/query-endpoint-dialog-with-code.png)

## <a id="update-an-endpoint" />Update an endpoint

> [!IMPORTANT]
>
> To modify a Feature Serving endpoint's configuration (such as changing the `FeatureSpec` or workload size), always use the update APIs described in this section. Do not delete and recreate the endpoint to apply changes. Deleting a live endpoint causes immediate downtime and interrupts all applications that query it.

You can update an endpoint using the REST API, the Databricks SDK, or the Serving UI.

### Update an endpoint using APIs

#### Databricks SDK - Python

```python
from databricks.sdk import WorkspaceClient
workspace = WorkspaceClient()

workspace.serving_endpoints.update_config(
  name="my-serving-endpoint",
  served_entities=[
    ServedEntityInput(
      entity_name="main.default.customer_features",
      scale_to_zero_enabled=True,
      workload_size="Small"
    )
  ]
)
```

#### REST API

```bash
curl -X PUT -u token:$DATABRICKS_API_TOKEN ${WORKSPACE_URL}/api/2.0/serving-endpoints/<endpoint_name>/config \
  -H 'Content-Type: application/json' \
  -d '"served_entities": [
        {
            "name": "customer-features",
            "entity_name": "main.default.customer_features_new",
            "workload_size": "Small",
            "scale_to_zero_enabled": True
        }
    ]'
```

### Update an endpoint using the UI

Follow these steps to use the Serving UI:

1. In the left sidebar of the Databricks workspace, click **Serving**.
2. In the table, click the name of the endpoint you want to update. The endpoint screen appears.
3. In the upper-right of the screen, click **Edit endpoint**.
4. In the **Edit serving endpoint** dialog, edit the endpoint settings as needed.
5. Click **Update** to save your changes.

![update an endpoint](https://docs.databricks.com/gcp/en/images/machine-learning/feature-store/update-endpoint.png)

## <a id="update-dependencies" />Update dependencies of a live Feature Serving endpoint

A Feature Serving endpoint resolves its dependencies when it is first built and deployed: the privileges its service principal needs to read the online table (`USE CATALOG`, `USE SCHEMA`, and `SELECT`), and `EXECUTE` on the Unity Catalog UDF described in its `FeatureSpec`. The endpoint fixes these permissions at build time and doesn't re-resolve them on a plain redeploy or restart. If you recreate the online table or UDF, the endpoint loses permission on it. If you update the UDF in place, the endpoint keeps running the original version. Feature lookups can fail, or silently use the old UDF logic, even while the endpoint continues to report **Ready**.

For both online tables and on-demand UDFs, Databricks recommends a versioned migration: create a new version of the dependency, create a new endpoint against it, and migrate traffic to the new endpoint. This helps you avoid downtime and the failure modes described in this section.

### Recreate an online table

> [!WARNING]
>
> Don't delete and recreate an online table in place under a live Feature Serving endpoint.

When you create an endpoint, Model Serving grants the endpoint's service principal `USE CATALOG` on the online table's catalog, `USE SCHEMA` on its schema, and `SELECT` on the online table. Deleting and recreating the table, even with the same name, creates a new securable in Unity Catalog, so the `SELECT` grant doesn't carry over. The service principal loses access to the table, OAuth token minting fails, and the connection to the online store falls back to password authentication and fails. Feature lookups then fail with errors such as `KeyError: 'OAUTH_TOKEN'` or `password authentication failed`.

These failures are easy to miss: the endpoint still reports **Ready** and the sync pipeline still shows successful runs, while lookups fail. Changing an online table's sync mode (for example, between `CONTINUOUS` and `SNAPSHOT`) can't be done in place and requires recreating the table, which can trigger this problem as well.

An endpoint doesn't read a specific online table. It looks up features through the offline feature table named in its `FeatureSpec`, and when a feature table is published to more than one online table, the endpoint uses the oldest one. Publishing the same feature table to a second online table doesn't move an endpoint to the new online table. See [Online Feature Store limitations](https://docs.databricks.com/gcp/en/machine-learning/feature-store/online-feature-store.md#limitations).

To minimize downtime, version the offline feature table as well as the online table:

1. Create a new offline feature table, and include the version in its name (for example, `customer_features_v2`).
2. Publish the new feature table to a new online table. See [Publish a feature table](https://docs.databricks.com/gcp/en/machine-learning/feature-store/online-feature-store.md#publish-a-feature-table).
3. Create a new `FeatureSpec` that uses the new feature table, and create a new Feature Serving endpoint that serves it.
4. Migrate traffic to the new endpoint. After the old endpoint no longer receives traffic, delete it and its online table.

### Update an on-demand UDF

> [!WARNING]
>
> Don't modify a Unity Catalog UDF used by a `FeatureSpec` in place.

A `FeatureSpec`'s on-demand UDF is built into the serving endpoint at deployment time. A plain refresh or redeploy reuses the same UDF in that serving image. An in-place update to the UDF under the same name doesn't take effect. If you drop and recreate the UDF, the endpoint also loses `EXECUTE` on it, so lookups that use the UDF fail.

`FeatureSpec`s and UDFs have no version field, so version by name: create a new UDF and a new `FeatureSpec`, create a new endpoint that uses the new `FeatureSpec`, and migrate traffic to it. See [Create a `FeatureSpec`](https://docs.databricks.com/gcp/en/machine-learning/feature-store/feature-function-serving.md#create-a-featurespec).

See [On-demand feature computation](https://docs.databricks.com/gcp/en/machine-learning/feature-store/on-demand-features-gcp.md).

### Recover an endpoint after an in-place change

If you already changed a dependency in place, rebuild the endpoint so that it re-resolves its dependencies. Create a new `FeatureSpec` (or, for a Model Serving endpoint, register a new model version), and [update the endpoint](https://docs.databricks.com/gcp/en/machine-learning/feature-store/feature-function-serving.md#update-an-endpoint) to serve it. Changing what the endpoint serves rebuilds the endpoint, which provisions a new service principal and re-runs permission setup. None of these reliably rebuild the endpoint: stopping and starting it, a plain redeploy, or changing an environment variable.

## Delete an endpoint

> [!WARNING]
>
> This action is irreversible. Deleting a Feature Serving endpoint causes immediate downtime for any applications querying it. If you want to change the endpoint's configuration, use [Update an endpoint](https://docs.databricks.com/gcp/en/machine-learning/feature-store/feature-function-serving.md#update-an-endpoint) instead of deleting and recreating the endpoint.

You can delete an endpoint using the REST API, the Databricks SDK, the Python API, or the Serving UI.

### Delete an endpoint using APIs

#### Databricks SDK - Python

```python
from databricks.sdk import WorkspaceClient
workspace = WorkspaceClient()

workspace.serving_endpoints.delete(name="customer-features")
```

#### Python API

```python
fe.delete_feature_serving_endpoint(name="customer-features")
```

#### REST API

```bash
curl -X DELETE -u token:$DATABRICKS_API_TOKEN ${WORKSPACE_URL}/api/2.0/serving-endpoints/<endpoint_name>
```

### Delete an endpoint using the UI

Follow these steps to delete an endpoint using the Serving UI:

1. In the left sidebar of the Databricks workspace, click **Serving**.
2. In the table, click the name of the endpoint you want to delete. The endpoint screen appears.
3. In the upper-right of the screen, click the kebab menu ![Kebab menu icon.](https://docs.databricks.com/gcp/en/images/product-icons/OverflowIcon.svg) and select **Delete**.

![delete an endpoint](https://docs.databricks.com/gcp/en/images/machine-learning/feature-store/delete-endpoint.png)

## Monitor the health of an endpoint

For information about the logs and metrics available for Feature Serving endpoints, see [Monitor model quality and endpoint health](https://docs.databricks.com/gcp/en/machine-learning/model-serving/monitor-diagnose-endpoints.md).

## Access control

For information about permissions on Feature Serving endpoints, see [Manage permissions on a model serving endpoint](https://docs.databricks.com/gcp/en/machine-learning/model-serving/manage-serving-endpoints.md#permissions).

## Example notebook

This notebook illustrates how to use the Databricks SDK to create a Feature Serving endpoint using Databricks Online Feature Store.

#### Feature Serving example notebook with online store

[Get notebook](https://docs.databricks.com/notebooks/source/machine-learning/feature-function-serving-online-store-dbsdk.html)
