🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10
EssentialMLOps22 min read

MLOps in 2026: End-to-End ML Pipeline Architecture

C
ChatWhole AI Team|2026-09-01

MLOps in 2026: End-to-End ML Pipeline Architecture

Machine learning without MLOps is like software without DevOps — it works in the lab but fails in production. This guide covers the complete MLOps stack, from feature engineering through model deployment and monitoring.

The MLOps Stack

Sponsored
Architecture Diagram
┌─────────────────────────────────────────────────────────┐
│                    MLOps Platform                        │
├─────────┬──────────┬──────────┬──────────┬──────────────┤
│ Feature │  Model   │ Pipeline │  Model   │   Model      │
│  Store  │ Registry │ Orchestr.│ Serving  │  Monitoring  │
├─────────┼──────────┼──────────┼──────────┼──────────────┤
│ Feast   │ MLflow   │ Airflow  │ Triton   │ Evidently   │
│ Tecton  │ DVC      │ Kubeflow │ BentoML  │ Whylabs     │
│ Hopsworks│ Weights│ Dagster  │ Seldon   │ Grafana     │
└─────────┴──────────┴──────────┴──────────┴──────────────┘

The five columns are not five independent products. A value written by the batch ingestion job has to be readable by the training job at the exact timestamp the label was created, and the same value has to come back from the online store at inference time. That requirement — one number, computed once, served twice — is why most of this architecture exists at all. Teams that skip the feature store usually discover the gap months later as an unexplained 4 point drop in offline AUC after a migration, because training read a table the serving path never wrote to. Budget roughly 30 percent of total ML engineering effort for the plumbing; the model itself is rarely where projects fail.

A useful maturity test: ask how long it takes to reproduce last month's training dataset. If the answer involves querying three systems and joining them by hand, the platform is level 0 regardless of how many tools are installed.

Feature Store Architecture

The two failure modes that dominate feature store design are train-serve skew and leakage. Skew happens when the training pipeline computes a 30 day rolling average in pandas while the serving path computes it with a SQL window frame that excludes the current row, so production sees values systematically shifted by one day. Leakage happens when a feature timestamp is later than the label timestamp, which leaks the answer into training and can inflate offline AUC by 2 to 6 points before collapsing in production. Point-in-time correct as-of joins, keyed on the label timestamp, are the fix — and they are worth testing with a deliberately adversarial fixture rather than trusting.

Core Concepts

python
from feast import FeatureStore, Entity, Feature, ValueType
from feast import FileSource, FeatureView
from datetime import timedelta

# Define entities
user_entity = Entity(
    name="user_id",
    value_type=ValueType.INT64,
    description="User identifier"
)

# Define feature views
user_features = FeatureView(
    name="user_features",
    entities=["user_id"],
    ttl=timedelta(days=1),
    features=[
        Feature(name="age", dtype=ValueType.INT32),
        Feature(name="total_purchases", dtype=ValueType.FLOAT),
        Feature(name="avg_order_value", dtype=ValueType.FLOAT),
        Feature(name="days_since_last_purchase", dtype=ValueType.INT32),
    ],
    source=FileSource(
        path="s3://features/user_features.parquet",
        event_timestamp_column="event_timestamp"
    )
)

# Store features
store = FeatureStore(repo_path=".")
store.apply([user_entity, user_features])

# Retrieve features for training
training_df = store.get_historical_features(
    entity_df=entity_df,
    features=[
        "user_features:age",
        "user_features:total_purchases",
        "user_features:avg_order_value",
    ]
).to_df()

# Retrieve features for serving (real-time)
feature_vector = store.get_online_features(
    features=[
        "user_features:age",
        "user_features:total_purchases",
        "user_features:avg_order_value",
    ],
    entity_rows=[{"user_id": 123}]
).to_dict()

Feature Store Best Practices

