Build a Real-Time ML Prediction Service
Machine LearningModel answerLast updated
Design an ML inference API that serves predictions in milliseconds, handling multitenancy, model rollouts, monitoring, and graceful degradation.
You need to design a production machine learning inference service that delivers predictions with strict latency guarantees. The system must handle real-time scoring requests for multiple tenants, serve different model types (gradient-boosted trees and transformers), and maintain high availability.
Your design should address:
Core requirements:
- Define concrete latency and availability targets and show how you'll meet them
- Specify the API contract: request/response format, authentication, and tenant isolation
- Propose a complete architecture from edge to model execution
Technical depth:
- How will you retrieve features quickly enough to meet latency budgets?
- What serving strategy will you use for CPU versus GPU models?
- How do batching, quantization, and caching fit into your latency budget?
- What autoscaling strategy accounts for both traffic patterns and cold-start time?
Operational maturity:
- How do you safely deploy a new model version without risking production traffic?
- What observability do you need to debug a latency spike or catch model degradation?
- How does the system behave when a dependency is slow or unavailable?
- What levers control cost as traffic scales?
Assume peak traffic of 50,000 requests per second across roughly 200 tenants, with models ranging from small tree ensembles to 100M-parameter transformers. Walk through the key design choices and explain the trade-offs.
Hints
Hint 1
Start by breaking your latency budget into stages: network, auth, feature fetch, inference, and serialization. Each stage needs a concrete millisecond target.
Hint 2
Consider what happens when one tenant's traffic spike threatens other tenants' SLOs. How do you enforce fairness without adding coordination overhead?
Hint 3
For GPU models, dynamic batching is the key throughput lever, but it adds queueing delay. Show how you tune batch size and wait time to balance throughput and p95 latency.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time ML Prediction Service
1. Requirements and Service-Level Objectives
Before sketching architecture, pin down the numbers. A vague "low latency" requirement leads to over-engineered or under-provisioned systems.
Assumed scale:
- 50,000 QPS peak, 20,000 average
- ~200 tenants; top five generate 60% of volume
- Small tree models (~1–3 ms inference) and transformer models (~15–25 ms)
- Request payload ~2 KB, response ~1 KB
Service-level objectives:
| Metric | Target |
|---|---|
| p50 latency | ≤ 20 ms |
| p95 latency | ≤ 50 ms |
| p99 latency | ≤ 120 ms |
| Availability | 99.95% (22 min/month error budget) |
Latency budget breakdown (p95 = 50 ms):
- TLS termination, load balancing, auth: 5 ms
- Feature retrieval: 10 ms
- Queueing and batching wait: 5 ms
- Model inference: 20 ms
- Response serialization and network: 10 ms
This decomposition is critical. It shows you understand where time is spent and gives you tuning knobs.
2. API Design
POST /v1/predict/{model_name}
Authorization: Bearer <token>
X-Tenant-ID: acme-corp
X-Request-ID: <uuid>
Idempotency-Key: <optional>
{
"entity_id": "user_8472",
"features": {
"transaction_amount": 125.0,
"merchant_country": "FR"
},
"options": {
"timeout_ms": 45,
"explain": false
}
}
→ 200 OK
{
"prediction": {
"score": 0.91,
"class": "high_risk"
},
"model_version": "fraud_v23",
"fallback": false,
"latency_ms": 18,
"request_id": "..."
}
Key elements:
- Authentication: Validate JWT or API key at the edge. Cache tenant metadata (quota, tier, model access) in-process to avoid round-trips.
- Rate limiting: Token bucket per tenant, per model. Enforce limits at the API tier using local counters periodically synced to Redis. This avoids a Redis lookup on every request.
- Multitenancy: Assign tenants to tiers (premium/standard) with quotas and priority queues. Large tenants get dedicated model replicas to prevent noisy neighbors.
- Idempotency: Optional key for client retries. Store result hashes in Redis with short TTL.
Batch endpoint: For offline or bulk use cases, offer POST /v1/predict:batch with up to 256 items per request.
3. Architecture Overview
Client → Regional L7 Load Balancer (Envoy/ALB)
→ API Gateway (Go/Rust, stateless)
├ Auth, validation, rate limit
├ Feature assembly
└ Model routing
→ Feature Store (Redis cluster + in-process LRU)
→ Model Servers
├ CPU pool (ONNX Runtime for trees, small nets)
└ GPU pool (Triton/TorchServe for transformers)
→ Async logging (Kafka) → Data lake → Monitoring
Control plane:
- Model registry
- Config service (feature flags, rollout weights)
- Autoscaler
API gateway tier:
- Stateless pods in Go or Rust. Handle auth, schema validation, quota checks, and route to the correct model server.
- Hold tenant config and feature schemas in memory, refreshed via pub/sub.
- Use least-request load balancing with zone affinity to model servers.
Feature store:
- Online key-value store (Redis, Aerospike, or DynamoDB) with precomputed aggregates.
- Streaming pipeline (Flink, Spark Streaming) computes fresh features from event logs.
- Client SDK issues one multi-get per request with a 10 ms hard timeout. On timeout, use stale cached values or safe defaults and flag the response.
- Shared feature definitions between training and serving prevent skew.
Model serving:
- CPU tier: Tree ensembles, logistic regression, small MLPs. Serve with ONNX Runtime. Latency is 1–3 ms; no batching needed. Autoscale on CPU and RPS.
- GPU tier: Transformers and larger nets. Use TensorRT or Triton Inference Server with dynamic batching.
- Max batch size: 32
- Max wait: 3–5 ms
- Separate priority queues per tenant tier
- Autoscale on queue depth and GPU utilization, not CPU
- Quantization: INT8 post-training quantization or FP16 via TensorRT. Expect 2–4× speedup. Gate deployment on offline accuracy checks (e.g., AUC drop < 0.2%).
- Model co-location: Run multiple small model instances per GPU using MIG or time-slicing to raise utilization.
Caching:
- Result cache: Hash(model_version, features) → prediction. Use only for deterministic, non-personalized requests (e.g., content scoring). TTL: seconds.
- Feature cache: In-process LRU with TTL of 5–30 seconds.
- Model warm-up: Preload weights and run dummy inferences before routing traffic to a new pod.
Autoscaling:
- API tier: scale on CPU and RPS.
- GPU tier: scale on queue depth, batch occupancy, and GPU memory. Maintain 30% headroom for bursts. Use predictive scaling based on diurnal patterns.
- Cold-start time for GPU pods: 2–4 minutes. Keep a warm image pool.
4. Model Versioning and Safe Rollouts
Model registry: Each version is an immutable artifact: weights, preprocessing logic, feature schema hash, offline eval metrics, and training dataset fingerprint. Every response includes the model version served.
Deployment flow:
- Shadow mode: Mirror 5% of live traffic to the new model. Log predictions but don't serve them. Compare output distribution and latency against the current model.
- Canary rollout: 1% → 5% → 25% → 100% of traffic, with automated gates:
- Error rate < baseline + 0.5%
- p95 latency < SLO
- Prediction distribution shift (PSI < 0.1)
- Business proxy metrics (e.g., conversion rate within bounds)
- Rollback: Router config flip to the previous version, which stays warm for 24 hours. Target < 60 seconds to rollback.
A/B testing:
- Assign units deterministically via hash(user_id, experiment_id).
- Log assignment with every prediction for later join with outcomes.
- Run experiments in isolated layers to prevent interference.
- Define sample size and duration upfront. Use sequential testing or fixed-horizon tests with Bonferroni correction.
5. Observability and Monitoring
Metrics (per tenant, model, version):
- QPS, p50/p95/p99 latency by stage
- Error rate, timeout rate, fallback rate
- Batch size, GPU utilization
- Cache hit rate
- Feature freshness lag
Use SLO burn-rate alerts with multi-window (1h, 6h) thresholds to balance sensitivity and noise.
Tracing: OpenTelemetry spans across API → feature store → model server. Tail-based sampling keeps slow requests and errors.
Data quality:
- Validate request schema and feature ranges at ingress.
- Track per-feature null rate, out-of-range rate, and staleness.
Model drift:
- Compute PSI or KL divergence between live input distribution and training distribution hourly.
- Once labels arrive (often delayed), compute online AUC, precision, recall, and calibration. Trigger retraining if performance degrades beyond threshold.
6. Fault Tolerance and Degraded Mode
Fallback behavior:
- If feature store times out: use cached or default values, flag response.
- If primary model is unavailable: serve from a simpler fallback model (e.g., last stable version or a lightweight heuristic model). Return
fallback: true. - If the entire inference tier is overloaded: return HTTP 503 with
Retry-Afterheader.
Circuit breakers: Wrap feature store and model calls. Open the circuit after sustained failures, fail fast, and periodically retry.
Regional failover: Deploy in multiple regions. Route via latency-based DNS. Replicate model artifacts to regional object stores.
Disaster recovery: Model registry and config are versioned and backed up. Redeploy from a clean snapshot takes < 15 minutes.
7. Cost and Security
Cost controls:
- Right-size GPU SKUs: Use T4 or A10 for inference, not A100s.
- Spot instances for batch workloads and some online replicas with fallback.
- Model distillation: Train smaller student models to reduce GPU hours.
- Autoscaling: Aggressive scale-down during off-peak hours.
- Chargeback: Meter tenant usage (requests, compute time) for internal cost allocation.
Security and compliance:
- PII: Hash or tokenize entity_ids. Encrypt features at rest and in transit. Audit access logs.
- Model IP: Restrict model artifact access via IAM. Serve models inside private VPCs.
- Regionalization: Deploy models in EU/US regions per GDPR. Route EU traffic to EU endpoints.
- Auditability: Immutable prediction logs with request ID, model version, tenant, and timestamp.
Common Pitfalls
- No latency budget: Not breaking down the 50 ms into stages means you can't debug or optimize.
- Batching without bounds: Unbounded dynamic batching can blow p99 latency.
- Ignoring multitenancy: One large tenant can starve others. Priority queues and quotas are essential.
- Cold model rollouts: Deploying a new version without warming the model leads to p99 spikes.
- Missing drift detection: Models degrade silently. Online monitoring is not optional.
Summary
A production ML inference service requires disciplined latency budgeting, separation of CPU and GPU workloads, multi-stage rollouts with automated gates, rich telemetry for every stage, and graceful degradation under load. The key trade-offs are batch size versus latency, cost versus headroom, and complexity versus debuggability. Strong answers show concrete numbers, anticipate failure modes, and explain how each design choice ties back to the SLOs.