Building a Production ML/LLM System (Capstone)
After this lesson, you will be able to:
- Architect an end-to-end production ML/LLM system that integrates everything from this track, data pipelines, feature stores, training, serving, monitoring, governance
- Apply the production hardening checklist before any ML system reaches real users
- Identify the most common production failure modes and the architectural patterns that prevent them
- Deploy a real ML system to a cloud platform (Modal/Vertex AI/SageMaker) with full observability and incident response in place
Before you start
#The Reference Architecture
┌─────────────────────────────────────────┐
│ INGESTION & FEATURES │
│ Kafka → Flink → Feature Store (Feast) │
│ + Data contracts, monitoring │
└─────────────────────────────────────────┘
│
┌─────────────▼───────────────────────────┐
│ TRAINING & VERSIONING │
│ Airflow + MLflow + DVC │
│ + W&B tracking, Docker, distributed │
└─────────────────────────────────────────┘
│
┌─────────────▼───────────────────────────┐
│ REGISTRY & DEPLOYMENT │
│ MLflow registry → Vertex AI / Triton │
│ + Approval gates, blue-green deploy │
└─────────────────────────────────────────┘
│
┌─────────────▼───────────────────────────┐
│ SERVING │
│ vLLM / Triton multi-model │
│ + Autoscale, spot, MIG, cost monitoring│
└─────────────────────────────────────────┘
│
┌─────────────▼───────────────────────────┐
│ MONITORING & GOVERNANCE │
│ Evidently / Arize for drift │
│ Langfuse for LLM tracing │
│ EU AI Act audit logging │
│ PagerDuty for incidents │
└─────────────────────────────────────────┘
│
┌─────────────▼───────────────────────────┐
│ RETRAIN LOOP │
│ Drift detected → trigger pipeline │
│ Eval gate → registry promote │
└─────────────────────────────────────────┘
#The Production Hardening Checklist (16 items)
| # | Layer | Concern | Pass criteria |
|---|---|---|---|
| 1 | Data | Schema validation | Pydantic/Avro contracts at every pipeline boundary |
| 2 | Data | Drift detection | Daily KS / PSI on key features, alert > threshold |
| 3 | Training | Reproducibility | Image SHA + git SHA + data hash logged per run |
| 4 | Training | Eval gates | Pass golden-set thresholds before promotion |
| 5 | Deployment | Blue-green / canary | Progressive rollout, automatic rollback on regression |
| 6 | Deployment | Rollback < 60s | Tested in chaos drills quarterly |
| 7 | Serving | Authentication | OAuth / API keys / IAM; never anonymous |
| 8 | Serving | Rate limiting | Per-user and per-tier limits; cost cap per user |
| 9 | Serving | Tracing | Distributed tracing (Langfuse / OpenTelemetry) on every request |
| 10 | Serving | Health checks | Liveness + readiness probes; not just HTTP 200 |
| 11 | Monitoring | Performance dashboards | Latency p50/p95/p99, accuracy, cost per request |
| 12 | Monitoring | Alerting | PagerDuty for severity-1; Slack for severity-2; ticket for severity-3 |
| 13 | Security | PII handling | PII redaction in logs; GDPR-compliant data retention |
| 14 | Security | Prompt injection defense | Input + output classifiers; tool sandboxing |
| 15 | Governance | Audit logging | Every model decision traceable for EU AI Act compliance |
| 16 | Governance | Model card | Public spec of capabilities + limits + bias measurements |
#Real-World Reference Architectures
#Customer Support Chatbot (Glean / Ada / Forethought style)
User query → API gateway (auth + rate limit)
→ RAG retrieval (Pinecone + Cohere Rerank)
→ LLM generation (Claude 3.5 Sonnet via vLLM if self-hosted)
→ Safety filter (PII + content classifier)
→ Citation validation
→ Streaming response
Background:
- Daily eval pipeline runs on golden set
- Drift detector on input distribution
- Cost dashboard with per-user attribution
- PagerDuty alerts on accuracy regression
#Fraud Detection (Stripe Radar style)
Transaction → Feature pipeline (real-time + batch features)
→ Feature store (online + offline)
→ Model serving (XGBoost + LLM hybrid)
→ Decision: allow / review / block
→ Logging for audit + retraining
Background:
- Continuous retraining (daily on new labels)
- A/B testing for new model variants
- Concept drift monitoring (label feedback delays)
- Compliance: GDPR + PCI + audit trail
#Content Moderation (TikTok / Meta style)
Upload → Multimodal preprocessing
→ Multiple classifiers in parallel (NSFW, hate, spam)
→ Human-in-loop for borderline
→ Action: approve / flag / remove
Background:
- Multi-tenant model serving (100+ models on shared GPUs)
- Adversarial robustness testing
- Localization + cultural context per region
- Appeals + transparency reporting
#Hands-On: Deploy Your Capstone
This is your project. Pick a real problem and deploy it end-to-end.
mlflow, pandas and xgboost, so it does not run on this page. Copy it to Google Colab or your own repository and replace each mock with a real component.# Copy to Colab: needs mlflow, pandas, xgboost, so it cannot run on this page.
# Capstone project skeleton — deploy a fraud-detection model end-to-end
# This is the SHAPE; replace mocks with real components
# === 1. Define the problem ===
# Task: classify transactions as fraud / legitimate
# Latency target: 50ms p95
# Throughput target: 1000 RPS
# Cost target: < $0.001 per request
# === 2. Data pipeline (Airflow DAG) ===
# Ingest → validate → feature engineer → push to feature store
# Code in airflow/dags/fraud_features.py
# === 3. Training (run weekly via CI) ===
import mlflow
import xgboost as xgb
import pandas as pd
mlflow.set_tracking_uri("https://mlflow.yourcompany.com")
with mlflow.start_run():
# Load features from feature store
df = pd.read_parquet("s3://feature-store/fraud/training_v1.parquet")
X, y = df.drop("is_fraud", axis=1), df["is_fraud"]
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, stratify=y)
# Train
model = xgb.XGBClassifier(n_estimators=500, max_depth=6, learning_rate=0.1)
model.fit(X_train, y_train)
# Eval against golden set
val_auc = roc_auc_score(y_val, model.predict_proba(X_val)[:, 1])
mlflow.log_metric("val_auc", val_auc)
# Eval gate: only register if AUC > previous baseline
if val_auc > 0.92:
mlflow.xgboost.log_model(model, "model", registered_model_name="fraud-detector")
# === 4. Deployment (manual approval gate) ===
# Approval gate: ML lead reviews drift checks + eval scores before promoting to Production
# from mlflow.tracking import MlflowClient
# MlflowClient().transition_model_version_stage("fraud-detector", version=42, stage="Production")
# === 5. Serving (FastAPI + Modal) ===
# import modal
# stub = modal.Stub("fraud-detector")
# @stub.function(image=modal.Image.debian_slim().pip_install("xgboost", "fastapi", "pydantic"))
# @modal.web_endpoint(method="POST")
# def predict(transaction: TransactionFeatures):
# # Load model from registry; cache in container
# # Score
# # Log to Langfuse for tracing
# # Return decision
# return {"decision": "allow", "fraud_probability": 0.03}
# === 6. Monitoring (Evidently dashboards) ===
# Daily: input feature drift report
# Weekly: prediction distribution drift
# Monthly: ground-truth label feedback loop (chargeback signal)
# === 7. Incident response (runbooks/) ===
# - "fraud-rate-spike": false-positive ratio jumped — investigate drift
# - "latency-regression": p95 > 100ms — investigate model size, GPU utilization
# - "false-negative-spike": missed fraud — emergency retrain, human-in-loop review
# === 8. Compliance (audit log) ===
# Every prediction logged: timestamp, transaction_id, features_hash, model_version, decision, confidence
# Retention: 7 years for PCI; 90 days for GDPR after user request
print("Capstone checklist:")
print(" [✓] 1. Data pipeline (Airflow + Kafka)")
print(" [✓] 2. Feature store (Feast)")
print(" [✓] 3. Training pipeline (MLflow + DVC)")
print(" [✓] 4. Eval gate (AUC > 0.92 threshold)")
print(" [✓] 5. Approval gate (ML lead manual review)")
print(" [✓] 6. Blue-green deployment")
print(" [✓] 7. Multi-region serving (US + EU)")
print(" [✓] 8. Drift monitoring (Evidently)")
print(" [✓] 9. Cost dashboard (per-user attribution)")
print(" [✓] 10. PagerDuty integration (severity-1)")
print(" [✓] 11. PII handling (GDPR-compliant logs)")
print(" [✓] 12. Audit logging (EU AI Act)")
print(" [✓] 13. Model card (public)")
print(" [✓] 14. Runbooks for top 10 incidents")
print(" [✓] 15. Chaos drills (quarterly)")
print(" [✓] 16. Post-mortem template")
print("\nDeploy your version of this. Bring me a system that passes")
print("all 16 hardening checks. That's the capstone.")
# --- Solution sketch ---
# Real deployment platforms (pick one):
# - Modal (modal.com): serverless GPU, simplest start
# - Anyscale (Ray Serve): scalable distributed serving
# - Vertex AI (GCP): full ML platform, integrated with feature store / pipelines
# - SageMaker (AWS): mature, complex, comprehensive
# - Azure ML: similar to SageMaker, M365 integration
# - RunPod / Lambda Labs: cheapest GPU, more DIY
#
# For a portfolio capstone: Modal + GitHub Actions CI is the lightest path to production-grade.#The Production Engineering Mindset
Production ML is engineering, not research. The mindset shifts:
| Research | Production |
|---|---|
| Maximize accuracy on benchmark | Minimize cost-per-correct-prediction |
| Run experiments | Run incidents |
| Notebooks | DAGs + containers + registries |
| Best-case latency | p95 / p99 latency under load |
| One-time eval | Continuous eval + drift monitoring |
| Single user (you) | Many users + many tenants |
| Failures = paper rejection | Failures = on-call page at 2am |
The best ML engineers think both ways: research mindset to find what's possible, engineering mindset to make it reliable.
#Key Takeaways
- Production ML is integration. The components are well-understood; the hard part is the wiring, the safety, the observability
- The 16-point hardening checklist is your launch readiness gate; never skip an item
- Reference architectures repeat. Chatbot, fraud detection, content moderation share the same skeleton with different models
- Production engineering is a distinct discipline from research engineering, different mindset, different success metrics
- Capstone = a system you can show employers that demonstrates the full stack, not just the model
#Quick Check
What's the single biggest difference between a Jupyter notebook prototype and a production ML system?