Deploy ML models at scale with low latency and high reliability
ML inference can be batch (precompute predictions for all entities) or real-time (compute on request). Choose based on latency requirements, data freshness needs, and cost constraints.
When: Predictions can be precomputed
When: Fresh predictions required
Model runs in application process
App Server
├── API Handler
├── Model (loaded in memory)
└── Feature computation
Use for: Simple models, low traffic
Dedicated inference service
App → Model Service → Response
↓
[TF Serving / Triton]
Use for: Large models, multiple consumers
On-demand compute (Lambda, Cloud Functions)
Request → Cold Start → Inference
(or warm)
Use for: Variable traffic, simple models
# Model serving with FastAPI
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import numpy as np
import pickle
import asyncio
from functools import lru_cache
app = FastAPI()
class PredictionRequest(BaseModel):
features: list[float]
user_id: str
class PredictionResponse(BaseModel):
prediction: float
confidence: float
model_version: str
# Load model at startup (singleton pattern)
@lru_cache(maxsize=1)
def get_model():
with open('model.pkl', 'rb') as f:
return pickle.load(f)
@app.post("/predict", response_model=PredictionResponse)
async def predict(request: PredictionRequest):
model = get_model()
# Input validation
if len(request.features) != model.n_features_in_:
raise HTTPException(400, "Feature dimension mismatch")
# Inference
features = np.array(request.features).reshape(1, -1)
prediction = model.predict_proba(features)[0, 1]
return PredictionResponse(
prediction=float(prediction),
confidence=float(max(prediction, 1 - prediction)),
model_version="v1.2.3"
)
# Batch endpoint for efficiency
@app.post("/predict_batch")
async def predict_batch(requests: list[PredictionRequest]):
model = get_model()
features = np.array([r.features for r in requests])
predictions = model.predict_proba(features)[:, 1]
return [
{"user_id": r.user_id, "prediction": float(p)}
for r, p in zip(requests, predictions)
]
# Two-stage recommendation serving
import faiss
import numpy as np
class TwoStageServer:
"""
Stage 1: Retrieval (approximate nearest neighbors)
Stage 2: Ranking (precise scoring)
"""
def __init__(self, item_embeddings, ranking_model, feature_store):
# Build FAISS index for retrieval
self.index = faiss.IndexFlatIP(item_embeddings.shape[1]) # Inner product
self.index.add(item_embeddings.astype('float32'))
self.item_embeddings = item_embeddings
self.ranking_model = ranking_model
self.feature_store = feature_store
async def get_recommendations(self, user_id: str, k: int = 10):
# Stage 1: Retrieval (fast, approximate)
user_embedding = await self.feature_store.get_user_embedding(user_id)
user_embedding = np.array(user_embedding).reshape(1, -1).astype('float32')
# Get top 100 candidates via ANN
n_candidates = 100
scores, candidate_ids = self.index.search(user_embedding, n_candidates)
# Stage 2: Ranking (precise, slower)
# Fetch full features for candidates
user_features = await self.feature_store.get_user_features(user_id)
item_features = await self.feature_store.get_item_features_batch(
candidate_ids[0].tolist()
)
# Score all candidates with ranking model
ranking_features = self._build_ranking_features(
user_features, item_features, candidate_ids[0]
)
ranking_scores = self.ranking_model.predict(ranking_features)
# Return top k by ranking score
top_k_idx = np.argsort(ranking_scores)[::-1][:k]
return [
{
"item_id": int(candidate_ids[0][i]),
"score": float(ranking_scores[i])
}
for i in top_k_idx
]
def _build_ranking_features(self, user_features, item_features, item_ids):
"""Combine user and item features for ranking."""
features = []
for i, item_id in enumerate(item_ids):
combined = {
**user_features,
**item_features[i],
"retrieval_rank": i,
"user_item_similarity": float(np.dot(
user_features.get('embedding', [0]),
item_features[i].get('embedding', [0])
))
}
features.append(list(combined.values()))
return np.array(features)
With millions of items, scoring all of them is infeasible. Stage 1 (retrieval) uses efficient approximate methods (ANN, inverted index) to narrow down to thousands. Stage 2 (ranking) uses full features and complex models on this smaller set. This achieves both coverage and precision within latency budgets.
Optimize in order of impact: Architecture (caching, batching) → Model (quantization, pruning) → Infrastructure (GPUs, edge deployment)
| Technique | Speedup | Accuracy Impact | Best For |
|---|---|---|---|
| Quantization | 2-4x | < 1% loss | Neural networks, embeddings |
| Pruning | 2-10x | 1-3% loss | Large neural networks |
| Distillation | 5-50x | 2-5% loss | Transformers, complex models |
| ONNX Runtime | 1.5-3x | None | Cross-framework optimization |
| TensorRT | 2-6x | < 1% loss | NVIDIA GPU deployment |
# Model quantization example
import torch
from torch.quantization import quantize_dynamic
class ModelOptimizer:
"""
Optimize models for inference.
"""
@staticmethod
def quantize_model(model, dtype=torch.qint8):
"""
Dynamic quantization: weights quantized, activations computed in float
Good for models with large linear layers (transformers, MLPs)
"""
quantized_model = quantize_dynamic(
model,
{torch.nn.Linear, torch.nn.LSTM},
dtype=dtype
)
return quantized_model
@staticmethod
def export_onnx(model, sample_input, output_path):
"""
Export to ONNX for cross-platform optimization.
"""
torch.onnx.export(
model,
sample_input,
output_path,
export_params=True,
opset_version=11,
do_constant_folding=True,
input_names=['input'],
output_names=['output'],
dynamic_axes={
'input': {0: 'batch_size'},
'output': {0: 'batch_size'}
}
)
@staticmethod
def benchmark_inference(model, sample_input, n_runs=100):
"""
Measure inference latency.
"""
import time
# Warmup
for _ in range(10):
_ = model(sample_input)
# Benchmark
latencies = []
for _ in range(n_runs):
start = time.perf_counter()
_ = model(sample_input)
latencies.append((time.perf_counter() - start) * 1000)
return {
'p50': np.percentile(latencies, 50),
'p95': np.percentile(latencies, 95),
'p99': np.percentile(latencies, 99),
'mean': np.mean(latencies)
}
# Knowledge distillation example
class DistillationTrainer:
"""
Train smaller student model to mimic larger teacher.
"""
def __init__(self, teacher_model, student_model, temperature=3.0, alpha=0.5):
self.teacher = teacher_model
self.student = student_model
self.temperature = temperature
self.alpha = alpha # Weight for distillation loss
def distillation_loss(self, student_logits, teacher_logits, true_labels):
"""
Combine soft label loss (from teacher) with hard label loss.
"""
# Soft labels from teacher
soft_teacher = torch.softmax(teacher_logits / self.temperature, dim=1)
soft_student = torch.log_softmax(student_logits / self.temperature, dim=1)
distill_loss = torch.nn.KLDivLoss(reduction='batchmean')(soft_student, soft_teacher)
distill_loss *= self.temperature ** 2 # Scale by T^2
# Hard labels
hard_loss = torch.nn.CrossEntropyLoss()(student_logits, true_labels)
return self.alpha * distill_loss + (1 - self.alpha) * hard_loss
# Multi-level caching for ML serving
import redis
import hashlib
from functools import lru_cache
class PredictionCache:
"""
Multi-level cache: L1 (in-memory) -> L2 (Redis) -> Model
"""
def __init__(self, redis_client, l1_size=10000, ttl_seconds=3600):
self.redis = redis_client
self.ttl = ttl_seconds
# L1: In-memory LRU cache
self._l1_cache = {}
self.l1_size = l1_size
def _cache_key(self, features: tuple) -> str:
"""Generate deterministic cache key from features."""
return hashlib.md5(str(features).encode()).hexdigest()
async def get_prediction(self, features: list, model_fn):
"""
Try caches before computing prediction.
"""
key = self._cache_key(tuple(features))
# L1: Check in-memory cache
if key in self._l1_cache:
return self._l1_cache[key]
# L2: Check Redis
cached = await self.redis.get(f"pred:{key}")
if cached:
prediction = float(cached)
self._update_l1(key, prediction)
return prediction
# Cache miss: compute prediction
prediction = await model_fn(features)
# Update caches
self._update_l1(key, prediction)
await self.redis.setex(f"pred:{key}", self.ttl, str(prediction))
return prediction
def _update_l1(self, key, value):
"""Update L1 cache with LRU eviction."""
if len(self._l1_cache) >= self.l1_size:
# Simple eviction: remove oldest
oldest = next(iter(self._l1_cache))
del self._l1_cache[oldest]
self._l1_cache[key] = value
# When to cache:
# - User embeddings (change slowly)
# - Item features (change with catalog updates)
# - Popular item predictions (high hit rate)
# - Avoid caching: personalized real-time features
# Kubernetes deployment for model serving
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-server
image: model-server:v1.2.3
resources:
requests:
memory: "2Gi"
cpu: "1000m"
limits:
memory: "4Gi"
cpu: "2000m"
ports:
- containerPort: 8080
readinessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 60
periodSeconds: 30
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: model-server-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: model-server
minReplicas: 3
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Pods
pods:
metric:
name: inference_latency_p99
target:
type: AverageValue
averageValue: 100m # 100ms
| Tool | Best For | Key Features |
|---|---|---|
| TensorFlow Serving | TensorFlow models | gRPC, batching, model versioning |
| Triton (NVIDIA) | Multi-framework, GPU | Dynamic batching, ensemble models |
| TorchServe | PyTorch models | Model archiver, metrics, logging |
| Seldon Core | Kubernetes-native | A/B testing, canary, explainability |
| BentoML | Packaging & deployment | Framework agnostic, easy packaging |
| Ray Serve | Complex pipelines | Composition, scaling, Python-native |
When discussing serving, show awareness of tradeoffs: Latency vs Throughput (batching helps throughput but adds latency), Cost vs Performance (GPUs are fast but expensive), Freshness vs Complexity (real-time is harder than batch). The best architecture depends on requirements.
Systematic optimization approach:
Preparation (before spike):
During spike:
Graceful degradation hierarchy:
The tradeoff:
Why batching helps throughput:
Dynamic batching strategies:
# Dynamic batching pseudocode
batch = []
batch_timeout = 10ms
max_batch_size = 32
while True:
request = wait_for_request(timeout=batch_timeout)
if request:
batch.append(request)
if len(batch) >= max_batch_size or timeout_reached:
process_batch(batch)
batch = []