python
class FeatureStoreManager:
    def __init__(self, store: FeatureStore):
        self.store = store
    
    async def validate_features(self, feature_view: str):
        """Validate feature freshness and quality"""
        stats = await self.store.get_feature_statistics(feature_view)
        
        checks = {
            'freshness': stats.max_age < timedelta(hours=1),
            'completeness': stats.null_rate < 0.05,
            'distribution': self._check_distribution(stats),
            'drift': self._check_drift(stats),
        }
        
        return FeatureValidationResult(
            feature_view=feature_view,
            passed=all(checks.values()),
            details=checks
        )
    
    def _check_distribution(self, stats):
        """Check if feature distribution is within expected bounds"""
        for feature in stats.features:
            if feature.mean < feature.expected_mean * 0.5:
                return False
            if feature.mean > feature.expected_mean * 2.0:
                return False
        return True

Freshness, completeness, distribution and drift are four separate checks that fail for four separate reasons. A freshness breach usually means the upstream job silently stopped. A null rate above 5 percent often means a join key changed type upstream. A mean drifting past twice its expected value points at a change in business logic rather than at noise. Wire these checks into the orchestration layer so a failed validation blocks the training task, instead of quietly producing a model nobody should ship.

Model Registry

A registry is a promotion workflow with a database attached, not a folder of artifacts. Every version should carry the training data snapshot id, the evaluation report, the hyperparameters, and the git sha of the code that produced it, because the question you will actually ask at 2 a.m. is what changed between version 7 and version 8. Stages — staging, shadow, canary, production, archived — encode who is allowed to move an artifact forward and what evidence they need first. Calling transition_model_version_stage by hand is fine for the first six months; after that, put the transition behind CI so the evidence becomes mandatory.

MLflow Model Registry

python
import mlflow
import mlflow.sklearn
from mlflow.tracking import MlflowClient

# Train model
model = train_model(X_train, y_train)

# Log model
with mlflow.start_run():
    mlflow.log_param("n_estimators", 100)
    mlflow.log_param("max_depth", 10)
    
    # Log metrics
    mlflow.log_metric("accuracy", accuracy)
    mlflow.log_metric("f1_score", f1)
    
    # Log model
    mlflow.sklearn.log_model(
        model,
        artifact_path="model",
        registered_model_name="churn_predictor"
    )

# Promote model to production
client = MlflowClient()
client.transition_model_version_stage(
    name="churn_predictor",
    version=1,
    stage="Production"
)

# Load production model
model = mlflow.pyfunc.load_model(
    "models:/churn_predictor/Production"
)

Model Versioning Strategy

python
class ModelVersionManager:
    def __init__(self, registry):
        self.registry = registry
    
    async def promote_model(self, model_name: str, version: int):
        """Promote model through stages with validation"""
        
        # Stage 1: Validation
        model = self.registry.load(model_name, version)
        val_results = await self.validate_model(model)
        
        if not val_results.passed:
            raise ModelValidationError(val_results.errors)
        
        # Stage 2: Shadow deployment
        await self.shadow_deploy(model_name, version)
        
        # Stage 3: A/B test
        ab_results = await self.run_ab_test(model_name, version)
        
        if ab_results.improvement < 0.01:  # Less than 1% improvement
            raise ModelNotImprovedError()
        
        # Stage 4: Full promotion
        self.registry.promote(model_name, version, "Production")
        
        return PromotionResult(
            model=model_name,
            version=version,
            improvement=ab_results.improvement
        )

Notice that the promotion gate rejects a model improving by less than 1 percent. Without a floor like that, an A/B test with 200 users per arm will promote a model on noise roughly one time in five, and nobody connects the regression to the promotion three weeks later. Require a minimum effect size, a minimum sample, and a rollback path that restores the previous version inside a single deploy cycle.

ML Pipeline Orchestration

Sponsored

Two properties matter more than the choice of orchestrator. First, idempotency: every task must be safe to re-run against the same date partition, which means writing to a temporary location and renaming on success rather than appending in place. Second, explicit data intervals: key the DAG on a logical date, not on whatever the wall clock says, so a backfill of the last 90 days produces rows identical to the original run. Airflow's external task sensor and Dagster's asset partitions both give you that. Neither can give you discipline about retries, so set two retries with a five minute delay and let transient failures heal themselves.

Airflow DAG for ML Pipeline

python
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.sensors.external_task import ExternalTaskSensor
from datetime import datetime, timedelta

default_args = {
    'owner': 'ml-team',
    'depends_on_past': False,
    'email_on_failure': True,
    'email': ['ml-alerts@company.com'],
    'retries': 2,
    'retry_delay': timedelta(minutes=5),
}

