What You'll Learn
- 1Decide between real-time, near-real-time, and batch serving from the freshness requirement
- 2Compute replicas, batch size, and cost per prediction for a target QPS
- 3Explain why queueing delay explodes as GPU utilization passes about 70 percent
- 4Design rollout, A/B split, and rollback so a bad model is a non-event
Why This Matters
Model serving is the bridge between trained models and real-world applications:
- Business Impact: Faster deployment means faster value realization
- User Experience: Low-latency serving enables real-time features
- Cost Efficiency: Optimized serving reduces infrastructure costs
- Reliability: Production serving requires high availability
â ī¸
A model that cannot be served reliably in production has zero business value, regardless of its accuracy.
Real-Time vs Batch Serving
Real-Time Serving
- Latency: <100ms
- Throughput: 1000-100,000 QPS
- Use Cases: Recommendations, fraud detection, search ranking
- Infrastructure: GPU clusters, load balancers
Batch Serving
- Latency: Minutes to hours
- Throughput: Millions of predictions
- Use Cases: Email campaigns, analytics, reporting
- Infrastructure: Spark clusters, job queues
Model Serving Architecture
Model Serialization Formats
Model serialization converts trained models into portable formats for serving. Key formats include:
- PyTorch TorchScript: JIT-compiled models for production deployment, saved as
.ptfiles - ONNX: Framework-agnostic format optimized for inference across different hardware
- TensorFlow SavedModel: Complete TensorFlow model with weights and computation graph
- TensorFlow Lite: Optimized format for mobile and edge deployment
Inference Server Implementations
TorchServe
TorchServe is PyTorch's model serving solution. A custom handler class extends BaseHandler and implements four key methods: initialize (load model), preprocess (transform input), inference (run prediction), and postprocess (format output). This architecture cleanly separates concerns and enables flexible model serving.
Triton Inference Server
NVIDIA Triton provides high-performance inference with features like dynamic batching, model ensembles, and multi-framework support. A model configuration file (config.pbtxt) defines input/output specifications, instance groups (GPU/CPU), and batching parameters. A client sends inference requests via gRPC and receives predictions.
Latency Optimization
Model Optimization
- Quantization: Reduces model precision (FP32 -> INT8) for faster inference with minimal accuracy loss
- Pruning: Removes unnecessary weights to reduce model size and computation
- ONNX Optimization: Uses ONNX Runtime with hardware-specific providers (CUDA, CPU) for optimized execution
Caching Strategies
Prediction caching stores frequently requested results to avoid redundant computation. A cache class generates unique keys from input features (using MD5 hashing), stores predictions in Redis with configurable TTL, and supports both direct cache lookups and compute-if-missing patterns. LRU caching provides in-memory caching for hot predictions.
Batching Optimization
Dynamic batching groups multiple inference requests to improve GPU utilization. Requests are collected in a queue, and when the batch size threshold or time limit is reached, the batch is processed together. This significantly improves throughput compared to processing requests individually.
A/B Testing Framework
An A/B testing framework enables controlled experiments with model variants. It handles experiment creation, deterministic user-to-variant assignment (using hash-based routing), prediction routing to the appropriate model, metrics collection, and statistical analysis (using t-tests to determine if differences are significant).
Capacity Math for a Serving Endpoint
A serving endpoint is sized by three numbers: requests per second, the batch the hardware processes together, and how long one batch takes. Dynamic batching turns per-request load into per-batch throughput:
A GPU that clears a batch of requests in ms sustains 800 QPS. Traffic smoothing on real traffic is rarely kind, so keep the fleet under target utilization :
Eighteen replicas at USD 2.00 per GPU-hour costs USD 36.00 per hour, and at 10,000 QPS the cost per prediction is:
That is USD 1.00 per million predictions for the hardware alone, before feature store, networking, and observability, which usually add 30 to 50 percent. Double the batch size and you halve the fleet, but you also add queueing delay for the requests that waited to fill the batch.
Queueing is where latency targets die. End-to-end latency decomposes into:
Only the first and last terms are stable. In a queueing system, expected wait grows with utilization roughly as : at 50 percent utilization the multiplier is 1, at 90 percent it is 9, and at 95 percent it is 19. A model that infers in 30 ms at idle will spend 200 ms in queue at 95 percent load while its GPU looks busy and healthy. Hold steady-state utilization near 70 percent, set the autoscaler to react on queue depth rather than CPU, and treat a batch delay larger than about 10 ms of the budget as a capacity signal rather than a tuning nuisance.
Cold start is the last sizing term. Loading a 700M parameter model from object storage takes 20 to 60 seconds per replica, so scale-from-zero events need warm min replicas during known traffic peaks, or you will serve a wave of timeouts exactly when traffic arrives. Preload model artifacts on node startup, keep one warm replica per version during a rollout, and let the load balancer drain rather than kill in-flight batches.
Interview Q&A
âšī¸
Q: How do you handle model versioning in production?
Answer:
- Semantic Versioning: Use major.minor.patch format
- Model Registry: Central repository for all model versions
- Traffic Splitting: Gradual rollout of new versions
- Rollback Capability: Quick reversion to previous versions
A model version manager handles deployment by registering models, updating traffic splits, and setting up monitoring. Rollback reverts to the previous known-good version with full traffic.
âšī¸
Q: How do you optimize model serving for cost efficiency?
Answer:
| Strategy | Implementation | Cost Savings |
|---|---|---|
| Auto-scaling | Scale based on traffic | 30-50% |
| Spot Instances | Use preemptible VMs | 60-70% |
| Model Optimization | Quantization, pruning | 40-60% |
| Caching | Cache frequent predictions | 50-70% |
| Batching | Group predictions | 20-30% |
âšī¸
Q: How do you ensure high availability in model serving?
Answer:
- Multi-Region Deployment: Deploy across multiple regions
- Health Checks: Regular health monitoring
- Circuit Breakers: Prevent cascade failures
- Graceful Degradation: Fallback to simpler models
Common Mistakes
Autoscaling on CPU while the GPU queue grows
Fix: Scale on queue depth and pending batch count, since a busy GPU with a full queue still violates the p99.
Deploying the new model with an instant traffic flip
Fix: Roll out at 1, 5, 25, then 100 percent with automatic rollback on latency or error thresholds.
Treating cost per prediction as a fixed property of the model
Fix: Recompute it whenever batch size, utilization, or instance price changes, because N depends on all three.
Best Practices
- Keep steady-state utilization near 70 percent and let the autoscaler own the spikes
- Pin warm replicas for each model version during rollout so cold starts never hit users
- Log model version, batch size, and queue time on every prediction so rollbacks are evidence-driven
Key Takeaways
- Per-replica throughput is batch over batch time: 32 requests in 40 ms is 800 QPS per GPU
- Fleet size is ceil(QPS / (QPS_replica x U)): 10,000 QPS at 70 percent utilization needs 18 replicas
- Cost per prediction at 18 replicas and USD 2 per GPU-hour is 1e-6 USD, about USD 1.00 per million predictions
- Queue wait grows with rho over (1 - rho): a 30 ms model waits 9x longer at 90 percent load than at 50 percent
Frequently Asked Questions
Real-time or batch: how do I choose?
Ask whether the prediction changes the outcome of the request in front of you. If it does, as with fraud checks, ranking, or dynamic pricing, it must return inside the request and you pay for always-on capacity. If the result is consumed later, as with nightly recommendations or lead scoring, batch scoring on spot instances typically costs 5 to 10 times less per prediction because you buy capacity by the minute instead of by the hour.
Why does p99 latency explode while average latency looks fine?
Because queueing delay is paid by the requests that arrive during a busy moment, and the average hides them. At 90 percent utilization the expected wait is nine times what it is at 50 percent, so a minority of requests sees hundreds of milliseconds while the mean moves by single digits. Watch p99 and queue depth together; the average alone will reassure you right up until the outage.
How many replicas should I keep warm for a new version?
One per version is the usual floor, plus enough warm capacity to absorb the canary slice. A 700 MB to 3 GB model takes 20 to 60 seconds to load, so a scale-from-zero event during a rollout produces timeouts in exactly the window you are trying to protect. Preload artifacts on node boot, keep the old version at full capacity until the new one has drained its cold start, then retire it.
Interview Questions
Q1: Walk me through sizing a serving fleet for 10,000 QPS with a 100 ms p99 target.
Measure one batch: 32 requests in 40 ms gives 800 QPS per replica. Divide peak QPS by per-replica throughput at 70 percent utilization: 10,000 / (800 x 0.7) = 18 replicas. Confirm the budget with the queue term, because inference may be 30 ms while queueing takes the rest.
Q2: Utilization is at 95 percent and p99 is 400 ms, but the model is fast. What is wrong?
Queueing, not compute. Wait scales as rho over (1 - rho), so the last 5 percent of utilization multiplies delay by 19. Add capacity or cut batch fill time, and move the autoscaler signal from CPU to queue depth so it reacts before the tail grows.
Q3: How do you roll back a model that is degrading quality without raising errors?
Watch a lagged outcome metric such as CTR, approval rate, or chargeback rate against the control arm, not just error rate. Keep the previous version loaded and its traffic split intact so rollback is a config change taking seconds, and record the decision with the metric that triggered it.
Quiz
Next Steps
- Module 5: Real-Time ML Inference - Deep dive into low-latency serving
- Module 6: Batch Prediction Systems - Learn large-scale scoring
- Practice: Design a model serving system for a recommendation engine
Continue to Real-Time ML Inference ->