Sub topic 14
Keeping features fresh with scheduled pipelines
This chapter assumes you can write PySpark aggregations, you know how to create and merge into a Unity Catalog feature table, and you know what a Databricks job is. It covers how to turn a one-off feature computation into a repeatable pipeline, and how to check that the features are still current.
Why freshness matters
A feature table is a snapshot of derived values. The source data keeps changing, so the snapshot ages. A feature such as order_count_90d that was last computed three weeks ago will give a model inputs that no longer match reality.
Freshness is the age of the newest data in the feature table, compared with what the model needs. The requirement differs by use case:
- A weekly churn model can tolerate features that are a day old.
- A fraud model that scores each transaction may need features that are minutes old.
Decide the freshness target first. It determines the schedule, the compute, and whether you need online serving.
The shape of a feature pipeline
A feature pipeline is a job that repeats four steps on a schedule:
- Read the source tables.
- Compute the features, using the same code every run.
- Write the result to the feature table with
merge. - Check that the write actually produced fresh data.
Writing the pipeline notebook
Keep the feature logic in one function. Training code and the scheduled job should both call it, because that is how you avoid training-serving skew. The example below adds a computed_at column so that freshness can be measured from the data itself.
from databricks.feature_engineering import FeatureEngineeringClient
from pyspark.sql import functions as F
fe = FeatureEngineeringClient()
FEATURE_TABLE = "main.ml.user_features"
def compute_user_features():
orders = spark.table("main.sales.orders")
return (
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"),
)
.withColumn("computed_at", F.current_timestamp())
)
features_df = compute_user_features()
if spark.catalog.tableExists(FEATURE_TABLE):
fe.write_table(name=FEATURE_TABLE, df=features_df, mode="merge")
else:
fe.create_table(
name=FEATURE_TABLE,
primary_keys=["user_id"],
df=features_df,
description="Per-user order features over the last 90 days",
)The tableExists branch makes the first run create the table and later runs merge into it. This keeps the notebook usable in a fresh environment, such as a new workspace or a test catalog.
Make runs idempotent
An idempotent job gives the same table state if you run it twice. merge on the primary key has this property: a rerun updates the same rows instead of adding duplicates. Because of this, you can safely retry a failed run or backfill by rerunning the job.
Plain append writes do not have this property. On a table with a primary key, duplicate keys also break the one-row-per-key assumption that lookups rely on.
Scheduling the job
Create a Databricks job with a notebook task and attach a trigger. The settings below use a cron schedule. The quartz_cron_expression field uses Quartz syntax, which has a seconds field first.
{
"name": "refresh_user_features",
"tasks": [
{
"task_key": "compute_and_merge",
"notebook_task": {
"notebook_path": "/Repos/ml/features/refresh_user_features"
}
}
],
"schedule": {
"quartz_cron_expression": "0 0 2 * * ?",
"timezone_id": "UTC",
"pause_status": "UNPAUSED"
},
"max_concurrent_runs": 1
}This runs at 02:00 UTC every day. Setting max_concurrent_runs to 1 stops a slow run from overlapping the next one. Two overlapping merges on the same table can conflict. Compute settings depend on your workspace, so add a cluster or use serverless as your environment requires.
Cron is not the only trigger. Choose by how the source data arrives:
| Trigger | Use it when | Trade-off |
|---|---|---|
| Scheduled (cron) | Sources update on a known cadence | Simple, but wastes a run if nothing changed |
| Table update | Run when an upstream Unity Catalog table changes | Fresher, but can fire often on busy tables |
| File arrival | Raw files land in a volume or external location | Needs a clear landing path |
| Continuous | Minutes-level freshness | Always-on compute cost |
Measuring freshness
A job that succeeds can still leave stale features. The source table might not have updated, or the filter might have matched nothing. Add a final check that fails the job when the table is too old.
stale = (
spark.table(FEATURE_TABLE)
.agg(
F.expr(
"max(computed_at) < current_timestamp() - INTERVAL 26 HOURS"
).alias("is_stale")
)
.first()["is_stale"]
)
if stale:
raise RuntimeError(f"{FEATURE_TABLE} is older than 26 hours")A 26-hour limit on a daily job leaves two hours of slack for slow runs. A failed job triggers whatever notification you set on the job, such as email or a webhook. Without the check, the table would age without any signal.
Comparing inside Spark avoids time zone mistakes that come from converting the timestamp to a Python datetime.
Edge cases
Rows that drop out of the window
merge updates and inserts, but it never deletes. Suppose a user placed orders 100 days ago and none since. They no longer appear in compute_user_features(), because the 90-day filter removes their orders. Their row in the feature table keeps the old values, and its computed_at falls further behind each day.
You have three options:
- Compute features for every user, so that users with no recent orders get
order_count_90d = 0. This is usually the most correct choice. - Use
mode="overwrite"so the table matches the latest computation exactly. The DataFrame schema must match the table. - Leave the stale rows, and have the consumer discard rows whose
computed_atis too old.
Late-arriving source data
If the job runs at 02:00 but an upstream load finishes at 03:00, your features miss the last day of orders. Fix this by ordering the pipelines with job task dependencies, or by using a table update trigger on the upstream table. Do not simply move your schedule later and hope.
Time series feature tables
For tables with a time series column, each run should add rows with a new timestamp, keyed on user_id and feature_ts. Merging with a new timestamp inserts rows. Merging with an existing timestamp overwrites that point in time. Be sure which of the two you intend before you backfill, because overwriting history can change past training sets.
Online serving
If an online table is synced from your feature table, it is only as fresh as the last successful merge plus the sync delay. The pipeline schedule sets the upper limit on online freshness. Check the current Databricks documentation for the sync requirements on your table, such as change data feed.
Common errors
- Schedule drift: the job succeeds but nothing validates the output. Add the freshness check.
- Duplicate logic: the notebook and the training code compute features differently. Share one function.
- Overlapping runs: concurrent merges fail or conflict. Set
max_concurrent_runsto 1. - Silent stale rows: merge never removes entities. Handle the dropout case explicitly.
Exercise
A daily job merges 90-day order features into main.ml.user_features. A user last ordered 120 days ago. After the job has run for a week, what does that user's row contain, and what is one way to fix it?
Show answer
The row keeps the values from the last run in which the user had orders inside the window, and its computed_at stops advancing. merge only updates and inserts, and the user no longer appears in the computed DataFrame. Fixes: compute features for all users so inactive ones get zero counts, use mode="overwrite", or filter on computed_at when reading.