Design a Real-Time and Batch AI Model Serving Platform
Machine LearningModel answerLast updated
Design a cloud inference platform that serves ML models at scale, covering hardware selection, autoscaling, multi-tenancy, cost controls, and safe deployment strategies.
Scenario
You are a senior ML infrastructure engineer at a company that offers model inference as a service. Engineering leadership has asked you to design the platform from scratch. It must handle two distinct workload types: low-latency real-time inference (chat completions, embeddings, vision) and high-throughput batch scoring (offline ranking, bulk generation).
What to Design
Walk through the full system. You are expected to make reasonable assumptions and state them clearly. Cover:
- Model packaging and versioning — how models are stored, tracked, and promoted to production
- Hardware selection — when to use CPUs vs. different GPU tiers, and why
- Autoscaling — what signals to scale on, and how to handle cold starts for large models
- Request routing — how traffic is dispatched to replicas, including weighted splits for rollouts
- Multi-tenant isolation — security boundaries and performance fairness across tenants
- SLOs and observability — what latency/throughput targets you would set and how you would measure them
- Cost controls — right-sizing, spot instances, utilization targets
- Failure handling and safe rollouts — canary deployments, shadow testing, fallback behavior
- Kubernetes integration — how the serving infrastructure maps onto Kubernetes primitives
- Comparison to existing offerings — where your design aligns with or diverges from platforms like SageMaker, Vertex AI, or Azure ML
What Is Expected
This is an open-ended design question. A strong answer:
- Starts with scoped assumptions and a back-of-envelope estimate to ground the design
- Identifies the two or three hardest problems early and addresses them with depth
- Makes explicit trade-offs rather than listing features
- Includes concrete numbers (latency targets, GPU memory, token throughput) where useful
- Discusses failure modes and how the system degrades gracefully
Hints
Hint 1
Start by nailing down your assumptions: number of tenants, RPS, model sizes, and SLO targets. These drive every hardware and scaling decision that follows — a design without them is just a list of buzzwords.
Hint 2
GPU utilization vs. tail latency is the central tension in LLM serving. Think about what signal you actually scale on (queue depth, KV-cache fill, p95 TTFT) and why CPU% is the wrong metric here.
Hint 3
Cold starts for large models are a genuine hard problem — a 70B model can take several minutes to load. Think through the full chain: node provisioning, image pull, weight loading, and which of those you can parallelize or pre-warm.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a broad prompt, so the right move is to signal breadth quickly, then go deep on the two or three genuinely hard problems: GPU utilization vs. tail latency, cold starts for large models, and noisy-neighbor isolation in a shared multi-tenant fleet. Covering every bullet at equal depth reads as a checklist recitation; examiners respond better to depth with honest trade-offs.
1. Scope and Assumptions
State your baseline before drawing anything:
- Tenants and models: ~1,000 tenants, ~500 active model versions in production at any time.
- Real-time workloads: LLM chat/completions, embeddings, image classifiers, classic tabular ML.
- Batch workloads: Offline scoring, bulk content generation, nightly re-ranking jobs.
- Scale: 20k real-time RPS at peak; ~10B tokens/day across batch jobs.
- Latency SLOs:
- Classic ML and embeddings: p99 < 50 ms end-to-end.
- LLM real-time: time-to-first-token (TTFT) p95 < 500 ms; inter-token latency p95 < 50 ms.
- Batch: completion within 24 hours at roughly half the real-time per-token cost.
- Availability: 99.9% for real-time, multi-zone, optional multi-region failover.
Back-of-envelope sanity check. A 70B model in FP8 on two H100s with continuous batching sustains roughly 2–3k output tokens/s. At 10M output tokens/hour for one heavily used model, that is ~2.8k tokens/s — so one or two replicas at full utilization, plus headroom for bursts. GPU-hours dominate the bill, so utilization is the primary efficiency metric.
2. API Surface
Real-time:
POST /v1/models/{model}/inferfor generic JSON or tensor payloads.- OpenAI-compatible
POST /v1/chat/completionswith SSE streaming, because tenants often port existing integrations. - Headers carry tenant key, optional model version pin, and request priority.
Batch:
POST /v1/batchesaccepts{input_uri, model, output_uri, completion_window}, returns abatch_id.GET /v1/batches/{id}polls status with progress.
Control plane: endpoints for registering model artifacts and creating/updating deployments with traffic weights and rollout policy.
3. High-Level Architecture
Five layers:
- Edge / API gateway — auth, per-tenant rate limiting (token bucket on RPS and tokens per minute), and region routing.
- Inference router — a model-aware L7 router that tracks each replica's queue depth, KV-cache fill, and loaded adapters. Routes by least outstanding tokens, with prefix-affinity to reuse KV-cache across requests sharing a system prompt.
- Serving pods on Kubernetes — vLLM or TensorRT-LLM for LLMs, Triton for vision and embeddings, lightweight CPU servers for tree models. KServe or a custom operator manages
InferenceServiceCRDs. - Batch system — jobs sharded into Kafka or SQS queues, workers pulling shards at large batch sizes on spot GPUs or idle real-time capacity. Each shard checkpoints so partial failures are retried from the last checkpoint, not from scratch.
- Control plane — model registry, deployment controller, autoscaler, billing, and an observability stack (OpenTelemetry traces, Prometheus + DCGM GPU metrics).
4. Hardware Selection
| Workload | Hardware | Rationale |
|---|---|---|
| Trees, lightweight preprocessing | CPU | Transfer overhead to GPU exceeds compute savings |
| Embeddings, small CNNs, <7B LLMs | L4 / A10, or MIG slice of H100 | Fits in memory; lowest cost per token at this size |
| 13–70B LLMs | H100 / A100 80 GB, tensor parallel | Memory bandwidth and HBM capacity are the bottleneck at decode |
| Batch LLM | Same GPUs, spot pricing, large batch sizes | Throughput matters; latency SLO is relaxed |
Selection should be empirical: benchmark each model across hardware profiles and pick the cheapest that meets the p95 SLO. Quantization (FP8, AWQ, GPTQ) often lets a model drop one hardware tier, meaningfully cutting cost.
5. Deep Dive: Autoscaling and Cold Starts
What to scale on. CPU utilization is wrong for GPU serving. Better signals: in-flight token count or queue depth per replica, KV-cache utilization percentage, and observed TTFT p95 relative to SLO. KEDA driven by a Prometheus query works well for the first two; a custom controller handles the SLO feedback loop.
The cold-start problem is severe for large models. A new pod for a 70B model must: (a) schedule onto a GPU node — possibly provisioning one from the cloud, 2–5 minutes; (b) pull the container image; (c) stream ~140 GB of weights from object storage. Mitigations, in order of impact:
- Warm pools of pre-provisioned GPU nodes that hold a GPU reservation but no workload, cutting provisioning from minutes to seconds.
- Node-local NVMe weight caches: the first load warms the cache; subsequent loads on the same node are fast.
- Fast streaming weight loaders (safetensors format with direct GPU transfer) rather than full-file-then-load.
min_replicas ≥ 1for paid tiers — never scale to zero unless cost pressure demands it.- Predictive scaling from diurnal traffic patterns to pre-warm before demand arrives.
- Multi-LoRA serving: one base model loaded permanently with hundreds of LoRA adapters hot-swapped per request. This collapses hundreds of fine-tuned variants into one always-warm replica.
Overload control. Before latency collapses, the router should shed or queue low-priority traffic and return 429 with a Retry-After header. This is better than letting queues grow until p99 becomes unusable for everyone.
6. Deep Dive: Multi-Tenant Isolation
Security: Per-tenant namespaces and network policies. Weights and prompts encrypted at rest and in transit. No cross-tenant KV-cache prefix sharing — this can leak timing information. Enterprise tiers get dedicated node pools with hard hardware boundaries.
Performance fairness: Per-tenant token quotas enforced at the gateway, plus weighted fair queuing inside the router so one tenant sending 32k-token prompts cannot starve others on the same replicas. When a tenant exhausts their quota, they get a 429 immediately rather than degrading the shared pool.
A common mistake is handling isolation only at the security layer and ignoring the performance fairness layer. Both are required; noisy-neighbor problems in a shared GPU pool are one of the hardest operational issues to debug after the fact.
7. Safe Rollouts
- Canary: deploy a new model version at 5% traffic weight, measure TTFT, error rate, and output quality signals against the baseline, then promote or roll back automatically based on thresholds.
- Shadow mode: mirror real traffic to the new version with no user-facing impact. Useful for catching regressions in output distribution before any live traffic is shifted.
- Blue/green: maintain the old version at 100% until the new one passes health checks, then flip atomically. Higher cost but simplest rollback.
Model version is immutable in the registry (content-addressed by digest). Promotion across stages (staging → canary → production) triggers the deployment controller, which reconciles InferenceService objects. A GitOps flow provides a full audit trail.
8. Comparison to Managed Offerings
SageMaker, Vertex AI, and Azure ML all offer managed inference endpoints with autoscaling and multi-model serving. Where a custom platform wins:
- Routing intelligence: managed offerings route at the load balancer level, not at the model level. KV-cache-aware routing and LoRA adapter affinity require a custom router.
- Cost optimization: multi-LoRA serving and bin-packing across model sizes are not exposed by managed services.
- SLO feedback loops: scaling on TTFT p95 rather than CPU requires hooks that managed platforms do not provide.
The trade-off is operational burden. For most teams, managed services are the right starting point; a custom platform makes sense once model count and traffic volume make the cost and routing gaps material.
Common Mistakes
- Scaling on CPU or GPU compute percentage rather than queue depth or latency signals.
- Ignoring cold starts and designing purely for steady-state throughput.
- Treating isolation as a security-only concern and shipping without per-tenant fair queuing.
- Using mutable model versions, which makes rollback ambiguous and auditing impossible.
- Not specifying which SLO — TTFT vs. total response time vs. throughput — you are optimizing for. These lead to different architectural decisions.