with DAG(
    'ml_training_pipeline',
    default_args=default_args,
    description='End-to-end ML training pipeline',
    schedule_interval='@weekly',
    start_date=datetime(2026, 1, 1),
    catchup=False,
) as dag:
    
    # Task 1: Extract and validate data
    extract_data = PythonOperator(
        task_id='extract_data',
        python_callable=extract_training_data,
        params={'date': '{{ ds }}'}
    )
    
    # Task 2: Feature engineering
    engineer_features = PythonOperator(
        task_id='engineer_features',
        python_callable=compute_features,
    )
    
    # Task 3: Train model
    train_model = PythonOperator(
        task_id='train_model',
        python_callable=train_and_validate,
    )
    
    # Task 4: Evaluate model
    evaluate_model = PythonOperator(
        task_id='evaluate_model',
        python_callable=evaluate_and_compare,
    )
    
    # Task 5: Deploy model
    deploy_model = PythonOperator(
        task_id='deploy_model',
        python_callable=deploy_to_production,
    )
    
    # Task 6: Monitor model
    setup_monitoring = PythonOperator(
        task_id='setup_monitoring',
        python_callable=configure_monitoring,
    )
    
    # Define dependencies
    extract_data >> engineer_features >> train_model
    train_model >> evaluate_model >> deploy_model
    deploy_model >> setup_monitoring

Dagster Pipeline

python
from dagster import op, job, Out, In
import pandas as pd

@op(out=Out(pd.DataFrame))
def extract_data(context):
    """Extract training data from data warehouse"""
    query = """
    SELECT * FROM features
    WHERE event_date = DATE '{{ ds }}'
    """
    return pd.read_sql(query, connection)

@op(ins={"data": In(pd.DataFrame)}, out=Out(pd.DataFrame))
def validate_data(context, data):
    """Validate data quality"""
    assert data.isnull().sum().sum() / data.size < 0.05
    assert len(data) > 1000
    return data

@op(ins={"data": In(pd.DataFrame)}, out=Out(dict))
def train_model(context, data):
    """Train ML model"""
    from sklearn.ensemble import RandomForestClassifier
    
    X = data.drop('target', axis=1)
    y = data['target']
    
    model = RandomForestClassifier(n_estimators=100)
    model.fit(X, y)
    
    return {"model": model, "features": X.columns.tolist()}

@job
def ml_pipeline():
    data = extract_data()
    validated = validate_data(data)
    result = train_model(validated)

Model Monitoring

Monitor four things, in this order. Prediction distribution first: if the share of positive predictions moves from 4 percent to 11 percent in a day, something upstream changed even though accuracy labels are still days away. Feature drift second, using population stability index computed on deciles — below 0.10 is stable, 0.10 to 0.20 merits a look, above 0.20 means retrain. Then latency and error rate, which catch infrastructure regressions no statistical test will see. Labelled accuracy comes last, because labels lag predictions by hours or weeks in most products. Alert on burn rate against a 30 day SLO rather than on raw thresholds: a 99.9 percent budget is about 43 minutes per month, and one long incident consumes it faster than twenty short ones.

Data Drift Detection

python
from evidently import ColumnMapping
from evidently.report import Report
from evidently.metric_preset import (
    DataDriftPreset,
    TargetDriftPreset,
    ClassificationPreset
)

class ModelMonitor:
    def __init__(self, reference_data, production_data):
        self.reference = reference_data
        self.production = production_data
    
    def check_drift(self) -> DriftReport:
        """Comprehensive drift detection"""
        
        # Data drift
        data_drift_report = Report(metrics=[
            DataDriftPreset(),
        ])
        data_drift_report.run(
            current_data=self.production,
            reference_data=self.reference
        )
        
        # Model performance drift
        performance_report = Report(metrics=[
            ClassificationPreset(),
        ])
        performance_report.run(
            current_data=self.production,
            reference_data=self.reference
        )
        
        return DriftReport(
            data_drift=data_drift_report,
            performance_drift=performance_report,
            has_drift=self._detect_drift(data_drift_report)
        )
    
    def _detect_drift(self, report) -> bool:
        """Detect if significant drift occurred"""
        result = report.as_dict()
        for metric in result['metrics']:
            if metric.get('result', {}).get('drift_detected'):
                return True
        return False

