Build a GPU-Based Model Serving System
System DesignModel answerLast updated
Design a service that exposes a trained ML model over an API, routes requests to GPU workers, and maximizes hardware utilization.
You're building a service that serves predictions from a trained machine learning model running on GPU hardware. Clients will send requests over the network and receive predictions back. Your job is to design both the client-facing interface and the internal architecture that delivers those predictions efficiently.
The problem has two parts:
Part A: Architecture and API
Design the complete serving stack. This includes:
- The client-facing API: what do requests and responses look like, how do errors surface, and what guarantees do you provide?
- The data flow: how does a request travel from entry point to GPU and back?
- Resource management: how do you decide which requests to accept, how do you distribute work across available GPUs, and what happens when load exceeds capacity?
- Operational concerns: handling GPU failures, deploying updated models, and monitoring system health
Part B: GPU Optimization
Once the basic system works, explain how to increase the number of requests each GPU can handle while maintaining acceptable response times. What are the bottlenecks in GPU execution for this workload? What techniques can improve throughput, and what trade-offs does each involve?
Assumptions You Should Clarify
The interviewer intentionally leaves details unspecified. Before diving in, establish:
- Model characteristics: Does it produce a single output (image classification, embeddings) or generate sequences iteratively (language models producing tokens one at a time)?
- Scale: How big is the model? Does it fit in one GPU's memory or require multi-GPU sharding?
- Performance requirements: Is the priority time-to-first-token, end-to-end latency for complete outputs, or maximum throughput for batch workloads?
- Traffic patterns: Expected request volume, burstiness, whether responses should stream back incrementally
- Client needs: Authentication schemes, per-user quotas, priority tiers
A reasonable working assumption for concreteness: a large language model that generates text token-by-token, serving real-time user requests where streaming responses matter.
Hints
Hint 1
For the API surface, think through what happens when capacity is full, a request times out, or generation hits a configured limit.
Hint 2
GPU compute vs memory bandwidth: different phases of inference are bottlenecked by different resources.
Hint 3
Batching helps, but naive batching creates head-of-line blocking when requests in the same batch have different output lengths.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Part A: System Architecture
API Design
The client-facing interface exposes a prediction endpoint. For a generative model:
Request format:
POST /v1/generate
{
"prompt": "user input text",
"max_tokens": 100,
"temperature": 0.7,
"stream": true
}
Response: If stream is true, return server-sent events delivering tokens incrementally. If false, buffer the complete output and return it in one response. Include a request ID for tracking and debugging.
Error handling: Return explicit HTTP codes—429 for rate limit exceeded, 503 when all capacity is busy, 400 for invalid parameters like negative max_tokens. Streaming responses that fail mid-generation send an error event before closing the connection.
Authentication and quotas: Use API keys in headers. Track per-key request counts and token usage. Enforce both rate limits (requests per minute) and resource quotas (total tokens generated per day).
Request Path
-
Gateway/Load Balancer: Terminates TLS, validates API keys, enforces per-client rate limits. Rejects requests immediately if the client has exceeded their quota—no sense queueing work you'll reject later.
-
Request Queue: Accepted requests enter a distributed queue (Redis, Kafka, or an in-memory queue per availability zone). The queue is bounded—once it reaches capacity, new requests receive a 503 immediately rather than waiting indefinitely.
-
Scheduler: Pulls requests from the queue and assigns them to GPU worker processes. The scheduler tracks which workers are idle and which are busy. For multi-GPU setups, the scheduler knows which workers host which model replicas.
-
GPU Workers: Each worker runs the model inference. For streaming, it writes generated tokens to a response channel as they're produced. Workers periodically heartbeat to the scheduler; missed heartbeats trigger failover.
-
Response Delivery: For streaming, the gateway holds an open HTTP connection and forwards events from the worker. For buffered responses, the worker sends the complete output back through the queue or directly via RPC.
Overload Behavior
Admission control: Set a maximum queue depth based on acceptable wait time. If the queue is full, immediately reject new requests with 503 and a Retry-After header.
Fairness: Use per-client queues with round-robin scheduling, or track recent token usage and deprioritize heavy users. This prevents one client from monopolizing GPU capacity.
Backpressure: The gateway tracks queue depth and latency. When queue wait time exceeds a threshold, start shedding load early—return 503s before requests even enter the queue.
Failure Handling
Worker failure: If a GPU worker crashes mid-request, the scheduler detects the missed heartbeat and re-queues the request (up to some retry limit). The client sees a timeout or an error event in the stream.
Model updates: Deploy new model versions by starting new workers with the updated weights, then gradually shifting traffic from old to new workers (blue-green deployment). Keep old workers alive until all in-flight requests complete.
GPU hardware failure: Monitor GPU health metrics (temperature, memory errors). If a GPU shows signs of failure, drain its requests and take it out of rotation.
Metrics
- Latency: Time from request arrival to first token (p50, p95, p99), and time to complete response.
- Throughput: Requests per second, tokens generated per second per GPU.
- Queue depth and wait time: Signal capacity issues before they cause user-visible failures.
- Error rates: Broken down by type (rate limit, timeout, worker failure).
- GPU utilization: Compute and memory usage per worker—reveals whether hardware is bottlenecked or underused.
Part B: GPU Optimization
Understanding the Bottleneck
GPU inference alternates between two phases:
-
Prompt processing (prefill): The model consumes the entire input prompt in one forward pass. This is compute-bound—the GPU performs matrix multiplications on the input tokens in parallel. Memory bandwidth is not the limiting factor here because data reuse is high.
-
Token generation (decode): The model generates one token at a time, using the previous output as the next input. Each step fetches model weights from GPU memory and produces a single token. This is memory-bandwidth-bound—the GPU must load billions of parameters from HBM for each token, but the arithmetic intensity is low.
The decode phase dominates total time for longer outputs. Improving decode throughput is key.
Batching
Static batching: Process multiple requests in the same forward pass. All requests in the batch share the model weights, so memory bandwidth per request drops. Compute increases linearly with batch size, but memory access does not—throughput improves.
Problem: Requests finish at different times. A batch of 8 requests must wait for the longest one to complete, wasting GPU cycles on padding or idle time.
Continuous batching (iteration-level batching): Instead of batching at the request level, batch at the token-generation step. As soon as one request finishes, swap it out and add a new request to the batch. This keeps the batch full and eliminates idle time. Libraries like vLLM and TensorRT-LLM implement this.
Memory Efficiency
Model weights are shared across requests and loaded once. KV cache (key-value tensors from the attention mechanism) is per-request state that grows with output length. Long outputs or large batches exhaust GPU memory.
PagedAttention: Borrow ideas from virtual memory—store KV cache in non-contiguous blocks, allowing dynamic allocation and eviction. When memory is tight, evict cache for low-priority requests and recompute it if needed later. This lets you pack more requests into the same memory budget.
Quantization: Store model weights in INT8 or INT4 instead of FP16. Reduces memory footprint and increases memory bandwidth. The cost is a small accuracy drop (typically negligible for large models with proper calibration). Quantization also reduces the number of bytes fetched per token, directly speeding up the memory-bound decode phase.
Other Optimizations
Flash Attention: Optimizes the attention computation to reduce memory reads/writes by fusing operations and recomputing intermediate values on the fly. Speeds up both prefill and decode.
Speculative decoding: Use a smaller, faster "draft" model to generate several tokens speculatively, then verify them with the full model in one pass. If the drafts are correct, you've saved multiple decode steps. Gains depend on how often the draft model guesses correctly.
Multi-GPU strategies: For models too large for one GPU, shard them across multiple GPUs (tensor parallelism or pipeline parallelism). Tensor parallelism splits each layer across GPUs; pipeline parallelism splits layers across GPUs. Tensor parallelism has lower latency but requires fast interconnects. Pipeline parallelism is easier to scale but adds microbatching complexity.
Measuring Impact
Track tokens per second per GPU as the primary throughput metric. Monitor latency distributions—p95 and p99 matter more than averages. Watch GPU memory utilization—you want it high but not so high that out-of-memory errors occur. Measure batch size over time—continuous batching should keep it near maximum.
Trade-offs Summary
| Technique | Throughput Gain | Latency Impact | Accuracy Impact | Complexity |
|---|---|---|---|---|
| Static batching | Moderate | Negative (head-of-line blocking) | None | Low |
| Continuous batching | High | Neutral to positive | None | Medium |
| Quantization | High (memory-bound workloads) | Positive (fewer bytes) | Small drop | Medium |
| PagedAttention | Moderate (better packing) | Neutral | None | High |
| Speculative decoding | Moderate | Positive (when drafts succeed) | None | High |
A strong answer walks through the reasoning for each optimization, ties it back to whether the workload is compute- or memory-bound, and acknowledges the engineering effort and accuracy trade-offs.