How to Set Up a Feature Store With Feast on Kubernetes So Training and Serving Share One Feature Definition

By KP  |  TZoneLabs  |  DevOps & Cloud Engineering

Keep your feature definitions in one Git repository and register them with Feast. Training reads them with get_historical_features, which does a point-in-time join so a row never sees data from after its own timestamp. Serving reads them with get_online_features from Redis, which a scheduled job fills from the same data. Run feast plan in merge requests and feast apply on merge, the way you would run Terraform. Feast stores and serves features. It does not compute them, and that part is still your batch job.

This is the how-to that follows our incident story about a feature that peeked into the future. The fix there was to define each feature once and share it between training and serving. This post shows one way to build that on Kubernetes. It builds on Part 2 (versioning), Part 4 (serving) and Part 6 (the pipeline).

As in the rest of the series, each concept below is lined up against the DevOps task it mirrors, since reasoning from something you already run is the fastest way into an unfamiliar tool.

What Maps to What

Feature Store Concept DevOps Equivalent
Feature definitions in a repo Infrastructure code kept as the single source of truth
feast plan and feast apply terraform plan and terraform apply
Registry Terraform state
Offline store The log archive or data warehouse you query for history
Online store A Redis cache in front of a database
Materialization job A cache warmer or scheduled sync job
Point-in-time join Running a metrics query as of a past timestamp
Feature TTL Cache TTL

Do You Need One?

Probably not yet if you have one model and one team. In that case, a shared feature module that both the training job and the serving app import, plus the parity test from the incident post, covers most of the risk with far less to operate. A feature store starts to pay off when several models or teams reuse the same features, when you need point-in-time correctness over a lot of history, or when serving needs fast lookups of precomputed values. The rest of this post assumes you are in that second group.

Step 1: Lay Out the Repository

feature_repo/
  feature_store.yaml
  features.py
  requirements.txt

This directory is the repository’s feature code. Treat it like Terraform code: it lives in Git, changes through merge requests, and is applied by CI. Pin the exact Feast version in requirements.txt, because the Python API changes between releases and a surprise upgrade is a surprise change to your features.

Step 2: Configure the Stores

project: fraud
provider: local
registry: s3://acme-ml-data/feast/registry.db
online_store:
  type: redis
  connection_string: redis-feast.mlops.svc:6379
offline_store:
  type: file
entity_key_serialization_version: 3

Three choices here are worth explaining:

  • The registry lives in S3, not on a pod’s disk. Every job that touches Feast (CI, the materialization job, the serving pods, training) has to see the same registry. A local file means each one sees its own version, which is the same trap as a Terraform state file on one laptop.
  • The online store is Redis. Use the Redis you already run, or a managed one such as ElastiCache, so the serving pods get single-digit-millisecond lookups inside the cluster.
  • The offline store is the file type, which reads Parquet from S3. It is fine to start with. At larger data volumes, move to a warehouse-backed offline store such as BigQuery, Snowflake or Redshift. Feast supports those, and the feature definitions stay the same.

Step 3: Define the Entity, the Feature View and a Feature Service

from datetime import timedelta
from feast import Entity, FeatureService, FeatureView, Field, FileSource
from feast.types import Float32, Int64

customer = Entity(name="customer", join_keys=["customer_id"])

txn_stats_source = FileSource(
    path="s3://acme-ml-data/features/customer_txn_stats.parquet",
    timestamp_field="event_timestamp",
    created_timestamp_column="created_at",
)

customer_txn_stats = FeatureView(
    name="customer_txn_stats",
    entities=[customer],
    ttl=timedelta(days=2),
    schema=[
        Field(name="txn_count_7d", dtype=Int64),
        Field(name="avg_amount_30d", dtype=Float32),
    ],
    source=txn_stats_source,
)

fraud_detector_v2 = FeatureService(
    name="fraud_detector_v2",
    features=[customer_txn_stats[["txn_count_7d", "avg_amount_30d"]]],
)