Real-Time Monitoring Dashboard

python
class MonitoringDashboard:
    def __init__(self, metrics_store):
        self.metrics_store = metrics_store
    
    async def get_dashboard_data(self, model_name: str, hours: int = 24):
        """Get monitoring data for dashboard"""
        
        metrics = await self.metrics_store.get_metrics(
            model_name=model_name,
            start_time=datetime.now() - timedelta(hours=hours)
        )
        
        return {
            'latency': {
                'p50': np.percentile(metrics['latencies'], 50),
                'p95': np.percentile(metrics['latencies'], 95),
                'p99': np.percentile(metrics['latencies'], 99),
            },
            'throughput': {
                'requests_per_minute': len(metrics['latencies']) / (hours * 60),
                'total_requests': len(metrics['latencies']),
            },
            'errors': {
                'error_rate': metrics['errors'] / len(metrics['latencies']),
                'timeout_rate': metrics['timeouts'] / len(metrics['latencies']),
            },
            'quality': {
                'prediction_distribution': self._compute_distribution(
                    metrics['predictions']
                ),
                'feature_drift_scores': metrics.get('drift_scores', {}),
            }
        }

CI/CD for ML

Treat the pipeline as three test tiers. Unit tests run in under a minute and cover feature transforms, schema contracts, and the serving wrapper; these are ordinary pytest and should block every pull request. Next comes a training job on a fixed 5,000 row sample that asserts thresholds: accuracy within 1 point of the current production model, no feature with a null rate above 5 percent, p95 inference latency under 100 ms. The full run happens on a schedule rather than on every commit, because a 45 minute training job in the critical path teaches people to click re-run until it goes green. Keep the thresholds in a versioned file so a deliberate change to them is a reviewed diff.

GitHub Actions Pipeline

# .github/workflows/ml-pipeline.yml
name: ML Pipeline

on:
  push:
    branches: [main]
  schedule:
    - cron: '0 0 * * 0'  # Weekly

jobs:
  train:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      
      - name: Install dependencies
        run: pip install -r requirements.txt
      
      - name: Run tests
        run: pytest tests/
      
      - name: Train model
        run: python train.py
        env:
          MLFLOW_TRACKING_URI: ${{ secrets.MLFLOW_URI }}
      
      - name: Evaluate model
        run: python evaluate.py
      
      - name: Deploy if approved
        if: success()
        run: python deploy.py

Model Testing

python
import pytest
import numpy as np

class TestModel:
    def test_prediction_shape(self, model):
        """Model returns correct output shape"""
        X = np.random.randn(10, 5)
        predictions = model.predict(X)
        assert predictions.shape == (10,)
    
    def test_prediction_range(self, model):
        """Predictions are in valid range"""
        X = np.random.randn(100, 5)
        predictions = model.predict(X)
        assert predictions.min() >= 0
        assert predictions.max() <= 1
    
    def test_latency(self, model):
        """Model inference is fast enough"""
        X = np.random.randn(1, 5)
        start = time.time()
        for _ in range(100):
            model.predict(X)
        latency = (time.time() - start) / 100
        assert latency < 0.1  # Less than 100ms
    
    def test_robustness(self, model):
        """Model handles edge cases"""
        # Empty input
        with pytest.raises(ValueError):
            model.predict(np.array([]))
        
        # NaN input
        X_nan = np.full((1, 5), np.nan)
        predictions = model.predict(X_nan)
        assert not np.any(np.isnan(predictions))

Production Architecture

Roll out in three steps rather than one. Shadow mode sends real traffic to the new model and discards its output; it costs a second inference per request but surfaces latency and crash problems with zero user risk. A canary then takes 5 percent of traffic for long enough to reach statistical power — comparing a 2 point regression at 95 percent confidence needs roughly 2,400 requests per arm, so a canary that runs four minutes at ten requests per minute tells you nothing at all. Only after that, full rollout, with a liveness probe that verifies the model file actually loaded rather than merely that the port answers, and an autoscaler that targets queue depth instead of CPU.

Kubernetes Deployment

