Build a Request Batching System for LLM Serving
System DesignModel answerLast updated
Design an inference service that groups incoming LLM requests into batches, assuming 100ms processing per batch, with attention to queueing, routing, and failure modes.
You're building a service that handles inference for a large language model. Clients submit prompts and wait for generated responses. Rather than processing requests individually, your service collects pending requests into groups and processes each group together to maximize hardware utilization.
Given constraint: Assume processing one group takes exactly 100 milliseconds.
Design the complete request flow—from when a client submits a prompt through returning the generated text—including your grouping strategy, capacity planning, result distribution, and error recovery. Clearly state what activities the 100ms includes and excludes.
What to Address
- How requests move from arrival to processing and back to clients
- Your policy for forming groups (triggers, size limits, timing)
- Calculating how many processing units you need
- Routing individual results from a group back to the correct waiting clients
- Handling worker crashes, problematic requests, and overload
Parameters to Consider
You may ask about these or state reasonable assumptions:
- Expected request rate and target latency (first token vs. complete response)
- Maximum group size the hardware supports
- Whether you have one model or multiple that cannot share groups
- Streaming vs. complete response delivery
- Prompt and response length distributions
Hints
Hint 1
Break down total latency into stages: network, waiting for group formation, processing, and return path
Hint 2
Consider both time-based and size-based triggers for closing a group
Hint 3
Challenge the fixed 100ms assumption—what real-world factors would make batch time variable?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Clarifying Questions First
Before designing, I'd confirm:
- What does 100ms measure? Pure GPU compute for one group, or does it include data transfer to/from the accelerator?
- Maximum group size? Batching efficiency typically caps at 16-64 requests depending on memory.
- Latency SLA? For example, p99 < 500ms for first token, or for complete response?
- Request volume? Say 1,000 requests/second to size the system.
- Streaming? Token-by-token streaming complicates result routing but improves perceived latency.
Assumptions for this design: 100ms is pure model compute, max batch size is 32, target is p99 < 400ms end-to-end for complete responses, 1,000 req/s, single model, responses returned whole (not streamed).
Architecture Overview
Components:
- API Gateway - receives requests, assigns IDs, enforces rate limits
- Batch Coordinator - queues requests, forms batches, tracks in-flight work
- Inference Workers - GPU instances that process batches
- Result Router - matches outputs to waiting clients
Latency Budget
Breaking down our 400ms target:
- Network ingress: 20ms (client to gateway)
- Queueing + batch formation wait: 100ms (worst case: just miss a batch)
- Model processing: 100ms (given)
- Network egress + routing: 20ms (worker to client)
- Buffer for variance: 160ms
This budget implies we must form batches frequently enough that queued requests don't wait beyond ~100ms.
Batching Policy
Dual trigger system:
- Size trigger: Close batch when 32 requests accumulate (maximize throughput)
- Time trigger: Close batch after 50ms even if only partially filled (bound latency)
Rationale: At 1,000 req/s, we get 50 requests every 50ms. With 50ms timeout, worst-case queue wait is 50ms, keeping us within budget. Size trigger ensures we don't waste capacity during high load.
Trade-off: Shorter timeout (e.g., 25ms) improves p99 latency but means more partially-filled batches, wasting GPU cycles. Longer timeout (e.g., 100ms) improves utilization but increases tail latency.
Capacity Planning
Throughput per worker:
- Batch completes in 100ms = 10 batches/second per worker
- At full batches: 32 requests/batch × 10 batches/s = 320 req/s per worker
Workers needed:
- For 1,000 req/s: 1,000 ÷ 320 = 3.125 workers minimum
- Add 50% headroom for bursts and partial batches: 5 workers
Why headroom matters: During off-peak, batches won't fill completely. If average batch size drops to 20, throughput per worker falls to 200 req/s, and we'd need 5 workers even at steady state.
Request Flow and Result Routing
Inbound:
- Client sends prompt to Gateway
- Gateway generates request_id, adds
(request_id, prompt, response_future)to Coordinator queue - Gateway returns 202 Accepted to client with request_id, keeps connection open
Batching:
- Coordinator monitors queue, forms batch when size=32 or 50ms elapsed
- Creates
batch_id, serializes prompts into single payload - Sends
(batch_id, [request_ids], batch_payload)to available Worker - Stores mapping:
batch_id → [request_id₁, request_id₂, ...]
Outbound:
- Worker processes batch, returns
(batch_id, [response₁, response₂, ...]) - Result Router looks up request_ids from batch_id
- Router matches each response to its request_id, resolves corresponding response_future
- Gateway streams response back to waiting client
Data structure: Use a hash map request_id → (client_connection, timestamp) to route results. Timeout and close connections after 1 second if no response arrives.
Failure Handling
Worker crashes mid-batch:
- Set 200ms timeout when sending batch to worker (2× expected time)
- On timeout, requeue all requests from that batch
- Mark worker as unhealthy, remove from pool
- Risk: Requests that were close to timing out may now exceed SLA. Mitigate with retry budgets—fail fast if request has been retried twice.
Poisonous requests:
- If a specific request causes crashes in 2 consecutive batches, quarantine it
- Return 400 Bad Request to client
- Log for investigation (likely adversarial input or edge case)
Overload and backpressure:
- If queue depth exceeds 5 seconds of work (5,000 requests), reject new requests with 503 Service Unavailable
- Prevents queue buildup that guarantees SLA violations
- Clients should implement exponential backoff retry
Partial failures:
- If worker returns fewer responses than requests in batch, map by position
- For missing responses, retry those specific requests in a new batch
Challenging the 100ms Assumption
Real-world variability:
-
Prompt length: Longer prompts mean more tokens to process in the prefill phase. A 10-token prompt might take 50ms, a 1,000-token prompt could take 300ms.
-
Response length: Each generated token adds time. If we're generating 100 tokens at 2ms/token, that's 200ms just for generation, not 100ms total.
-
Batch size: Smaller batches underutilize parallelism. A batch of 4 might complete in 80ms, batch of 32 in 100ms, batch of 64 in 150ms due to memory contention.
-
Model architecture: A 7B parameter model might sustain 100ms batches; a 70B model could take 500ms+ for the same batch.
Adaptive approach: Monitor actual batch completion times and adjust the time trigger dynamically. If p50 batch time grows to 150ms, increase timeout to 75ms to maintain latency targets. Track metrics per prompt-length bucket for smarter scheduling.
Common Mistakes
- Ignoring queueing time: Treating 100ms as end-to-end latency when queue wait dominates
- No backpressure: Accepting unlimited requests leads to queue explosion and guaranteed timeouts
- Forgetting result ordering: Responses must map back to the correct client, especially when batches contain unrelated requests
- Single point of failure: Coordinator going down loses all in-flight state—needs replication or persistent queue
- Not monitoring batch utilization: Without metrics on average batch size, you can't tell if you're wasting capacity