How do you serve ML models at low latency and high throughput?
Written by the mlprep team · Updated
How do you serve an ML model at low latency and high throughput in production? What are the main levers?
Model serving sits at the intersection of ML and systems engineering. The key tension: latency (how fast a single request returns) and throughput (how many requests per second you serve) often trade off against each other, and your SLO determines which to optimize.
The serving stack#
A typical inference path: request arrives → feature lookup → preprocessing → model forward pass → postprocessing → response. The model itself is often not the bottleneck — feature retrieval and preprocessing frequently dominate.
Profile before optimizing. Common slow spots:
- Feature store lookups (network calls to Redis/DynamoDB)
- Tokenization or image decoding on CPU
- Model loading overhead per request (load model once, keep in memory)
- Cold starts on serverless infrastructure
Batching#
Running inference on a batch of B inputs uses roughly the same compute as a single input (up to hardware saturation), so throughput scales linearly with batch size. Dynamic batching collects requests that arrive within a short time window (say 10ms) and runs them together, trading a small latency hit for much higher GPU utilization.
For latency-sensitive applications (user-facing, P99 < 50ms), batching window must be tiny or skipped. For throughput-sensitive applications (batch scoring overnight), maximize batch size.
Quantization#
Reduce model weights from float32 to float16 (half precision) or int8. Float16 halves memory bandwidth and often has hardware acceleration (tensor cores on Nvidia GPUs). Int8 can halve it again but requires calibration to avoid accuracy loss. TorchScript's torch.quantization or ONNX Runtime handle this without modifying the model code.
Rule of thumb: float16 is nearly free (1-2% accuracy drop on most models, 1.5-2x speedup). Int8 requires measurement — some models tolerate it, others don't.
Model distillation and pruning#
Distillation trains a smaller "student" model to mimic the outputs of a larger "teacher." The student is 3-10x smaller and faster, with moderate accuracy loss. DistilBERT is 40% smaller and 60% faster than BERT with 97% of its performance.
Pruning removes weights below a threshold. Unstructured pruning (individual weights to zero) is easy but doesn't speed up dense matrix operations. Structured pruning (remove entire attention heads or layers) maps to actual speedups.
Hardware#
GPUs for throughput-heavy workloads (batch scoring, compute-intensive models). CPUs for low-latency simple models (gradient boosted trees, logistic regression score instantly). Dedicated inference hardware (AWS Inferentia, Google TPU) for large-scale deployments.
Framework choice#
TorchServe, Triton Inference Server, or BentoML manage model loading, batching, and scaling. ONNX Runtime provides a portable, optimized runtime across hardware backends. For transformers specifically, vLLM and TensorRT-LLM add paged attention for throughput-efficient LLM serving.
You mentioned int8 quantization requires calibration — what does calibration mean here, and what goes wrong without it?
The quantization problem#
Float32 can represent values roughly in the range ±3.4 × 10³⁸ with ~7 decimal digits of precision. Int8 represents 256 values from -128 to 127. To map floats to int8, you need a scale and zero-point:
x_int8 = round(x_float / scale) + zero_point
The scale determines how much float range maps to the int8 range. If you set scale too small, large activations get clipped (you lose the tails). If you set scale too large, small values quantize to the same integer (you lose precision for small values). Either case degrades accuracy.
What calibration does#
Calibration runs a representative sample of real data through the model before quantization. It observes the actual range of activations at each layer — what are the min/max values that appear in practice? Then it sets the scale to cover that range without clipping.
Without calibration, you either clip important activations or waste resolution on ranges that never appear. Either hurts model accuracy.
Calibration in practice#
PyTorch's post-training quantization:
model.qconfig = torch.quantization.get_default_qconfig('fbgemm')
torch.quantization.prepare(model, inplace=True)
# Run calibration data through the model
with torch.no_grad():
for batch in calibration_loader:
model(batch)
torch.quantization.convert(model, inplace=True)A few hundred to a few thousand representative examples are usually sufficient. The calibration set should cover the distribution of inputs you expect in production — if you calibrate on training data but serve a different distribution, the scales will be wrong.
When calibration isn't enough#
Some layers are sensitive to quantization regardless of calibration — typically the first and last layers, and attention score computations in transformers. Quantization-aware training (QAT) simulates quantization noise during training, allowing the model to adapt its weights to work within int8 constraints. QAT recovers most accuracy when post-training quantization fails.
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Model serving optimizes for latency (single request speed) and throughput (requests per second) — they trade off. Profile first: feature retrieval and preprocessing often dominate over the model itself. Dynamic batching, float16 quantization, and keeping the model warm in memory are the highest-leverage quick wins. Int8 quantization needs calibration data to set activation scales — without it, clipping or precision loss degrades accuracy. Distillation and pruning are the heavier tools for throughput at scale.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- How would you design a serving system that serves both a fast simple model and a slow accurate model, routing between them?
- What is speculative decoding in LLM serving and what problem does it solve?
- How do you set an SLO for a model serving endpoint, and what do you do when the model can't meet it?
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions
How do you make a model smaller and faster without losing much accuracy?
How would you design an LLM serving system for millions of users?
How do you deploy speculative decoding in production — draft selection, tree attention, and batch-size trade-offs?
How do you serve hundreds of fine-tuned LoRA adapters on one base model efficiently?