Data & Feature Pipelines for Production
After this lesson, you will be able to:
- Distinguish batch (Airflow/dbt) from streaming (Kafka/Flink) data pipelines and pick the right architecture for your latency/freshness target
- Use data contracts and schema registries (Confluent, Apicurio, Avro/Protobuf) to prevent silent data corruption between producers and consumers
- Apply DAG-orchestrated workflows (Airflow, Prefect, Dagster) with idempotency, retries, and observability for production reliability
- Recognize the 'silent data quality' failure modes (schema drift, late-arriving data, dedup races) and the patterns that prevent them
Before you start
#Batch vs Streaming Architectures
#DAG Orchestration: Airflow / Prefect / Dagster
The dominant pattern: declare your pipeline as a Directed Acyclic Graph (DAG) of tasks. Each task is idempotent, has retries, has observability hooks.
| Tool | Best for |
|---|---|
| Airflow | Mature, vast ecosystem, complex DAGs |
| Prefect | Modern Python-native, dynamic DAGs |
| Dagster | Asset-centric (data products), strong typing |
| Kubeflow Pipelines | K8s-native ML pipelines (Vertex AI Pipelines under the hood) |
| Argo Workflows | K8s-native, language-agnostic |
#Data Contracts
A contract specifies: schema (field names, types, nullability), invariants (no negative ages, prices in $), update SLAs, ownership.
#Feature Stores: The Online/Offline Bridge
The dominant feature stores in 2026:
| Store | Origin | Sweet spot | Trade-offs |
|---|---|---|---|
| Feast | Tecton open-source (2019) | Most lightweight; team owns the infra | DIY ingestion + serving; you wire it up |
| Tecton | Tecton SaaS | Managed end-to-end + low-latency online serving | Cost; vendor lock-in |
| Hopsworks | LogicalClocks/Hopsworks AI | On-prem + EU sovereignty; PySpark heritage | Heavier deploy footprint |
| Databricks Feature Store | Databricks | Native to Delta Lake / Unity Catalog users | Locked to Databricks |
| SageMaker Feature Store | AWS | Native AWS integration | AWS-only |
#Online vs Offline Serving
| Property | Offline store | Online store |
|---|---|---|
| Latency target | Minutes (batch read) | Sub-10 ms (point lookup) |
| Volume per query | Millions of rows | One entity at a time |
| Consumer | Training, backfill, batch scoring | Realtime inference, online serving |
| Backend | Parquet / Delta / Iceberg, Snowflake, BigQuery | Redis, DynamoDB, Cassandra |
| Cost per GB-month | Cents | Dollars (RAM-resident) |
Notice that the online store is 10-100x more expensive per GB. You don't load ALL features into the online store, only the ones with realtime traffic. The feature store handles the partitioning.
#Point-in-Time Correctness: The Subtle Killer
T, every feature value in that row must reflect what your system would have known at T, not what it knows today.user_features to purchase_events on user_id. If you naively JOIN ON user_id, you'll pick up user_features as they exist today, including features computed from purchases that happen AFTER the prediction timestamp. The model "learns" using future information, scores 99% in offline eval, and lays a 60% accuracy egg in production. This is feature leakage, and it's why point-in-time joins exist.T_event, join to the latest feature value with feature_timestamp <= T_event. Most feature stores call this an as_of_join or point_in_time_join and implement it on top of Spark / Polars / DuckDB.Why this join cannot leak is derived step by step in Feature Stores: Serving Consistent Features at Scale.
avg_purchases_per_week = 2.3 for the event on 2026-05-10, but that value didn't exist until 2026-05-15. A model trained on the naive join would silently encode future information; the point-in-time join gives the model 0.7, the value the system would actually have known at prediction time. This is the bug feature stores were built to eliminate.Your team is training a churn model. Offline AUC is 0.94; production AUC is 0.71. You verify the model code, the feature definitions, and the production training data, all match. The most likely diagnosis?
#Feature Versioning and Data Validation
Feature stores also tackle two adjacent problems:
- Feature versioning. When you change a feature's definition (
avg_purchases_per_weeknow excludes returns), you don't want to silently invalidate every model trained on the old definition. The feature store assigns the new version a new identity; old models keep using the old version; new models pin the new version. Without this, you get the worst of both worlds, silent retraining drift. - Data validation. Tools like Great Expectations, Deequ, and Soda let you express assertions over data (
expect_column_values_to_be_between('age', 0, 120)) and run them as quality gates in the pipeline. Feature stores integrate these, invalid rows are quarantined to a dead-letter queue, not silently passed downstream. - ML metadata stores like MLMD (TFX) and OpenMetadata track the full provenance: which feature version, which training run, which model, which deployment. EU AI Act compliance leans heavily on this lineage.
A teammate proposes 'we can skip the feature store, we'll just rerun the same SQL in training and inference.' Why is this brittle in practice?
#Streaming Patterns
For real-time ML, streaming is essential. Kafka is the dominant message bus; Flink and Spark Streaming are the dominant processors.
Common patterns
- CDC (Change Data Capture): stream database changes via Debezium → Kafka → Flink → feature store
- Tumbling windows: aggregate over fixed N-second windows (e.g., 5-min user activity counts)
- Sliding windows: rolling windows that slide forward (e.g., 1-min window every 10 seconds)
- Session windows: user-session boundaries (gap-based)
# Flink-style sliding window aggregation
events.key_by(lambda e: e.user_id) \
.window(SlidingWindows.of(minutes=5, slide=10)) \
.aggregate(MyAggregate())#Common Failure Modes
#Hands-On
apache-airflow and pandas libraries, so it does not run on this page. Copy it to Google Colab or a local environment to try it.# Copy to Colab: needs airflow, pandas, so it cannot run on this page.
# Minimal Airflow DAG with data-quality gate
# Run: pip install apache-airflow great-expectations
from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
import pandas as pd
# --- Tasks ---
def extract():
# Mock: pull from raw source
df = pd.DataFrame({
"user_id": [1, 2, 3, 4, 5],
"purchase_amount": [10.0, 25.5, -5.0, 100.0, 30.0], # Note: -5.0 is invalid!
"timestamp": ["2026-05-05", "2026-05-05", "2026-05-05", "2026-05-05", "2026-05-05"],
})
df.to_parquet("/tmp/raw_purchases.parquet")
def validate():
df = pd.read_parquet("/tmp/raw_purchases.parquet")
# Data-quality assertions
assert df["user_id"].notna().all(), "user_id has nulls"
assert (df["purchase_amount"] >= 0).all(), f"Negative purchase amounts found: {df[df['purchase_amount'] < 0].to_dict()}"
assert df["purchase_amount"].max() < 10_000, "Suspicious large purchase"
return "validated"
def transform():
df = pd.read_parquet("/tmp/raw_purchases.parquet")
df["hour_of_day"] = pd.to_datetime(df["timestamp"]).dt.hour
df["log_amount"] = (df["purchase_amount"] + 1).apply(lambda x: x ** 0.5)
df.to_parquet("/tmp/feature_purchases.parquet")
return f"transformed {len(df)} rows"
def load_to_feature_store():
df = pd.read_parquet("/tmp/feature_purchases.parquet")
print(f"Pushed {len(df)} feature vectors to feature store")
return f"loaded {len(df)} rows"
# --- DAG ---
default_args = {"retries": 3, "retry_delay": timedelta(minutes=2), "owner": "ml-team"}
with DAG("ml_feature_pipeline", start_date=datetime(2026, 1, 1),
schedule="@daily", default_args=default_args, catchup=False) as dag:
e = PythonOperator(task_id="extract", python_callable=extract)
v = PythonOperator(task_id="validate", python_callable=validate)
t = PythonOperator(task_id="transform", python_callable=transform)
l = PythonOperator(task_id="load", python_callable=load_to_feature_store)
e >> v >> t >> l
# Run locally for testing:
print("Try: airflow dags test ml_feature_pipeline 2026-05-05")
print("Notice: 'validate' will FAIL because of the -5.0 purchase amount.")
print("This is the SAFETY: bad data never reaches training.")
print("\nCHALLENGE: Add a 'reject' branch that on validation failure:")
print(" 1. Sends the bad rows to a dead-letter queue")
print(" 2. Alerts the upstream team")
print(" 3. Continues the pipeline with the GOOD rows only")
# --- Solution sketch ---
# Branch on validation:
# from airflow.operators.python import BranchPythonOperator
# def validate_and_branch():
# df = pd.read_parquet("/tmp/raw_purchases.parquet")
# if (df["purchase_amount"] < 0).any():
# alert_upstream_team(df[df["purchase_amount"] < 0])
# df = df[df["purchase_amount"] >= 0]
# df.to_parquet("/tmp/raw_purchases.parquet")
# return "transform"
# v = BranchPythonOperator(task_id="validate", python_callable=validate_and_branch)The same idea in pure Python runs here: a four-task pipeline, retries, and a data-quality gate that stops bad data from reaching the feature store.
Tests: Verify validate fails on every retry. Verify transform and load never run while the bad row is present. Verify the solution moves the bad row to the dead-letter list and still loads the good rows.
#Key Takeaways
- Batch + streaming are complementary. Use batch for training, streaming for fresh inference features; reconcile via the same feature engineering logic
- DAG orchestration with idempotency, retries, observability is non-negotiable. Airflow/Prefect/Dagster
- Data contracts prevent silent corruption. Pydantic/Avro/Protobuf at every boundary, schema registry as source of truth
- Late-arriving data, non-idempotent tasks, schema drift are the three production failure modes, each has standard fixes
- Production data pipelines are the most expensive component of a real ML system, far more than the model
#Quick Check
Why must pipeline tasks be idempotent?
Your data team adopts Feast. They define features in YAML, ingest from Kafka and S3, and serve via Redis. A month later, a model trained against feature version v2 is in production. The data team renames a column upstream and rolls out v3. What protects the production model from breaking?