Design a Multi-Tenant GPU Inference Engine
System DesignModel answerLast updated
Architect a scalable, low-latency API platform for serving multi-tenant deep learning workloads (including LLMs) across heterogeneous GPUs under strict latency SLOs.
Design a scalable, multi-tenant GPU inference engine capable of serving diverse deep learning models—ranging from small vision/text classifiers to massive autoregressive Large Language Models (LLMs)—to internal product services and external API consumers.
Your system must handle low-latency online inference with explicit Service Level Objectives (SLOs), scale gracefully from small pilot traffic to tens of thousands of requests per second across heterogeneous GPU hardware (e.g., NVIDIA H100, A100, L4), and manage multiple concurrent model versions and LoRA adapters.
Walk through the end-to-end architecture and address the following structural topics:
- API Design & Interface Protocol: Define the synchronous and asynchronous API surfaces. Specify request/response schemas, tenant authentication, versioning semantics (API path vs. model alias/pinning), protocol choices (gRPC vs. HTTP/2 + SSE), and job polling/webhook mechanisms.
- System Architecture & Request Lifecycle: Trace request flows through the API Gateway, CPU preprocessing tier, routing layer, continuous batching engine, GPU worker fleet, model registry, and async job queue.
- Decoupled Autoscaling: Explain how and why CPU frontend scaling signals differ from GPU pool scaling signals.
- Diagnostic Scenario: Outline a step-by-step diagnostic workflow for a situation where CPU usage is low but GPU nodes are fully saturated under rising tail latencies.
- SLO-Aware Scheduling & Batching: Compare micro-batching for static models against continuous batching (prefill vs. decode disaggregation) for LLMs. Explain fair-queueing mechanisms across tenants and backpressure handling.
- GPU Memory & KV-Cache Management: Describe memory allocation strategies (PagedAttention, prefix caching, quantization), tensor/pipeline parallelism, and per-tenant memory isolation.
- Multi-Model Hosting & Adapter Management: Explain colocation strategies (Multi-Instance GPU vs. MPS vs. time-slicing) and shared base-model execution for multi-tenant LoRA adapters.
- Deployment, Rollout & Fault Tolerance: Detail model versioning, shadow traffic, canary rollouts, artifact caching hierarchies (S3 → NVMe → Host RAM → VRAM), and multi-region failover routing.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Multi-Tenant GPU Inference Engine Architecture
1. Requirements & Core Metrics
Latency & SLO Targets
- Static Models (Classifiers, Embeddings, Vision): Synchronous p99 latency $< 50\text{ ms}$.
- Autoregressive LLMs:
- Time-to-First-Token (TTFT) p99 $< 400\text{ ms}$.
- Inter-Token Latency (ITL) p99 $< 30\text{ ms}$ (approx. 33 tokens/sec streaming throughput).
- Async Batch Jobs: Completion SLA within minutes to hours depending on job tier.
- Availability: 99.99% for sync predictions; 99.9% for async execution pools.
Scale Assumptions
- Peak Traffic: 20,000 Requests Per Second (RPS) distributed globally.
- Fleet Heterogeneity: Mix of NVIDIA H100 (80GB HBM3), A100 (80GB PCIe/SXM), and L4 (24GB).
- Memory Constraint Example: A 70B FP16 parameter model occupies $\sim 140\text{ GB}$ of VRAM across a tensor-parallel (TP) pair of GPUs.
- A 4,000-token context sequence with 80 layers and 8 Key-Value (KV) heads at FP16 consumes: $$\text{KV Size} = 2 \times 80 \text{ layers} \times 8 \text{ heads} \times 128 \text{ dim} \times 2 \text{ bytes} \times 4000 \text{ tokens} \approx 1.31 \text{ GB per sequence}$$ This confirms that VRAM capacity for KV blocks, rather than peak compute (TFLOPS), primarily caps LLM concurrency.
2. API Schema and Request Lifecycle
+--------------------+
| API Client (gRPC) |
+---------+----------+
|
v
+----------------------------+
| API Gateway (Auth/SLO) |
+-------------+--------------+
|
+------------+------------+
| |
v v
+-------------------+ +--------------------+
| Sync Request Flow | | Async Job Router |
| (HTTP/2 SSE) | | (SQS / Redis) |
+---------+---------+ +---------+----------+
| |
v v
+-------------------+ +--------------------+
| CPU Tokenizer Node| | Async Batch Worker |
+---------+---------+ +--------------------+
|
v
+-------------------+
| GPU Worker Fleet |
| (PagedAttention) |
+-------------------+
Endpoints & Interfaces
- Synchronous Predict/Generate:
POST /v1/models/{model_alias}:predictor:stream- Protocol: gRPC internally; HTTP/2 with Server-Sent Events (SSE) externally for token streaming.
- Headers:
Authorization: Bearer <token>,X-Tenant-ID: <id>,Idempotency-Key: <uuid>. - Path vs. Versioning: The path
/v1reflects API protocol stability. Model versions are declared via aliases (e.g.,model="llama-3-70b:stable") or exact immutable pins (e.g.,model="llama-3-70b:v2.1.0-sha-a4f19").
// Sync Request Body
{
"model": "text-summarizer:stable",
"lora_adapter": "tenant-402-finance-v1",
"inputs": {
"prompt": "Summarize the following quarterly earnings transcript..."
},
"parameters": {
"max_tokens": 512,
"temperature": 0.2,
"top_p": 0.9
},
"priority": "interactive",
"timeout_ms": 3000
}
// Sync SSE Stream Payload Chunk
{
"id": "gen-89a3f-block-12",
"object": "text_completion.chunk",
"resolved_model_version": "llama-3-70b:v2.1.0-sha-a4f19",
"choices": [
{
"delta": {"text": " operating"},
"finish_reason": null
}
],
"usage": {
"prompt_tokens": 842,
"completion_tokens": 14,
"gpu_time_ms": 42.1
}
}
- Async Execution API:
POST /v1/jobs- Used when processing large documents, offline batch evaluations, or requests with strict cost budgets that run on preemptible spot GPU pools.
- Returns
202 Acceptedwith ajob_id. Clients track execution via webhooks (/v1/webhooks/jobs) or polling (GET /v1/jobs/{job_id}).
3. End-to-End System Architecture
[ Client ]
│
▼
[ API Gateway ] ──── Auth, Rate-Limiting, Tenant Token Bucket
│
▼
[ CPU Frontend Tier ] ──── Preprocessing, Detokenization, Schema Validation
│
▼
[ Dynamic Router ] ──── Prefix-Aware Cache Affinity Routing
│
▼
[ GPU Inference Node ]
├── Engine Scheduler (Continuous Batching / Chunked Prefill)
├── Memory Manager (PagedAttention KV Cache Block Allocation)
└── Execution Hardware (Tensor Parallel CUDA Streams)
- API Gateway: Enforces mutual TLS, extracts tenant identities, evaluates request rate limits, and validates request integrity.
- CPU Frontend Tier: Decouples heavy CPU-bound tasks from GPUs. Performs string tokenization, image resizing/normalization, and safety guardrail filter checks.
- Dynamic Router & Load Balancer: Maintains an in-memory view of cluster state. Uses hash-consistent prefix routing to send incoming prompts to nodes already holding relevant system prompt KV blocks in cache.
- GPU Worker Node:
- Engine Scheduler: Manages active inference sequences using dynamic, continuous batching.
- PagedAttention Engine: Allocates physical VRAM memory blocks for KV sequences dynamically, bypassing virtual memory fragmentation.
- Execution Engine: Executes forward-pass kernels (e.g., FlashAttention-3) tuned for specific hardware microarchitectures.
- Model Registry & Storage Tier: Global S3 artifact store backed by local NVMe drives on worker nodes acting as local read-through caches.
4. Decoupled CPU vs. GPU Autoscaling
Scaling rules for CPU frontend tiers and GPU execution pools are completely separated due to differences in cost, initialization time, and saturation metrics.
CPU Scaling Signals GPU Scaling Signals
+--------------------------------+ +--------------------------------+
| • CPU Utilization (> 70%) | | • KV Cache Block Occupancy |
| • Request Queue Depth | | • P99 Time-to-First-Token |
| • Tokenization Latency | | • Engine Queue Dwell Time |
+--------------------------------+ +--------------------------------+
│ │
▼ ▼
Fast Scale-Up (< 5 sec) Slow Scale-Up (2-5 min)
(Stateless K8s Pods) (Weight Loading & Warmup)
| Dimension | CPU Frontend Tier | GPU Worker Fleet |
|---|---|---|
| Primary Metric | CPU Utilization (70%), HTTP Request Rate | Engine Queue Dwell Time, KV Cache Block Occupancy |
| Startup Time | $1 - 3 \text{ seconds}$ | $2 - 5 \text{ minutes}$ (fetching 100GB+ weights + warming CUDA graphs) |
| Capacity Reserve | Minimal (10% over-provisioning) | Dedicated Warm Pools (pre-loaded base models ready for traffic spikes) |
| Scale-Down Policy | Rapid (1-minute cooldown) | Conservative (15-30 minute cooldown to avoid weight reload thrashing) |
5. Diagnostic Scenario: Saturated GPUs with Low CPU Usage
Symptom
CPU usage across frontends stays low ($< 20%$), but end-to-end request latencies skyrocket, and GPU SM (Streaming Multiprocessor) occupancy reports high saturation ($> 95%$).
+---------------------------------+
| High Latency & High GPU SM% Observed |
+----------------+----------------+
|
v
+---------------------------------+
| Is Engine Queue Time Growing? |
+----------------+----------------+
|
+-------------------+-------------------+
| YES | NO
v v
+--------------------------+ +--------------------------+
| KV Cache Block Starvation| | Large Prompt Prefill Stall|
| or High Batch Overheads | | (Compute-Bound Bottleneck)|
+-------------+------------+ +------------+-------------+
| |
v v
+--------------------------+ +--------------------------+
| Enforce Tenant Quotas & | | Enable Chunked Prefill |
| Defragment KV Blocks | | Disaggregate Prefill/Decode|
+--------------------------+ +--------------------------+
Troubleshooting Step-by-Step
- Isolate Latency Metrics: Check the latency breakdown:
Time_in_Frontend_Preprocessvs.Time_in_Engine_Queuevs.Time_in_GPU_Execution. IfTime_in_Engine_Queueis high, requests are queuing up at the GPU batching layer. - Inspect Memory vs. Compute Metrics:
- KV Cache Block Utilization: If KV block utilization is near $100%$, the engine cannot schedule new request decodes. It is forced to pause sequences or swap them to CPU host memory, causing memory stalls.
- Prefill vs. Decode Distribution: High SM occupancy with low token throughput indicates large input prompts causing prefill compute stalls. Long prefill passes block pending decode steps for existing requests.
- Check Context Length Distributions: Determine whether a tenant is sending abnormally long prompt sequences (e.g., 32k context inputs) that saturate tensor core FLOPs and drain available KV cache blocks simultaneously.
Remediation Plan (Ordered by Speed to Resolution)
- Dynamic Load Shedding & Quotas (Immediate): Apply rate-limiting to high-context requests. Reject low-priority background requests at the API Gateway with HTTP
429 Too Many Requestsand aRetry-Afterheader. - Enable Chunked Prefill & Pipeline Splitting (Configuration): Break long prompt prefills into smaller token chunks (e.g., 512 tokens) and interleave them with decode steps to bring down tail inter-token latency (ITL).
- Disaggregate Prefill and Decode Execution (Infrastructure): Separate the GPU fleet into dedicated Prefill Nodes (compute-heavy, high TP) and Decode Nodes (memory bandwidth-heavy, large KV capacity).
- Promote Replicas from Warm Pools (Scale-out): Re-allocate underutilized warm GPU capacity to the overloaded model version.
6. SLO-Aware Scheduling & Batch Management
Static Models vs. LLM Autoregressive Batching
Static Model Micro-Batching (Fixed Bounds)
[Req 1][Req 2][Req 3] ──> | GPU Forward Pass | ──> Output Batch
Continuous Batching (Dynamic Iteration Scheduling)
Step 1: [Seq 1 (Decode)][Seq 2 (Decode)][Seq 3 (Prefill)] ──> GPU Step
Step 2: [Seq 1 (Decode)][Seq 2 (Decode)][Seq 3 (Decode )] ──> GPU Step (Seq 1 Finishes)
Step 3: [Seq 4 (Prefill)][Seq 2 (Decode)][Seq 3 (Decode )] ──> GPU Step
- Static Micro-Batching: Used for vision and classifier tasks. Requests gather in a queue for up to a max timeout (e.g., $5\text{ ms}$) or until a maximum batch size (e.g., 32) is met, then run together in one execution pass.
- Continuous Batching (LLMs): Runs batching at the individual token generation step level rather than the request level. New requests enter the running batch instantly during their prefill phase while finished sequences leave the batch immediately, maximizing hardware utilization.
Disaggregated Prefill and Decode (P/D Disaggregation)
- Prefill Cluster: Compute-bound. Runs prompt token ingestion using large Tensor Parallelism (TP) setups to keep Time-To-First-Token (TTFT) low.
- Decode Cluster: Memory-bandwidth-bound. Receives prefill KV cache states across high-speed network interfaces (e.g., InfiniBand/RoCE) and streams step-by-step token generation.
Incoming Request ──> [ Prefill Pool (TP=8) ]
│ (Transfer KV Cache via RDMA)
▼
[ Decode Pool (TP=2) ] ──> Streaming Tokens to Client
7. GPU Memory & KV-Cache Architecture
Virtual Tokens: [ Page 0 (Tok 0-15) ] [ Page 1 (Tok 16-31) ]
│ │
▼ ▼
Physical VRAM: [ Block 88 (GPU 0) ] [ Block 12 (GPU 0) ]
PagedAttention & Cache Management
Traditional sequential memory allocation leads to memory fragmentation because output context lengths are non-deterministic.
- PagedAttention Solution: Allocates VRAM for key-value projections in fixed-size memory blocks (e.g., 16 tokens). A central memory page table maps virtual token offsets to non-contiguous physical blocks in GPU VRAM.
- Prefix Caching: Common system prompt blocks (such as shared instruction prompts or system contexts) are assigned shared read-only physical memory pages. Multiple requests reference these shared pages via copy-on-write pointers, significantly reducing duplicate KV cache storage.
Multi-Tenant Model Isolation & Quantization
- Weight Quantization: Base model weights are loaded in FP8 or INT4 formats, reducing VRAM footprint by 50–75% and freeing up capacity for larger active KV cache pools.
- Tenant Isolation: Enforce hard memory quotas per tenant for KV cache blocks. Prevent shared prefix cache lookups across tenant boundaries to protect system boundaries and avoid side-channel leaks.
8. Multi-Model Hosting & Multi-Tenant Adapters
+-----------------------------------+
| Shared Base Model Weights (FP8) |
+-----------------+-----------------+
|
+-------------------------+-------------------------+
| |
v v
+-------------------+ +-------------------+
| LoRA Adapter A | | LoRA Adapter B |
| (Tenant 1, VRAM) | | (Tenant 2, VRAM) |
+-------------------+ +-------------------+
Hosting Architecture Options
- Base Model + Multi-Tenant LoRA (Recommended for Fine-tunes):
- Keep a single set of base model parameters (e.g., Llama-3-70B) in VRAM.
- Dynamically load smaller rank adaptation matrices ($\text{Rank } r \in [8, 64]$) into VRAM on demand. Batched forward passes execute base matrix math combined with tenant-specific LoRA kernel operations in a single kernel run using S-LoRA / Punica techniques.
- NVIDIA Multi-Instance GPU (MIG):
- Hardware-level partition of an A100/H100 GPU into isolated instances (e.g., splitting one 80GB GPU into seven independent 10GB slices). Provides strict compute and memory isolation for small static models.
- Multi-Process Service (MPS):
- Software-level CUDA context multiplexing. Allows multiple static model processes to share a single GPU device safely with low context switching overhead.
9. Deployment, Routing, & Cold-Start Optimization
Tiered Artifact Loading Hierarchy
[ Object Store (S3) ] ──── Fetch Latency: ~10-30s (Over 10Gbps Network)
│
▼
[ Node Local NVMe Cache ] ──── Fetch Latency: ~2-5s (PCIe Gen5 Bus Transfer)
│
▼
[ Host Pinned RAM ] ──── Fetch Latency: ~500ms (Direct DMA Transfer)
│
▼
[ GPU VRAM ] ──── Direct Hardware Execution Memory
Rollout Strategies & Route Management
- Shadow Evaluation: The gateway duplicates live input streams, sending one stream to the target production model and an asynchronous copy to a candidate model version. Responses from the candidate are dropped after logging token generation accuracy and execution performance.
- Canary Deployment: Shift traffic progressively based on defined weights: $1% \to 5% \to 25% \to 100%$. Automatically trigger rollbacks if latency metrics or error rates break established SLO thresholds.
# Canary Router Weight Resolution Strategy
def resolve_model_target(tenant_id: str, model_alias: str) -> str:
route_config = registry.get_routing_table(model_alias)
if not route_config.is_canary_active:
return route_config.stable_version
# Deterministic hash assignment ensures consistent user routing
user_hash = crc32_hash(f"{tenant_id}:{model_alias}") % 100
if user_hash < route_config.canary_percentage:
return route_config.canary_version
return route_config.stable_version
10. Key Architecture Trade-Offs
| Option A | Option B | Selected Trade-Off Rationale |
|---|---|---|
| Synchronous HTTP/2 Streaming | Asynchronous Job Queues | Use HTTP/2 SSE for real-time interactive user interfaces requiring low TTFT. Use Async Queues for background document processing to optimize hardware batch occupancy and reduce costs. |
| Disaggregated Prefill/Decode | Colocated Execution | Disaggregation requires dedicated network interconnects (NVLink/InfiniBand) for high-speed KV transfers, but removes prefill-induced latency stalls during generation decode steps. |
| Aggressive Prefetch Caching | Memory Isolation | Global prefix caching saves significant VRAM across identical requests, but shared cache blocks must be strictly isolated to public system prompts to prevent cross-tenant data leaks. |
| MIG Hardware Partitioning | Dynamic MPS Time-Slicing | MIG offers absolute performance isolation but limits flexible memory utilization. MPS improves overall GPU utilization for small models at the cost of potential compute resource contention. |