ML Notes
Different approaches to deploying ML models: batch, real-time, shadow, canary, blue-green, and A/B testing.
Different deployment approaches serve different needs. Choose based on latency requirements, risk tolerance, and traffic patterns.
Deployment Types
1. Batch Deployment
Process data in batches, generate predictions offline, store results.
Use when:
- Latency not critical (can wait hours)
- Process large datasets efficiently
- Lower computational cost
- Predictions don't need to be real-time
Example: Daily email recommendations
def batch_predict_emails():
all_users = load_all_users()
for batch in chunks(all_users, batch_size=1000):
user_features = prepare_features(batch)
predictions = model.predict(user_features)
store_predictions(batch, predictions)
# Send emails tomorrow morning2. Real-time/Online Deployment
Generate predictions immediately on request, low latency required.
Use when:
- Latency critical (must respond quickly)
- Unpredictable request patterns
- Individual predictions needed
- Can't batch process
Example: Credit card fraud detection
@app.post("/check_transaction")
def check_transaction(transaction):
risk_score = model.predict(transaction)
if risk_score > 0.8:
return {"status": "blocked", "reason": "fraud_risk"}
else:
return {"status": "approved"}Latency considerations:
- <10ms: Very fast (cache possible)
- 10-100ms: Fast (acceptable for most)
- 100-1000ms: Acceptable for some user interactions
- >1000ms: Too slow for interactive use
3. Shadow Deployment
Run new model alongside current, capture predictions but don't use them.
Process:
- Deploy new model to prod environment
- Run both models on same data
- Compare predictions, log differences
- Monitor performance without risking users
Benefits:
- Test new model in real production environment
- Compare predictions with actual data
- No risk to end users
- Can run indefinitely until confident
Implementation:
class ShadowDeployment:
def __init__(self, current_model, new_model, logger):
self.current_model = current_model
self.new_model = new_model
self.logger = logger
def predict(self, X):
# Production prediction (current)
current_pred = self.current_model.predict(X)
# Shadow prediction (new, logged)
new_pred = self.new_model.predict(X)
# Log comparison
difference = np.abs(current_pred - new_pred).mean()
self.logger.info(f"Shadow diff: {difference:.4f}")
# Return current (don't use new yet)
return current_pred4. Canary Deployment
Gradually increase traffic to new model, monitor closely, roll back if issues.
| ├─ Hour 1-2: 5% traffic | New Model, 95% → Current |
| ├─ Hour 3-4: 10% traffic | New Model |
| ├─ Hour 5-24 | 25%, 50%, 75% gradually |
| └─ If healthy: 100% traffic | New Model |
Steps:
- Deploy new model to production
- Route small percentage (5%) of traffic to new model
- Monitor metrics carefully
- Gradually increase traffic: 10% → 25% → 50% → 100%
- Keep old model ready for instant rollback
Benefits:
- Low-risk rollout
- Early detection of issues
- Smooth transition
- Easy rollback if problems
Implementation:
def canary_deployment(user_id, X):
"""Route percentage of traffic to new model"""
canary_percentage = get_current_canary_traffic() # 5%, 10%, 25%...
# Consistent assignment (same user always routed same way)
hash_value = int(hashlib.md5(str(user_id).encode()).hexdigest(), 16)
user_bucket = hash_value % 100
if user_bucket < canary_percentage:
prediction, model_used = new_model.predict(X), 'new'
else:
prediction, model_used = current_model.predict(X), 'current'
# Log which model was used
log_deployment(user_id, model_used, prediction)
return prediction5. Blue-Green Deployment
Two identical production environments, switch between them.
Process:
- Deploy new model to green environment
- Run full test suite on green
- Switch router to direct traffic to green
- Keep blue as instant rollback option
- After stable, retire blue
Benefits:
- Atomic switch (no gradual transition)
- Easy rollback
- Full environment tested
6. A/B Testing Deployment
Compare two models on random samples, measure statistical significance.
| ├─ 50% Control Group | Model A (current) |
| └─ 50% Treatment Group | Model B (new) |
| Measure | Click rate, conversion, engagement, revenue |
| Duration | 2 weeks (enough for statistical significance) |
Process:
- Randomly assign users to control/treatment
- Serve different models
- Collect metrics for both groups
- Statistical test (t-test, chi-square)
- If significant improvement: deploy to all
Implementation:
Recommended Deployment Flow
| ├─ If healthy | increase to 10% |
| ├─ 10% | 25% → 50% → 100% |
| ├─ Each stage | 2-4 hours |
Risk Management
Metrics to Monitor
| Metric | Target | Alert Threshold |
|---|---|---|
| Error rate | <0.1% | >0.5% |
| Latency p99 | <100ms | >500ms |
| Model accuracy | baseline | -5% drop |
| Data quality | baseline | Any drift |
Rollback Triggers
Automatic rollback if:
- Error rate spikes >1%
- Latency p99 > 5 seconds
- Model accuracy drops >10%
- Data quality check fails
- Manual override by operator
Summary
Deployment strategies:
- Batch: When latency not critical
- Real-time: When fast response needed
- Shadow: Test in production safely
- Canary: Gradual rollout with monitoring
- Blue-Green: Atomic switching
- A/B Test: Statistical comparison
Choose based on risk tolerance, latency needs, and business requirements.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Model Deployment Strategies.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Machine Learning topic.
Search Terms
machine-learning, machine learning, machine, learning, mlops, model, deployment, model deployment strategies
Related Machine Learning Topics