The pieces:

  • Entity is the thing features describe, here a customer, and the key used to look them up.
  • Feature view declares which columns of the Parquet file are features, their types, and how long a value stays valid.
  • Feature service is a named bundle of features that one model version uses. Think of it as the pinned version from Part 4: the model uses fraud_detector_v2, so changing a feature for a new model doesn’t silently change what the old one reads.

The Parquet file is produced by your own batch job, and that job is where the incident’s bug lived. Feast does not compute txn_count_7d for you. It reads the value from the file, so the file has to be correct. Write each value with the timestamp at which that value was actually known, counting only transactions strictly before it, like the as-of query in the incident post. A feature view over a leaky table is a leaky feature with a nicer API.

Step 4: Plan in Merge Requests, Apply on Merge

Add two jobs to the pipeline from Part 6:

feast-plan:
  stage: test
  image: python:3.11-slim
  rules:
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      changes:
        - feature_repo/**/*
  script:
    - pip install -r feature_repo/requirements.txt
    - cd feature_repo
    - feast plan

feast-apply:
  stage: release
  image: python:3.11-slim
  resource_group: feast-registry
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      changes:
        - feature_repo/**/*
  script:
    - pip install -r feature_repo/requirements.txt
    - cd feature_repo
    - feast apply

feast plan shows what would change in the registry without changing it, so a reviewer sees “this merge request alters the type of txn_count_7d” before it merges. feast apply registers the change. The resource_group serialises applies, for the same reason it serialised promotions in Part 6.

The runner needs read and write access to the registry bucket. Give it a scoped role instead of keys in a variable, and use the IAM debugging steps if an apply fails with an access error.

Step 5: Fill the Online Store on a Schedule

Serving reads from Redis, and Redis only has what a materialization job copied there. Run it as a CronJob:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: feast-materialize
spec:
  schedule: "*/30 * * * *"
  concurrencyPolicy: Forbid
  jobTemplate:
    spec:
      activeDeadlineSeconds: 900
      template:
        spec:
          restartPolicy: Never
          serviceAccountName: ml-feast
          containers:
            - name: materialize
              image: registry.example.com/ml/feast-repo:1.0.0
              workingDir: /app/feature_repo
              command: ["sh", "-c", "feast materialize-incremental $(date -u +%Y-%m-%dT%H:%M:%S)"]
              resources:
                requests:
                  cpu: "500m"
                  memory: 1Gi

materialize-incremental copies the values that arrived since the last run, so each run is short. concurrencyPolicy: Forbid stops runs from overlapping, and the deadline stops a hung run from holding the slot. The image is the feature repository with Feast installed, built in the pipeline like any other.

Be aware of what this means for freshness. A value in Redis is only as new as the last successful run, so with a 30-minute schedule the online value for a 7-day count can lag the exact value by up to 30 minutes. That gap is small and bounded, but it is still a difference between training and serving. For features that must be current to the second, Feast supports pushing values into the online store as events happen, which is a bigger design than this post covers.

Step 6: Read Features in Training

from feast import FeatureStore

store = FeatureStore(repo_path="feature_repo")

entity_df = labels[["customer_id", "txn_id", "event_timestamp", "is_fraud"]]

training_df = store.get_historical_features(
    entity_df=entity_df,
    features=store.get_feature_service("fraud_detector_v2"),
).to_df()

Each row of entity_df has the time of the transaction in event_timestamp. Feast joins it to the latest feature value at or before that time and never a later one. That removes the bug from the incident at the source: a row can’t see the rest of its burst. Hold out the most recent week for evaluation as before, because a point-in-time join protects the features and not the split.

Record which feature service the model was trained with, using the MLflow tracking from Part 2:

mlflow.set_tag("feature_service", "fraud_detector_v2")

Now the registry tells you not only which data and code produced a model but which features it expects.

Step 7: Read the Same Features in Serving

