Design a Low-Latency LLM Inference Gateway
System DesignModel answerLast updated
Design a production gateway that routes, batches, and serves LLM inference requests at scale with low latency and high throughput.
Scenario
Your company runs a B2B SaaS product that embeds an AI assistant into third-party applications. Customers send chat completion requests (think: a /v1/chat/completions style API) to your platform, which routes them to one or more large language models you host internally on GPU clusters.
You are asked to design the LLM Inference Gateway — the layer that sits between external clients and the raw model servers.
Scale & Requirements
Functional requirements
- Accept streaming and non-streaming chat completion requests
- Support multiple models (e.g., a 7B, a 70B, and a 405B parameter model)
- Enforce per-tenant rate limits and quotas
- Return token-by-token streaming responses (SSE/WebSocket)
Non-functional requirements
- P50 time-to-first-token (TTFT) under 500 ms, P99 under 2 s
- Throughput: sustain 5,000 requests per second (RPS) at peak
- At least 99.9% availability
- Cost efficiency: GPU utilization should stay above 70% during business hours
What is expected
Walk through:
- API design — what does the external-facing contract look like?
- Architecture — what are the major components and how do they interact?
- Request routing and batching — how do you decide which model server handles a request?
- Streaming — how does token-by-token output flow back to the client?
- Key deep dives — at least two of: rate limiting, continuous batching, KV-cache management, autoscaling, or fault tolerance
- Trade-offs — where did you make explicit choices and what did you give up?
Hints
Hint 1
Start by separating the gateway's concerns from the model server's concerns — the gateway should be stateless so it scales horizontally, while the model server manages GPU state (KV cache).
Hint 2
Continuous batching (also called iteration-level scheduling) is the key technique that keeps GPU utilization high without sacrificing latency — explain how it differs from static batching.
Hint 3
Streaming over SSE requires the gateway to hold open long-lived connections; think about what this means for connection counts, load balancer timeouts, and back-pressure.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarifications to Make First
Before designing, confirm:
- Are models hosted on-prem or via a mix with third-party APIs as fallback?
- Is streaming mandatory for all tiers, or just paid tiers?
- What is the max context window? (Affects KV cache sizing and timeout budgets.)
- Multi-region or single-region for now?
Assume: on-prem GPU cluster, streaming for all tiers, 8K–128K context window depending on model, single region initially.
2. API Design
POST /v1/chat/completions
Headers:
Authorization: Bearer <tenant_api_key>
X-Model: llm-70b (or passed in body)
Body:
{
"model": "llm-70b",
"messages": [...],
"stream": true,
"max_tokens": 512,
"temperature": 0.7
}
Response (streaming): text/event-stream (SSE)
data: {"id":"...","choices":[{"delta":{"content":"Hello"}}]}
data: [DONE]
Response (non-streaming): standard JSON object
Key decisions:
- OpenAI-compatible schema reduces client integration cost.
X-Modelheader (or body field) allows routing without parsing the full payload at the edge.- SSE is preferred over WebSocket for unidirectional streaming — simpler infrastructure, works through HTTP/2, and plays well with CDN/proxies.
3. Architecture Overview
Clients
|
[Edge Load Balancer] (L7, TLS termination, sticky for streaming)
|
[Gateway Service] (stateless, horizontally scaled, ~20 pods)
| |- Auth & rate-limit check (Redis)
| |- Request validation
| |- Model router
|
[Request Queue per model tier] (e.g., Kafka or in-memory priority queue)
|
[Inference Workers / Dispatch Layer]
|
[Model Servers] (vLLM or TGI on GPU nodes, one process per GPU group)
|
[Response Stream relayed back through Gateway → Client]
The gateway is intentionally thin and stateless. All GPU-side state (KV cache, batch slots) lives on the model servers.
4. Request Routing and Batching
Routing
- Map
modelfield → model tier → pool of model servers for that tier. - Within a pool, route to the server with the fewest active sequences (not fewest requests — a long 128K-context sequence consumes far more KV cache than ten 1K-context ones).
- Fall back to least-loaded by GPU memory utilization, polled every 1 s via a sidecar metrics endpoint.
Continuous Batching (iteration-level scheduling)
- Static batching waits to fill a full batch before starting a forward pass — this destroys latency for short requests stuck behind long ones.
- Continuous batching (used by vLLM, TGI) inserts new sequences into the running batch at each decoding step. A sequence that finishes frees its slot immediately.
- Result: GPU stays busy, new requests don't wait for the whole batch to drain. Typical GPU utilization improvement from ~40% (static) to 70–85% (continuous).
- The gateway's dispatch layer sends a request to a model server and opens a gRPC stream; the model server pushes tokens as they are generated.
5. Streaming Back to the Client
Token relay pipeline:
- Model server generates a token → pushes via server-side gRPC stream to the inference worker/dispatch layer.
- Dispatch layer forwards the token chunk to the gateway pod that owns the client connection.
- Gateway pod writes an SSE
data:frame to the open HTTP connection.
Challenge: connection affinity
- The gateway pod that accepted the request must remain the one writing SSE frames. Solve with consistent-hash or session-cookie sticky routing at the load balancer.
- Alternatively, use a pub/sub channel (e.g., Redis Streams keyed by
request_id): any gateway pod can subscribe and relay. This decouples the gateway pods at the cost of a small extra hop (~1–2 ms).
Back-pressure
- If the client reads slowly, the TCP send buffer fills. The gateway must respect write-back-pressure and pause pulling tokens rather than buffering unboundedly in memory.
Timeout handling
- Generating 128K output tokens at 50 tokens/s would take roughly 2,560 seconds (~43 minutes) — clearly impractical. The real mitigation is to enforce a contractual
max_tokenscap (e.g., 4K) so that generation time stays within a few minutes at most. Set load balancer idle timeout above that bounded maximum. - Use heartbeat SSE comments (
: keep-alive) every 15 s to prevent proxy timeouts on shorter responses.
6. Deep Dives
Rate Limiting
- Two levels: per-tenant RPM (requests per minute) and TPM (tokens per minute).
- TPM is harder: you don't know output tokens upfront. Charge input tokens at request entry; charge output tokens as they stream back using a post-completion callback to deduct from a sliding window in Redis.
- Use a token-bucket in Redis with a Lua script for atomic check-and-decrement. At 5K RPS, Redis at ~100K ops/s is sufficient with a small cluster.
- Tenants that exceed limits get 429s with a
Retry-Afterheader and their position in a priority queue.
KV Cache Management
- KV cache is the dominant GPU memory consumer. A single 70B model in FP16 needs ~140 GB for weights, leaving ~20–40 GB on an A100-80GB node for KV cache.
- vLLM's PagedAttention divides KV cache into fixed-size blocks (pages), allocating lazily. This avoids fragmentation and raises effective batch size.
- For very long contexts (>32K tokens), the model server may preempt (evict) a low-priority sequence to disk and restore it later. The gateway should surface this as increased latency, not an error.
Autoscaling
- Scale model server pods on GPU memory utilization (target 70%) and queue depth (target <50 ms wait time).
- Cold start for a 70B model (loading weights from NFS/S3 to GPU): ~3–5 minutes. Maintain a minimum warm pool of 2 replicas per model tier; scale-down delay of 10 minutes to avoid thrashing.
- Use predictive scaling on historical diurnal traffic patterns to pre-warm before morning peak.
7. Trade-offs
| Decision | Benefit | Cost |
|---|---|---|
| Stateless gateway + Redis pub/sub for streaming | Horizontal scale, no sticky routing required | Extra ~2 ms latency per token, Redis becomes a dependency |
| Continuous batching | High GPU utilization, low TTFT | More complex scheduler in model server; harder to bound worst-case latency |
| Per-tenant TPM limit charged post-generation | Accurate billing | Tenants can momentarily exceed limit; needs burst allowance |
| Single region initially | Simpler ops | No geo-latency reduction; single point of failure for availability SLA |
| SSE over WebSocket | Simpler, HTTP/2 friendly | Client cannot send mid-stream messages (acceptable for chat completions) |
Common Mistakes to Avoid
- Conflating the gateway with the model server: putting batching logic in the gateway means it has to understand GPU state — keep these concerns separated.
- Ignoring KV cache as the bottleneck: most candidates focus on CPU/network; at scale, KV cache exhaustion is what causes queuing and latency spikes.
- Static batching: always explain continuous batching — interviewers will probe this.
- Not accounting for long-lived connections: 5,000 RPS with average 5-second streams = ~25,000 concurrent open connections. This drives pod sizing (file descriptor limits, memory per connection).