Design an LLM Inference Gateway with Request Batching
System DesignModel answerLast updated
Design a production gateway that receives streaming LLM requests, batches them efficiently, routes to GPU backends, and handles autoscaling under bursty traffic.
Scenario
Your company offers a developer API that lets third-party applications call a self-hosted large language model (7B–70B parameter range). Traffic is bursty: calm during nights, spiky during business hours, with occasional viral bursts 10–20x above the baseline. Latency SLAs matter — customers care about time-to-first-token (TTFT) and total generation time.
You currently run a few GPU servers but have no serious infrastructure between the caller and the model process. The on-call engineer keeps getting paged because queues overflow or cold GPUs serve the first tokens slowly.
What you are expected to design
Design an LLM Inference Gateway that sits between API callers and GPU backends. Your design should address:
- Requirements & scale — clarify functional and non-functional requirements; propose concrete numbers.
- API contract — what does the gateway expose to callers? What does it expose to backend workers?
- Data model — what state does the gateway need to track per request?
- Core architecture — components, data flow, how continuous batching works at a high level.
- Autoscaling — how do you scale GPU workers up and down without dropping requests?
- Deep dives — pick at least two: token streaming to the caller, request prioritization, cost-aware routing, handling very long contexts.
- Trade-offs — discuss at least two meaningful design decisions where reasonable engineers could disagree.
Constraints / assumptions you may state
- You may use any cloud or open-source components.
- The model weights are already loaded on each GPU worker; cold-start is 2–4 minutes.
- You do not need to design the model itself or training infrastructure.
- One GPU worker can serve one or more requests simultaneously via continuous batching.
Hints
Hint 1
Start by separating concerns: the gateway is a CPU-bound routing layer; the GPU worker is compute-bound. Keep them independently scalable and think about what state must live where.
Hint 2
Continuous batching (iteration-level scheduling) is the key technique that lets a GPU interleave tokens from multiple requests — contrast it with static batching to show you understand the trade-off.
Hint 3
For streaming, think end-to-end: the GPU emits one token at a time, the gateway must fan it out to the right HTTP/SSE connection. Where can you lose tokens? Where can you buffer too aggressively?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & Scale
Functional
- Accept text (and optionally image) prompts; return streamed token responses.
- Support per-customer API keys with rate limits and quotas.
- Allow callers to specify model variant, sampling parameters (temperature, top-p), and max tokens.
Non-functional
- TTFT p95 ≤ 800 ms at baseline load.
- Throughput: ~5,000 requests per minute at peak (≈ 83 RPS).
- Availability: 99.9% (≤ 8.7 h downtime/year).
- GPU utilization target: 70–85% at steady state.
Out of scope: model training, fine-tuning pipelines, prompt/response storage beyond short-term logging.
2. API Contract
Caller → Gateway (external)
POST /v1/completions
Authorization: Bearer <api_key>
{
"model": "llm-70b",
"messages": [...],
"max_tokens": 512,
"stream": true,
"priority": "standard" | "bulk"
}
Response: text/event-stream with Server-Sent Events (SSE), each event carrying a token delta and a finish reason on the final event.
Gateway → Worker (internal)
POST /infer (HTTP/2 or gRPC)
{
"request_id": "<uuid>",
"prompt_tokens": [...], // already tokenized
"sampling_params": {...},
"max_new_tokens": 512
}
Workers stream token IDs back over the same connection; the gateway detokenizes and forwards to the caller.
3. Data Model (Gateway State)
The gateway is mostly stateless for the request body (prompt stays with the worker), but tracks:
| Field | Type | Purpose |
|---|---|---|
| request_id | UUID | Correlation key end-to-end |
| api_key_id | FK | Rate limiting, billing |
| status | enum | queued / running / streaming / done / error |
| worker_id | string | Which GPU pod owns this request |
| enqueued_at | timestamp | Queue-time SLA tracking |
| token_count_so_far | int | For quota enforcement mid-stream |
| sse_connection | handle | Live HTTP connection to caller |
A fast in-process map (one per gateway replica) plus a distributed rate-limit counter in Redis is sufficient. Avoid storing full prompts in Redis — they can be MBs.
4. Core Architecture
Callers
│ HTTPS / SSE
▼
Load Balancer (L7)
│
▼
Gateway Fleet (stateless CPU pods, horizontally scaled)
│ tokenize, validate, enqueue
▼
Request Queue (per-model, per-priority — e.g., two tiers in a message broker)
│ workers pull batches
▼
Worker Pool (GPU pods, one process per GPU)
│ continuous batching, generate tokens
▼
Token stream back → Gateway → SSE to caller
Continuous batching (key concept): Unlike static batching (wait, collect N requests, run together, return all), continuous batching schedules at the iteration level. The GPU scheduler checks after every forward pass whether a slot has finished and can be replaced by a queued request. This keeps GPU utilization high without forcing new requests to wait for the longest running one. A 70B model on an A100 can typically run 8–32 concurrent sequences this way.
Tokenization happens in the gateway (CPU), not on the GPU, to avoid wasting accelerator time.
5. Autoscaling
Scale-out trigger: queue depth > N seconds of expected drain time (e.g., > 30 s of backlog), evaluated every 15 s.
Scale-in: utilization < 40% for 5 consecutive minutes, with a minimum floor of 2 workers to avoid cold-start latency on sudden spikes.
Cold-start mitigation (2–4 min is painful):
- Keep 1–2 "warm standby" workers running at all times (cost: ~15% GPU overhead).
- Pre-pull model weights to node local disk so startup is IO-bound, not network-bound.
- Queue requests during scale-out rather than failing them — callers get higher TTFT once the worker is ready, not an error.
Spot/preemptible GPUs: Use for bulk/low-priority traffic. Standard-priority requests route only to on-demand workers.
6. Deep Dives
Token Streaming to Callers
The worker streams token IDs to the gateway over gRPC server streaming. The gateway maintains an open SSE connection to the caller, keyed by request_id. Each token chunk is forwarded immediately — no buffering — to minimize TTFT perception.
Risk: if the caller's network is slow, the gateway must back-pressure. Options: drop the SSE connection and let the caller retry (simplest), or buffer up to ~50 tokens per request in memory with a timeout (complexity vs. resilience trade-off).
Request Prioritization
Two queue tiers: standard (interactive, lower latency SLA) and bulk (batch jobs, higher throughput SLA). Workers pull from standard first; they only pull from bulk when standard is empty or they have spare capacity slots. This prevents bulk jobs from starving interactive users without requiring separate GPU pools.
7. Trade-offs
Single shared queue vs. per-worker queues
A single queue (per model tier) makes routing simple and avoids hot spots — any worker can take any request. The downside is that KV-cache reuse across requests is harder (useful for prefix caching of shared system prompts). Per-worker queues enable prefix-cache affinity routing but add complexity and can create unbalanced load. For most deployments at medium scale, a shared queue with optional "sticky" routing for known high-reuse prefixes is the right balance.
Tokenizing at the gateway vs. at the worker
Tokenizing in the gateway lets the gateway enforce token quotas before the request reaches the GPU and allows accurate queue-depth estimates in tokens (not chars). The downside is that the gateway needs the tokenizer vocab loaded in memory (~500 MB for a large tokenizer), and a tokenizer update must be synchronized between gateway and worker. At scale this is worth doing; for a small deployment, tokenizing at the worker is simpler.
Common Mistakes to Avoid
- Treating TTFT and throughput as the same metric. Optimizing only throughput (larger batches) hurts TTFT. Expose both in your SLA discussion.
- Storing the full prompt in the queue. Prompts can be 10s of KB–MBs. Pass a reference or stream directly to the worker; don't route large payloads through Redis.
- Ignoring worker crash mid-stream. The gateway must detect a dropped gRPC stream and either retry (if the request was not yet started) or return a partial-response error to the caller.
- No graceful drain on scale-in. Terminating a worker mid-generation drops all in-flight streams. Workers should receive a SIGTERM, stop accepting new work, finish current sequences, then exit.