# model-serving.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: model-server
spec:
  replicas: 3
  selector:
    matchLabels:
      app: model-server
  template:
    metadata:
      labels:
        app: model-server
    spec:
      containers:
      - name: model
        image: model-server:latest
        resources:
          requests:
            memory: "4Gi"
            cpu: "2"
            nvidia.com/gpu: "1"
          limits:
            memory: "8Gi"
            cpu: "4"
            nvidia.com/gpu: "1"
        ports:
        - containerPort: 8080
        env:
        - name: MODEL_PATH
          value: "s3://models/production/model.pkl"
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: model-server-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: model-server
  minReplicas: 2
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70

Cost Optimization

Advertisement

Three levers move cost, and only one of them is free. Quantization to INT8 typically cuts model size 4× with under 1 point of metric loss, and dynamic quantization on linear layers needs no calibration data at all. Structured pruning that removes 30 percent of channels gives a real 1.25× speedup, whereas unstructured pruning at the same sparsity buys nothing on hardware without sparse kernels — the FLOP count drops and the latency does not. Distillation is the expensive one: it requires a full training run, but a 175M student trained on teacher logits can match an 8B teacher on narrow tasks at roughly one fiftieth of the inference cost. Measure each change against the same eval set, because a 4× size win that costs 3 points of recall is not a win.

Model Optimization Techniques

python
class ModelOptimizer:
    def quantize(self, model, precision="int8"):
        """Reduce model size with quantization"""
        if precision == "int8":
            return torch.quantization.quantize_dynamic(
                model, {torch.nn.Linear}, dtype=torch.qint8
            )
        elif precision == "fp16":
            return model.half()
    
    def prune(self, model, amount=0.3):
        """Remove unnecessary weights"""
        import torch.nn.utils.prune as prune
        for module in model.modules():
            if isinstance(module, torch.nn.Linear):
                prune.l1_unstructured(module, name='weight', amount=amount)
        return model
    
    def distill(self, teacher_model, student_model, train_data):
        """Knowledge distillation"""
        # Train student to mimic teacher
        for batch in train_data:
            with torch.no_grad():
                teacher_logits = teacher_model(batch)
            student_logits = student_model(batch)
            loss = kl_divergence(student_logits, teacher_logits)
            loss.backward()

Conclusion

MLOps in 2026 requires a comprehensive approach covering the entire ML lifecycle:

  1. Feature Store — Centralized feature management with validation
  2. Model Registry — Version control and staged promotion
  3. Pipeline Orchestration — Automated training and deployment
  4. Monitoring — Real-time drift detection and alerting
  5. CI/CD — Automated testing and deployment

The key is to start simple and add complexity as needed. Begin with MLflow for tracking, Airflow for orchestration, and Evidently for monitoring. Scale up as your ML operations mature.

A practical build order for a team starting from nothing: week one, MLflow tracking plus a data snapshot id on every run, so any past result is reproducible. Week two, a single orchestrated training job with idempotent tasks and a metric gate. Week three, a registry with two stages and a manual promotion rule. Week four, prediction-distribution monitoring and an alert that pages someone. Feature stores, shadow deploys, and multi-armed routers come later, once the first four weeks are boring. Each stage you add should answer a question you are already asking; a platform built ahead of its questions becomes a platform nobody trusts.

Common Mistakes

Letting training read a table that the serving pipeline does not write, then chasing an unexplained AUC drop after launch

Fix: Generate both paths from one feature definition and assert equality on a fixture for every feature view

Promoting on a metric difference smaller than the noise of the A/B test that measured it

Fix: Set a minimum effect size and a minimum sample size per arm, and refuse promotion below either

Alerting on raw thresholds such as error rate above 2 percent, then ignoring the alert during traffic spikes

Fix: Alert on SLO burn rate over a 30 day window so the threshold already accounts for the budget remaining

Key Takeaways

  • The feature store exists to guarantee one value is computed once and served twice; point-in-time correct joins are what make that guarantee real
  • A registry without staged promotion and a minimum effect size promotes noise roughly one time in five at small sample sizes
  • Idempotent tasks and logical dates are what make a backfill produce rows identical to the original run
  • Monitor prediction distribution, feature drift, latency, and burn rate before labelled accuracy, because labels arrive last

Explore More Articles

Search across 3100+ tutorials and news articles.