Change the FastAPI app from Part 4 so it looks features up by customer instead of expecting them in the request:

from feast import FeatureStore

store = FeatureStore(repo_path="/app/feature_repo")
service = store.get_feature_service("fraud_detector_v2")

@app.post("/predict")
def predict(payload: dict):
    rows = pd.DataFrame(payload["rows"])
    features = store.get_online_features(
        features=service,
        entity_rows=[{"customer_id": cid} for cid in rows["customer_id"]],
    ).to_df()
    data = rows.merge(features, on="customer_id", how="left")
    scores = model.predict(data[FEATURE_COLUMNS]).tolist()
    return {"model": MODEL_URI, "predictions": scores}

Create the FeatureStore once at start-up, not per request. The names in FEATURE_COLUMNS have to match the feature service, and the model’s feature service tag from Step 6 is the place to check that. Include the feature repo, at the same version CI applied, in the serving image.

A customer with no value in the online store gets a null, either because they are new or because the value passed its TTL. Decide what the model does with that on purpose, and count it. A counter of missing features per feature, next to the metrics from Part 5, turns a quiet failure into a graph.

Step 8: Alert When Materialization Stops

If the CronJob fails quietly, Redis keeps serving old values and everything looks healthy. Alert on the time of the last success, using kube-state-metrics:

- alert: FeastMaterializationStale
  expr: time() - kube_cronjob_status_last_successful_time{cronjob="feast-materialize"} > 3600
  labels:
    severity: warning
  annotations:
    summary: "Feast has not materialized successfully in over an hour"

This is the lesson from Part 5 and from our TLS certificate incident again: alert on the checker, not only on the result. Keep the threshold above twice the schedule, and keep the feature TTL longer than that so a delayed run doesn’t turn into nulls.

Mistakes That Show Up Later, Not Immediately

  • Assuming Feast computes the feature. It stores and serves what your batch job wrote. A wrong definition upstream is still wrong, only faster to look up.
  • Stamping features with the write time. The event timestamp has to be when the value was known. If it is the time the batch job ran, a point-in-time join returns the wrong value for historical rows.
  • A TTL shorter than the materialization gap. Values expire between runs and serving starts returning nulls for active customers.
  • A registry on local disk. CI, the CronJob and the serving pods end up with different views of the features.
  • Reading features without a pinned feature service. Editing a feature view for a new model changes what the production model reads.
  • Letting the schedule drift unnoticed. A stale online store looks like a healthy one until accuracy drops.
  • Adopting a feature store for one model. It adds a registry, a Redis and a job to run. A shared module and a parity test may be enough.

Key Lessons

  1. One definition, two readers.
    Training and serving should read the same feature, through the same code, from the same repository.
  2. Point-in-time joins fix leakage, but only for correct data.
    The join stops a row seeing the future, and the batch job still has to stamp values honestly.
  3. Run it like Terraform.
    Plan in merge requests, apply on merge, serialise applies, and keep state in shared storage.
  4. Alert on the sync job.
    A quiet materialization failure leaves a healthy-looking dashboard and stale predictions.
  5. Don’t adopt it before you need it.
    For one model and one team, a shared module with a parity test costs far less.

Summary

Piece Where It Runs What Goes Wrong Without It
Feature repo and feast apply Git and GitLab CI Two feature definitions that drift apart
Registry in S3 Shared by every job Each component sees a different version
Offline store and point-in-time join Training Job Rows that see data from their own future
Online store in Redis Serving pods Slow lookups or recomputed features
Materialization CronJob Kubernetes Stale values served as if fresh
Staleness alert Prometheus A silent sync failure

A feature store is not new technology for a DevOps engineer. It is a registry, a cache and a sync job, with one extra rule about time.

Read Next

Follow along on LinkedIn for what we write next, and subscribe to the newsletter so you don’t miss the next post.


Tags:
#MLOps   #Feast   #FeatureStore   #Kubernetes  
#DevOps   #MachineLearning

Leave a Comment