Sub topic 6
What a feature table is
A feature table is a Delta table in Unity Catalog that stores computed features for machine learning. It has a primary key, so each row describes one entity, such as one user or one product. This chapter covers what makes a table a feature table, how to create one, and the errors you are most likely to hit.
This chapter assumes you know basic PySpark DataFrame operations, Delta tables, the catalog.schema.table naming in Unity Catalog, and the train, evaluate, and infer workflow of machine learning.
Why a feature table exists
Suppose you compute order_count_90d in a notebook, train a model, and then someone else writes a second version of that logic for the serving system. The two versions drift apart, and predictions degrade without any error. This problem is called training-serving skew.
A feature table addresses it by giving the feature values one stored, named home:
- Teams compute a feature once and reuse it across models.
- Training and inference read the same stored values.
- Unity Catalog permissions and lineage apply to the table, so access is governed.
- A model can be logged with references to the table, so features are retrieved by key at inference time.
The working model
A Unity Catalog feature table is an ordinary Delta table with a primary key constraint on one or more non-null key columns. There is no separate storage system. The key columns identify the entity, and the remaining columns are feature values.
You can create one with plain SQL:
CREATE TABLE main.ml.product_features (
product_id BIGINT NOT NULL,
category STRING,
avg_rating DOUBLE,
CONSTRAINT product_features_pk PRIMARY KEY (product_id)
);Two details matter here. The key column must be declared NOT NULL, because a primary key cannot contain nulls. The constraint is also informational in Unity Catalog. Delta does not reject duplicate keys on write, so your pipeline must guarantee uniqueness. Duplicate keys are the most common source of wrong results later (see the errors section).
The following diagram shows where the pieces sit.
Creating a feature table from a DataFrame
In practice you usually compute features with Spark first. This DataFrame aggregates orders into one row per user over the last 90 days:
from pyspark.sql import functions as F
orders = spark.table("main.sales.orders")
user_features_df = (
orders
.filter(F.col("order_ts") >= F.date_sub(F.current_date(), 90))
.groupBy("user_id")
.agg(
F.count("*").alias("order_count_90d"),
F.avg("amount").alias("avg_order_amount_90d"),
F.max("order_ts").alias("last_order_ts"),
)
)The groupBy("user_id") guarantees one row per user_id, which is exactly what a primary key requires. Now register the result as a feature table with FeatureEngineeringClient:
from databricks.feature_engineering import FeatureEngineeringClient
fe = FeatureEngineeringClient()
fe.create_table(
name="main.ml.user_features",
primary_keys=["user_id"],
df=user_features_df,
description="Per-user order features over the last 90 days",
)
# Later runs update existing rows and insert new ones.
fe.write_table(
name="main.ml.user_features",
df=user_features_df,
mode="merge",
)create_table builds the table from the schema of df, sets the primary key, and writes the rows. write_table with mode="merge" matches rows on the primary key. It updates rows that exist and inserts rows that do not. The chapter on writing feature data covers the write modes in more detail.
The table name uses three parts: catalog, schema, table. You need USE CATALOG and USE SCHEMA on the parents and CREATE TABLE on the schema to create it.
Feature table versus a plain Delta table
| Aspect | Plain Delta table | Feature table |
|---|---|---|
| Storage | Delta | Delta (same) |
| Primary key | Optional | Required, non-null |
| Lookup by key at inference | Not supported by models | Supported through feature lookups |
| Time series column | No concept | Optional, enables point-in-time joins |
| Appears in feature lineage | As a table only | As a feature source for models |
Because a feature table is still Delta, you can query it with SQL, use time travel, and apply the same grants as any other table.
Choosing what goes in a feature table
Keep these rules in mind when you design the table:
- One table describes one entity. Put user features in a user table and product features in a product table. Do not mix grains.
- Every row is identified by the primary key and nothing else. If the same user can legitimately have many rows, you need a time series column (covered in the next chapter).
- Store features, not labels. Labels belong in a separate table, so that one feature table can serve many models.
- Store computed values, not raw events. The feature table is the output of a Spark job, not the input.
- Choose column names that stand alone, such as
order_count_90d. The window in the name prevents later confusion about what the value means.
Common errors
- Null in a key column. Creating a table from a DataFrame whose key column contains nulls fails. Filter the nulls out or fix the join upstream.
- Duplicate keys. The constraint is not enforced, so duplicates are written silently. A later lookup can then return an arbitrary row or multiply rows in a join. Check with a count before writing:
dupes = (
user_features_df
.groupBy("user_id")
.count()
.filter("count > 1")
)
assert dupes.count() == 0, "user_id must be unique"- Missing permissions.
PERMISSION_DENIEDordoes not existerrors usually mean you lackUSE CATALOG,USE SCHEMA, orCREATE TABLE. The error can look like a missing table when it is really a missing grant. - Creating a table that already exists.
create_tablefails if the name is taken. Usewrite_tableto add data to an existing table. - Schema changes. Adding a column later requires an explicit schema change on the table. Writing a DataFrame with extra columns to an existing table does not add them automatically.
Checking your result
After creating the table, confirm its shape and key:
spark.sql("DESCRIBE TABLE EXTENDED main.ml.user_features").show(truncate=False)
spark.table("main.ml.user_features").limit(5).show()The extended description lists the columns and, in the table information, the primary key constraint. If the constraint is absent, the table was created as a plain Delta table and models cannot use it for lookups.
Exercise
A teammate creates a Delta table of user features with a user_id column but no primary key constraint, then asks why a feature lookup cannot use it. Separately, they find that two rows share one user_id in a table that does have the constraint. Explain both problems and the fix for each.
Show answer
The first table is a plain Delta table. Feature lookups need a primary key on non-null key columns, so the table must declare user_id as NOT NULL with a PRIMARY KEY constraint (or be created with fe.create_table(..., primary_keys=["user_id"])). The second problem exists because Unity Catalog primary keys are informational and do not reject duplicates. The fix is to make the writing job produce unique keys, for example by aggregating with groupBy("user_id") or deduplicating, and to assert uniqueness before each write.