Chapter
ML Systems
Training vs inference, feature stores, drift, and online/offline consistency for ML platform interviews.
Training vs Inference
Training optimizes model parameters on datasets; inference serves predictions under latency and availability SLOs. Confusing the two — or ignoring serving constraints while designing training — is a classic interview miss.
| Dimension | Training | Inference |
|---|---|---|
| Objective | Minimize loss / maximize reward | Meet quality + latency + cost |
| Compute | Throughput-oriented GPUs | Latency-oriented, autoscaled |
| Data | Large batches, shuffled | Single examples / microbatches |
| Failure mode | Wasted $ / bad checkpoint | User-facing outage |
| Versioning | Experiment tracking | Canary + rollback |
- Pin model artifact digests in serving; never "latest" in production
- Batch inference for offline jobs; stream for online paths
- Quantization, distillation, and caching are inference-side cost levers
- Training-serving skew is its own failure class — keep feature parity
Data → Train → Eval → Register model
↓
Package (image/weights)
↓
Shadow → Canary → Full serve
↓
Monitor → Retrain triggerInterview signal
State SLOs for inference (p99, error rate) separately from training KPIs (loss, AUC). Show you know who on-calls which system.
LLM twist
For LLM products, "training" may be fine-tunes while "inference" is API or self-hosted serving — same separation of concerns applies.
Feature Stores Basics
A feature store centralizes feature definitions, materialization, and serving so training and inference share consistent logic. Interviews test whether you understand point-in-time correctness and online/offline splits.
| Component | Role |
|---|---|
| Feature definitions | Code/SQL that computes signals |
| Offline store | Historical features for training (warehouse) |
| Online store | Low-latency KV for serving |
| Materialization jobs | Batch/stream pipelines filling stores |
| Registry / catalog | Discovery, owners, SLAs |
- Define features once; generate training rows with point-in-time joins
- Serve the same feature values online that training would have seen
- Version feature logic; breaking changes need model retrain
- Monitor freshness and null rates per feature
Events / batch tables
│
Feature pipelines
/ \
Offline store Online store (Redis/Dynamo)
(train join) │
│ ▼
Train set Model server reads features
│ │
└── same definitions ──┘Leakage
Using future information in training features inflates offline metrics and tanks production. Point-in-time joins are non-negotiable.
When to mention
Any ranking, fraud, or personalization design should name a feature store or equivalent shared feature layer.
Training–Serving Skew
Training–serving skew is any mismatch between features or preprocessing at train time versus serve time. It silently destroys model quality and is a favorite ML systems interview probe.
| Skew source | Example | Fix |
|---|---|---|
| Code fork | Different normalization in two repos | Shared library / feature store |
| Data freshness | Train on T-1, serve stale cache | Freshness SLOs + alerts |
| Defaulting | Train drops nulls; serve fills 0 | Explicit default policies |
| Timezone / IDs | Join key mismatch | Canonical entity keys |
| Embedding model | Train with v1, serve v2 vectors | Version pins + migrations |
- Log serving feature vectors and compare distributions to training
- Shadow compute offline features for a sample of live traffic
- Integration tests: same input → same features in both paths
- Treat schema evolution as a coordinated deploy across pipelines and models
Debugging story
"Offline AUC looked great; production tanked — we found a timezone bug in the online join." Walk the detection method, not just the bug.
LLM RAG analog
Skew also appears when eval uses different chunking/embeddings than production retrieval. Keep eval pipelines identical to prod configs.
Drift Monitoring
Drift is distribution shift in inputs, features, or predictions over time. Concept drift changes the label relationship; data drift changes the input mix. Production ML interviews expect detection, triage, and retrain triggers.
| Signal | Detect with | Action |
|---|---|---|
| Feature drift | PSI, KL, mean/var shifts | Investigate upstream data |
| Prediction drift | Score distribution change | Check calibration / traffic mix |
| Performance drift | Lagged labels / human feedback | Retrain or rollback |
| Embedding drift | Centroid shifts in RAG corpus | Re-index / refresh docs |
- Establish baselines from a stable production window
- Alert on sustained drift, not single-day noise
- Separate traffic-mix changes (new market) from true concept drift
- Automate retrain only when labels and pipelines are trustworthy
Live traffic → log features/preds
↓
Drift detectors
↓
┌───────┴───────┐
Data issue Model issue
(fix ETL) (retrain/canary)
↓
Postmortem + thresholdsLabel delay
Many domains lack immediate ground truth. Use proxy metrics (thumbs, edit distance, downstream conversion) carefully and disclose lag in interviews.
Interview signal
Name at least one statistical drift metric and one product metric. Pure stats without business impact is incomplete.
Online & Offline Pipelines
Offline pipelines process batches for training, backfills, and reports. Online pipelines serve low-latency features and predictions. Designs that ignore consistency between them fail at scale.
| Mode | Latency | Typical tech | Use |
|---|---|---|---|
| Offline batch | Minutes–hours | Spark/warehouse dbt | Train sets, reports |
| Nearline stream | Seconds | Kafka + Flink | Fresh features |
| Online serve | ms | KV + model server | User requests |
| Async LLM jobs | Seconds–minutes | Queues + workers | Long agents, evals |
- Backfill story: how you recompute features after a bug
- Exactly-once vs at-least-once: know your consumer idempotency
- Late events: watermark policies for streaming features
- Cost: offline can recompute cheaply; online must be lean
Events
/ \
Batch Stream
│ │
Offline Speed features
features │
\ /
Serving merge
│
PredictionWhat to propose
Start with batch + simple online reads. Add streaming when freshness SLOs demand it — and name the freshness number.
Model Serving Patterns
Serving patterns include synchronous APIs, batch scorers, streaming, and LLM gateways with queues. Choose based on SLA, fan-out, and whether GPUs are involved.
| Pattern | When | Watch out |
|---|---|---|
| Sync REST/gRPC | Interactive UX | Tail latency, timeouts |
| Async job + poll | Long generations | UX complexity |
| Batch score | Nightly rankings | Stale scores |
| Gateway + router | Multi-model products | Observability sprawl |
| Edge / on-device | Privacy, offline | Model size limits |
- Autoscale on queue depth and GPU utilization, not just CPU
- Canary by traffic % with automatic rollback on error/latency
- Isolate noisy neighbors: separate pools for huge prompts vs tiny classifiers
- Cache embeddings and frequent completions where safe
LLM gateway
Centralize auth, rate limits, prompt logging (redacted), and provider failover in one gateway — teams otherwise reinvent it per service.
Interview signal
Tie serving choice to p99 budget and cost. Mention canary and rollback without being asked.
Staff depth layer
ML Systems — Staff Depth
Even in LLM-heavy interviews, staff engineers still speak feature stores, training/serving skew, batch vs online paths, and inference capacity planning. Connect classical ML serving patterns to LLM inference: queues, batching, caching, model registries, and clear ownership of data contracts.
Anti-patterns → say instead
✕ Notebook → production copy-paste
Hidden data dependencies, nondeterministic preprocessing, and no model lineage break rollback and debugging.
Say instead: Registry with model card, feature contract, eval report, canary, and one-click rollback to prior artifact.
✕ Ignoring training/serving skew
Offline AUC looks great while online features are stale or computed differently.
Say instead: Share feature definitions; monitor skew; point-in-time correct labels for training.
✕ One giant synchronous inference path
Peak QPS without batching/queues melts GPUs or blows p99 for everyone.
Say instead: Separate interactive vs batch; continuous batching for LLMs; backpressure and load shedding.
✕ Feature store as a dumping ground
Undocumented features with unclear freshness SLAs become unowned landmines.
Say instead: Owners, SLAs, PII classification, and consumers listed per feature entity.
7B chat model, avg 800 input + 200 output tokens, target 20 QPS steady, burst 60 QPS for 5 minutes.
- Tokens/sec needed ≈ 20 × (800+200) = 20,000 tok/s aggregate (rough; decode-bound on generation).
- Measure single-GPU decode tok/s with expected batch (e.g. 2,500 tok/s decode on a given GPU config) → need ~8 GPUs at 20 QPS if generation-heavy.
- Add continuous batching + prefix cache; expect 1.5–3× effective throughput depending on shareable prefixes.
- Burst 60 QPS: queue with timeout, degrade to smaller distilled model, or shed non-premium traffic — don't silently miss SLO.
- Cost sketch: 8× A100-class ≈ cloud $24–40/hr → $17k–29k/mo before replicas for HA; compare to API mid-tier at 20×86400×1000tok × $/1M.
- 20 QPS × 1k tokens/req ≈ 1.728B tokens/day
- API at $0.50/1M in + $1.50/1M out blend ~$1/1M → roughly $1.7k/day if all API — motivates self-host or cascade
- p99 budget: queue 100ms + prefills + decode; stream first token < 500ms for UX
Capacity plan from tokens/sec and batching reality; always name the degradation story for bursts.
Cheat sheet
- Model registry + lineage + rollback
- Watch training/serving skew
- Batch vs online paths drawn separately
- LLM serving: continuous batching, KV cache, speculative decoding
- Load shed / degrade models under burst
- Feature ownership and PII labels
- Canary + shadow before full traffic