Build a Production ML Training Pipeline for Time-Series Models
Machine LearningModel answerLast updated
Design a complete ML training system for forecasting, covering data handling, training infrastructure, serving, and monitoring with emphasis on temporal correctness.
You need to architect a complete machine learning training system for time-series forecasting models. Your design should address:
Data Pipeline: How do you handle temporal data ingestion, create windowed samples without lookahead bias, and generate features that work identically in training and production?
Training Infrastructure: What components enable reproducible experiments, efficient training (mixed precision, checkpointing), hyperparameter search, and experiment tracking?
Model Lifecycle: How do you manage model versions, validate models before deployment, and implement safe promotion from development to production?
Serving Architecture: Design both batch and real-time inference paths. How do you ensure feature consistency between training and serving? What latency and throughput targets are reasonable?
Operations: How do you monitor models in production, detect when retraining is needed, implement rollbacks, and maintain the entire system through CI/CD?
Provide a high-level architecture showing key components and their relationships. Define critical interfaces and explain the most important design decisions. Focus on what makes time-series forecasting different from other ML problems.
Hints
Hint 1
The biggest failure mode in time-series ML is data leakage—ensure your validation split and feature computation never use future information
Hint 2
Training and serving must use identical feature logic; consider how to share code between batch and streaming contexts
Hint 3
Reproducibility requires more than just setting seeds—think about data versioning, deterministic operations, and full lineage tracking
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Production Time-Series Training System
The central challenge in time-series ML is temporal integrity: preventing any form of future information leakage while maintaining exact feature parity between training and serving. Everything else flows from this constraint.
Scale and Requirements
Start by establishing concrete targets:
Data volume: 5,000 time series with minute-level granularity over 5 years yields roughly 10 billion observations (~2-3 TB in compressed columnar format).
Training: Sequence models (Transformers, LSTMs, temporal CNNs) training on 1-8 GPUs, typical runs taking 1-10 hours.
Inference requirements:
- Batch: process all series in under 30 minutes nightly
- Streaming: sub-10ms p99 latency, handling 50k requests/second peak
Operational targets: daily or weekly scheduled retraining plus drift-triggered updates, with sub-5-minute rollback capability and full reproducibility.
Architecture Overview
Raw Data Sources
↓
Point-in-Time Data Store (versioned snapshots)
↓
Feature Library (shared pure functions)
↙ ↘
Offline Path Online Path
(batch features) (streaming state)
↓ ↓
Training Dataset Real-time Features
↓ ↓
Experiment Runner Inference Service
↓ ↓
Model Registry → Staging → Production
↓
Monitoring & Drift Detection
↓
Orchestrator (triggers retraining)
The critical design choice: one Feature Library used by both paths. This eliminates train-serve skew.
Core Interfaces
class TemporalDataSource:
"""Point-in-time correct data access"""
def query(self, start_time, end_time, as_of_time) -> DataFrame:
# Returns only data known at as_of_time
pass
class FeatureDefinition:
"""Dual-mode feature: batch and streaming"""
lookback_window: timedelta # history requirement
def compute_batch(self, df: DataFrame) -> Series:
# Vectorized for training
pass
def compute_streaming(self, state: dict, new_data: dict) -> float:
# Incremental update for serving
pass
class TimeSeriesDataset:
"""Sliding windows with temporal splits"""
def __init__(self, data, input_window, forecast_horizon,
stride, temporal_split):
# Creates non-overlapping train/val/test splits
pass
def __getitem__(self, idx) -> tuple[Tensor, Tensor, dict]:
# Returns (input_sequence, targets, metadata)
pass
class ModelSignature:
"""Contract between training and serving"""
feature_names: list[str]
input_length: int
horizon: int
normalization_params: dict
Data Handling (Critical Component)
Point-in-time correctness: Every observation has both event_time (when it occurred) and knowledge_time (when it became available). Training queries use as_of filtering to prevent using revised or late-arriving data that wasn't available at prediction time.
Temporal splitting: Use walk-forward validation with an embargo period equal to the forecast horizon. This prevents label leakage where training targets overlap with validation inputs. Standard k-fold cross-validation is incorrect for time-series because it violates temporal ordering.
Example: for 7-day forecasting, if training ends on day 100, validation cannot start before day 107. The gap ensures no overlap between training labels and validation features.
Window generation: Rather than materializing all windows, maintain an index of (series_id, end_timestamp) tuples and slice on-demand from memory-mapped arrays. Validate that windows don't span data gaps longer than your maximum lookback period.
Feature computation: Write features as pure functions that operate on DataFrames. For each feature, implement both:
- Batch version using vectorized operations (pandas/polars)
- Streaming version maintaining incremental state
Write automated tests that replay historical data through the streaming path and assert agreement with batch computation within numerical tolerance (1e-9).
Normalization: Fit scalers only on training data within each fold. Persist scaler parameters as model artifacts since serving must apply identical transformations.
Training Infrastructure
Reproducibility stack:
- Pin all dependencies with locked versions (requirements.lock)
- Use Docker images referenced by digest, not tags
- Record git SHA and fail if working directory has uncommitted changes
- Set seeds for Python, NumPy, PyTorch (CPU and CUDA)
- Enable deterministic algorithms:
torch.use_deterministic_algorithms(True)andcudnn.benchmark=False - Assign DataLoader worker-specific seeds via
worker_init_fn
Every training run is uniquely identified by: (code_sha, image_digest, data_snapshot_id, config_hash, random_seed)
Configuration management: Use hierarchical config systems (Hydra) with composition. Store the fully resolved config with each run. Version control config files alongside code.
Training optimizations:
- Mixed precision (bfloat16 on modern hardware, fp16 with GradScaler on older GPUs)
- Gradient clipping before optimizer step
- Compiled models when stable (
torch.compile) - Efficient data loading with prefetching and pinned memory
Checkpointing: Save complete state for exact resumption:
- Model weights, optimizer state, scheduler state
- Training progress (epoch, step, best metric)
- All RNG states (Python, NumPy, torch CPU and CUDA)
- Early stopping counters
- Data loader position
Write atomically to object storage (write temp file, then rename). Retain last N checkpoints plus best.
Experiment tracking: Log to MLflow or Weights & Biases:
- Hyperparameters and resolved config
- Training/validation metrics per epoch
- Learning curves and prediction plots
- System metrics (GPU utilization, throughput)
- Data snapshot version and code version
Hyperparameter tuning: Use Optuna or Ray Tune with:
- Pruning to kill unpromising trials early
- Multi-fidelity optimization (train on smaller horizon first)
- Parallel trial execution
- Search spaces that encode domain knowledge (e.g., log-uniform for learning rate)
Model Registry and Promotion
Registry stores:
- Serialized model weights
- Model signature (expected features, input shape, output shape)
- Normalization artifacts
- Training metrics and validation scores
- Full lineage (data version, code version, config)
Promotion gates before production:
- Validation set performance exceeds threshold
- No degradation vs. current production model on holdout set
- Feature schema compatibility check
- Inference latency within SLO (measure on representative hardware)
- Integration test passes (end-to-end prediction flow)
Stages: development → staging → production. Each environment uses separate infrastructure. Staging runs shadow traffic or replays production requests to validate before cutover.
Serving Architecture
Batch inference:
- Scheduled job (Airflow, Prefect) loads model from registry
- Reads latest data snapshot
- Computes features using batch path
- Generates predictions for all series
- Writes results to database/data warehouse
- Target: process 5k series in under 30 minutes
Streaming inference:
- Service loads model at startup
- Maintains feature state per series in memory (or Redis for distributed)
- On request: updates state with new data, computes features via streaming path, runs model
- Returns prediction
- Target: p99 latency <10ms
Feature parity enforcement:
- Shared feature library imported by both paths
- Automated integration tests that compare batch and streaming outputs
- Schema validation ensures serving receives all required features
- Monitoring alerts on feature distribution drift between paths
Scaling: Batch uses horizontal scaling (parallel workers per series partition). Streaming uses load balancers across stateless replicas with sticky sessions or shared state.
Monitoring and Retraining
Model quality monitoring:
- Compare predictions against actuals when labels arrive (realized performance)
- Track calibration (predicted vs actual distributions)
- Monitor prediction diversity (catch mode collapse)
- Alert on error rate increases or accuracy degradation
Data drift detection:
- Compare feature distributions between training data and production (KL divergence, KS test)
- Track missing data rates and anomalies
- Monitor for concept drift using performance on recent windows
System monitoring:
- Inference latency percentiles (p50, p95, p99)
- Throughput and error rates
- Resource utilization
- Feature computation time
Retraining triggers:
- Scheduled (weekly or daily)
- Performance-based: accuracy drops below threshold
- Drift-based: distribution shift exceeds threshold
- Manual trigger from operator
Orchestrator (Airflow) runs triggered retraining, registers new model, promotes through gates, and deploys.
Testing and CI/CD
Test pyramid:
- Unit tests: individual feature computations, model forward pass
- Integration tests: end-to-end training run on toy dataset (minutes), batch vs streaming feature parity
- System tests: full pipeline on subset of real data, rollback procedure
CI pipeline:
- Lint and type checking
- Unit test suite
- Build Docker image
- Fast integration tests on CPU
- Tag and push image on main branch
CD pipeline:
- Staging deployment from main
- Run integration tests against staging
- Manual approval for production
- Blue-green deployment to production
- Automated rollback if health checks fail
Rollback: Registry maintains history. Rollback = promote previous production version. Entire process under 5 minutes. Practice rollbacks regularly.
Common Mistakes
- Lookahead bias: Using validation data to fit scalers, or validation labels overlapping with training targets
- Feature skew: Different feature code in training vs serving, causing silent degradation
- Non-determinism: Not controlling all randomness sources, making bugs unreproducible
- Missing lineage: Unable to identify which data/code produced a given model
- No embargo gap: Validation set contaminated by training label windows
The key differentiator in a strong answer is understanding that time-series systems fail in subtle ways when temporal integrity is violated, and building every component with this constraint in mind.