Design a Low-Latency LLM Inference API Service
System DesignModel answerLast updated
Design a production-ready HTTP service that serves a single large language model to thousands of concurrent users with low latency and high throughput.
Scenario
Your team has fine-tuned a 7-billion-parameter text generation model. Product wants to expose it as a REST API that external developers can call. Within six months you expect:
- 1,000 requests per minute at peak
- Average prompt length: ~300 tokens; average output length: ~200 tokens
- P95 latency target: first token in ≤ 1 second, full response in ≤ 8 seconds
- The model weights fit in a single high-memory GPU (e.g., an 80 GB A100)
You do not need to design the training pipeline, billing, or authentication in depth — focus on the serving path.
What is expected
Walk the interviewer through:
- Requirements clarification — what questions would you ask, and what assumptions do you settle on?
- High-level architecture — components from client to GPU
- API design — key endpoints and parameters
- Request lifecycle and batching strategy — how a request travels through the system
- Scaling approach — how you handle traffic growth
- Key trade-offs — at least two concrete ones with reasoning
Hints
Hint 1
Think about what happens when many requests arrive simultaneously — can you process them together somehow, and what are the limits of doing so?
Hint 2
A single GPU can serve requests, but what sits in front of it? Consider what components handle routing, queuing, and load distribution.
Hint 3
Streaming responses (token by token) and batch responses have very different latency profiles — when would you choose each, and how does that affect your API contract?
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements Clarification
Before designing, a strong candidate asks:
- Streaming or batch response? Streaming (server-sent events) dramatically improves perceived latency; assume we support both.
- Synchronous or async API? At 1,000 RPM (~17 RPS) a synchronous API is viable; no need for a job-queue model yet.
- SLA on availability? Assume 99.9% uptime — one GPU going down needs a fast failover path.
- Multi-tenancy isolation? Assume a shared pool for now; per-tenant GPU pinning is a future concern.
- Prompt/output length variance? High variance matters for batching; assume moderate variance with the numbers above.
2. High-Level Architecture
Client
│ HTTPS
▼
API Gateway (rate limiting, auth token validation, TLS termination)
│
▼
Inference Router (stateless, horizontally scalable)
│ picks least-loaded worker
▼
Request Queue (in-memory or Redis, per GPU worker)
│
▼
Inference Worker (one process per GPU)
├── Continuous Batching Engine (e.g., vLLM or TGI)
│ └── A100 GPU
└── Streams tokens back up the chain via SSE / chunked HTTP
Key components:
- API Gateway: handles auth, rate limits, and TLS. A managed gateway (or nginx + middleware) keeps the inference workers free of that overhead.
- Inference Router: stateless HTTP service. Routes to workers, tracks in-flight request counts for load balancing. Can be scaled horizontally without touching GPU state.
- Per-GPU Request Queue: a bounded queue (e.g., depth 50–100) in front of each worker. Provides backpressure — if the queue is full, the router returns HTTP 429 immediately rather than letting latency blow up.
- Inference Worker: one Python process owning one GPU, running a continuous batching engine.
3. API Design
POST /v1/completions
Request body:
{
"prompt": "...",
"max_tokens": 200,
"temperature": 0.7,
"stream": true // boolean; default false
}
Response (stream=false):
{
"id": "req_abc123",
"text": "...",
"usage": { "prompt_tokens": 310, "completion_tokens": 198 }
}
Response (stream=true):
Server-Sent Events, one event per token:
data: {"token": "Hello", "index": 0}
...
data: {"token": "", "finish_reason": "stop"}
GET /v1/health — liveness check for the load balancer.
Keep the API surface small. Do not expose model internals (logits, hidden states) in v1.
4. Request Lifecycle and Batching
Continuous batching (the critical insight)
Naive static batching waits to accumulate N requests then runs them together — terrible for latency. Continuous batching (used by vLLM, TGI) works differently:
- Each forward pass of the model processes a dynamic batch of active sequences.
- When one sequence finishes, its GPU memory slot is immediately freed and a waiting request is inserted into the next iteration.
- This keeps GPU utilization near 100% without forcing any request to wait for an artificially large batch to fill.
Memory: PagedAttention
KV-cache memory for long sequences is the bottleneck. Paged attention (vLLM) stores KV-cache in non-contiguous pages (like virtual memory), eliminating fragmentation and allowing 2–4× more concurrent sequences on the same GPU compared to contiguous allocation.
Latency path for a single request
- Client sends POST → API Gateway validates token → Inference Router picks worker with shortest queue → enqueued (~1–5 ms).
- Worker picks up request in the next batch iteration → prompt is prefilled (one forward pass over all prompt tokens) → first token emitted (target ≤ 1 s).
- Autoregressive decode: one forward pass per output token, batched with other active sequences → tokens streamed back.
- Sequence ends → memory freed → next queued request admitted.
5. Scaling Approach
Vertical first: one A100 with continuous batching handles ~17 RPS at these lengths comfortably. Measure actual GPU utilization and queue depth before adding hardware.
Horizontal scale-out: add more GPU workers behind the Inference Router. Workers are stateless (weights are loaded once at startup); the router simply round-robins or least-connections routes.
Model replicas vs. tensor parallelism: for a 7B model that fits on one GPU, replicate the entire model across N GPUs (each a full copy) rather than sharding — simpler, lower latency, no inter-GPU communication overhead.
Auto-scaling signal: use GPU memory bandwidth utilization and queue depth, not CPU metrics, to trigger scale-out.
6. Key Trade-offs
Trade-off 1: Streaming vs. batch response
Streaming (SSE) delivers first-token latency well under 1 s and feels fast to users, but complicates clients (must handle chunked streams) and makes response caching impossible. Batch response is simpler but user waits 5–8 s staring at nothing. Decision: default to streaming for interactive use cases; offer batch for programmatic bulk calls where the caller prefers a single JSON blob.
Trade-off 2: Queue depth vs. latency
A deeper queue tolerates traffic spikes without dropping requests (fewer 429s) but allows latency to grow unboundedly under sustained overload — a user could wait minutes in queue while expecting a 1 s response. A shallow queue (depth ~30–50, corresponding to ~3 s of processing time at current throughput) provides a hard latency bound and fails fast, letting the client retry or show a degraded message. Decision: use a shallow queue and communicate capacity honestly via 429 + Retry-After header.
Trade-off 3: One large model vs. smaller distilled model
Serving the full 7B model gives best quality but higher cost and latency. A distilled 1–2B model can run on a cheaper GPU (e.g., A10G) with sub-200 ms first-token latency. Unless quality benchmarks show a clear regression, consider the smaller model for latency-sensitive paths and route longer/complex prompts to the larger model.
Common Mistakes to Avoid
- Forgetting the KV-cache memory budget: assuming you can batch 100 requests without accounting for the memory each sequence's KV-cache consumes — this is the real capacity constraint, not compute.
- Using CPU auto-scaling metrics: GPU workers are bottlenecked on memory bandwidth and VRAM, not CPU — CPU metrics will mislead you.
- No backpressure: accepting requests indefinitely and queuing them causes latency to explode silently; always bound the queue and return 429 early.
- Tensor parallelism for a single-GPU-sized model: adds communication overhead and operational complexity with no benefit when the model fits on one GPU.