What You'll Learn
- 1Decompose an end-to-end latency budget into network, queue, inference, and post-processing terms
- 2Pick a quantization precision from model size, memory, and accuracy constraints
- 3Choose a batch size from the throughput curve instead of the largest batch that fits
- 4Compute the cache hit rate a latency SLO actually requires
Why This Matters
Real-time inference is critical for applications where latency directly impacts user experience and business outcomes:
- User Engagement: 100ms delay can reduce conversions by 7%
- Competitive Advantage: Faster predictions enable real-time personalization
- System Efficiency: Optimized inference reduces infrastructure costs
- Scalability: Handle millions of requests without degradation
âšī¸
Real-time ML inference is not just about speed, it's about maintaining accuracy while achieving low latency at scale.
Low-Latency Serving Architecture
Model Quantization
PyTorch Quantization
Quantization reduces model precision from FP32 to INT8 or FP16 for faster inference. PyTorch supports dynamic quantization (applied at inference time), static quantization (applied after calibration with representative data), and per-tensor quantization for fine-grained control. Static quantization provides better performance but requires a calibration step.
TensorFlow Quantization
TensorFlow Lite provides post-training quantization and float16 quantization. Post-training quantization converts models to INT8 with a representative dataset for calibration. Float16 quantization reduces model size while maintaining good accuracy, making it ideal for GPU inference.
GPU Inference Optimization
GPU inference leverages mixed precision (FP16/FP32) for faster computation while maintaining accuracy. Key techniques include:
- Mixed Precision: Use AMP (Automatic Mixed Precision) for automatic FP16/FP32 switching
- TorchScript: Compile models to TorchScript for optimized execution
- Batch Processing: Process multiple inputs simultaneously for better GPU utilization
- Model Freezing: Disable gradient computation for inference-only workloads
Dynamic Batching
Dynamic batching collects individual inference requests and processes them together as a batch. This dramatically improves GPU utilization by filling the parallel processing capacity. Requests are queued, and when either the batch size threshold or time limit is reached, the entire batch is processed and results are distributed back to individual requestors.
Edge Deployment
Edge deployment converts models for on-device inference:
- TensorFlow Lite: Optimized format for Android/mobile with INT8 quantization and representative dataset calibration
- CoreML: Apple's format for iOS devices with image input types and classifier configurations
- ONNX with FP16: Cross-platform format with float16 conversion for reduced size and faster inference
Caching Strategies
Inference caching stores predictions to avoid redundant computation. The cache class provides:
- Cache Key Generation: Unique keys from model name + features using MD5 hashing
- Get/Set Operations: Redis-backed storage with configurable TTL
- Invalidation: Remove cached predictions when models update
- Get-or-Compute: Cache-aside pattern that computes and caches on miss
Latency Monitoring
Latency monitoring tracks inference performance across multiple dimensions:
- Timer-based tracking: Start/end timing per request with automatic duration calculation
- Percentile metrics: P50, P90, P95, P99 latencies for comprehensive visibility
- SLA checking: Verify that latency targets are met (e.g., P99 < 100ms)
- Statistics aggregation: Mean, count, and distribution analysis
The Latency Budget, Item by Item
Sub-10 ms is not one number, it is six that must add up. The request pays for transport, gateway work, feature fetch, queueing, inference, and post-processing:
A realistic on-device budget inside a 10 ms ceiling is 1 ms network or inter-process hop, 1 ms gateway, 2 ms feature lookup from an in-process cache, 1 ms of queueing, 4 ms of inference, and 1 ms to format the answer. That sums to 10 ms with nothing left, which is why the same architecture in a cloud region, where the network term alone is 10 to 30 ms, cannot promise single-digit latency at all. Placement decision first, model optimization second.
Precision, Memory, and Speed
Model memory scales with parameter count and bytes per weight :
A 700 million parameter model is 2.8 GB at FP32, 1.4 GB at FP16, and 0.7 GB at INT8. For memory-bound layers, speedup from precision alone tracks the byte ratio:
In practice you measure 2x to 3x rather than the theoretical 4x, because activations, kernel launch overhead, and dequantization steps do not shrink with the weights. The honest trade is a 0.5 to 1.5 point accuracy drop against a 2x to 3x speedup, which is almost always worth it for ranking and recommendation models and often not for medical or scoring models where a single point of AUC is expensive.
Where Batching Stops Helping
Dynamic batching is a curve, not a switch. If a batch takes ms of fixed overhead plus ms per item, throughput in requests per second is:
With ms of kernel and scheduling overhead and ms per item: a batch of 1 gives 118 QPS, 16 gives 1,000, 64 gives 1,600, and 128 gives 1,778. The curve flattens after about 64, while queue wait keeps growing linearly with batch size. Pick the knee of the curve, cap batch delay at roughly 10 ms, and let the extra batch time buy throughput only until it starts spending your p99.
Cache Hit Rate Required by the SLO
A prediction cache changes the latency distribution only if you know the hit rate your SLO demands. Solving for the required hit rate :
With 1 ms hits, 50 ms misses, and a 5 ms SLO, you need , which is 91.8 percent. Below that, the miss path dominates and no amount of Redis tuning rescues the tail. Measure hit rate per feature group: a single low-cardinality key type can hide a miss storm behind a healthy global average.
Interview Q&A
âšī¸
Q: How do you achieve sub-10ms latency for ML predictions?
Answer:
| Strategy | Implementation | Latency Reduction |
|---|---|---|
| Model Optimization | Quantization, pruning | 2-5x faster |
| Hardware Acceleration | GPU/TPU inference | 10-100x faster |
| Caching | Redis feature cache | 50-90% reduction |
| Batching | Dynamic batching | 2-4x throughput |
| Edge Computing | On-device inference | <5ms |
âšī¸
Q: How do you handle model size constraints for edge deployment?
Answer:
- Model Compression: Quantization, pruning, knowledge distillation
- Architecture Selection: Use efficient architectures (MobileNet, EfficientNet)
- Feature Selection: Reduce input features
- Hardware-Aware Design: Optimize for target hardware
Edge model optimization follows a multi-step process: knowledge distillation creates a smaller student model, quantization reduces precision, pruning removes unnecessary weights, and the final model is verified against size constraints.
âšī¸
Q: How do you monitor and optimize inference performance?
Answer:
- Latency Tracking: P50, P90, P95, P99 latencies
- Throughput Monitoring: Requests per second
- Resource Utilization: GPU/CPU memory and compute
- Error Rate Tracking: Failed predictions
- Cost Analysis: Cost per prediction
Common Mistakes
Chasing model speedup while the network and feature fetch dominate the budget
Fix: Time each stage first; halving a 4 ms inference term helps far less than removing a 30 ms network hop.
Using the largest batch the GPU memory allows
Fix: Pick the knee of the QPS curve, around batch 64 in the worked example, and cap queue delay at 10 ms.
Optimizing for average latency
Fix: Report p95 and p99 per stage, because queueing and cache misses hide in the tail you never graphed.
Best Practices
- Publish a latency budget table with a row per stage before any optimization work starts
- Quantize by default and validate accuracy on a held-out slice before shipping, then keep the FP16 fallback
- Track cache hit rate per feature group, since the SLO usually requires more than 90 percent hits
Key Takeaways
- A 10 ms on-device budget splits 1 + 1 + 2 + 1 + 4 + 1 across network, gateway, features, queue, inference, and post
- A 700M parameter model is 2.8 GB at FP32, 1.4 GB at FP16, and 0.7 GB at INT8, with 2x to 3x measured speedup
- Batching returns QPS = 1000b / (T0 + b t): 118 at batch 1, 1,600 at batch 64, only 1,778 at batch 128
- With 1 ms hits and 50 ms misses, a 5 ms SLO requires at least 91.8 percent cache hit rate
Frequently Asked Questions
Can a cloud service really promise sub-10 ms inference?
Rarely, because transport alone often costs 10 to 30 ms before the model runs. Single-digit latency means the model runs on the device, in the browser, or in the same rack as the caller with an in-process feature cache. The usual compromise is a 40 to 60 ms cloud budget for interactive features and on-device inference only where the privacy or responsiveness requirement is absolute.
Is INT8 quantization always safe?
It depends on the margin the model has. Ranking and embedding models usually lose well under a point of AUC because the score ordering barely changes, while finely calibrated classifiers or models with a heavy tail of rare classes can lose more. Always evaluate on a held-out slice that includes the rare classes, keep the FP16 artifact for rollback, and treat quantization as a measured change rather than a build flag.
Why does latency get worse under load even though the model is unchanged?
Because requests queue. Expected wait grows with utilization as rho over (1 - rho), so going from 50 to 90 percent utilization multiplies queue delay by about nine while inference time stays constant. The model is unchanged; the arrival pattern is now competing for the same batch slots. Add capacity or reduce batch fill time rather than tuning the model.
Interview Questions
Q1: How do you build a latency budget for a 10 ms target?
Assign every stage a fixed share before optimizing: 1 ms transport, 1 ms gateway, 2 ms feature lookup, 1 ms queue, 4 ms inference, 1 ms serialization. Anything that cannot fit its share is either moved closer to the caller or dropped from the path, because a budget with no slack breaks on the first retry.
Q2: You quantized to INT8 and throughput tripled but one class of predictions degraded. What now?
Isolate whether the loss comes from weights or activations by evaluating per-class AUC on a held-out slice, then try mixed precision: keep the sensitive layers at FP16 and quantize the rest. If the loss persists, fall back to FP16 for that model and treat INT8 as opt-in per model rather than a global default.
Q3: Where does dynamic batching stop being worth it?
At the knee of the QPS curve. With 8 ms fixed overhead and 0.5 ms per item, batch 64 gives 1,600 QPS while batch 128 gives only 1,778 for twice the queue wait. Cap batch delay near 10 ms of the budget and stop spending p99 on throughput you will not use.
Quiz
Next Steps
- Module 6: Batch Prediction Systems - Learn large-scale scoring
- Module 7: Recommendation System Design - Apply inference to recommendations
- Practice: Build a real-time inference system for a use case
Continue to Batch Prediction Systems ->