Batching Service for Autocomplete Inference with Fixed Batch Time
System DesignModel answerLast updated
Design a low-latency serving stack that groups autocomplete requests into fixed-duration accelerator batches, sizes the fleet, handles failures, and critiques the fixed-time premise.
You are building the backend for an as-you-type code suggestion feature in an editor extension. Whenever the user stops typing briefly, the extension sends the text surrounding the cursor and waits for one suggested continuation. The model runs on GPU/accelerator hosts. Serving one prompt at a time leaves most of the hardware idle, so the service must combine requests into batches.
To get started, assume this simplification: every batch, of any size up to the cap, takes exactly 250 ms to execute.
Requirements
Functional
- Each request gets exactly one completion or an explicit error.
- Clients can cancel (the extension does this when the user resumes typing).
- Two service tiers exist. Paying users should see lower latency when the system is loaded.
Non-functional (propose different numbers if you justify them)
- Peak traffic: 40,000 requests/second across the world.
- Maximum batch size per model replica: 64.
- End-to-end p99 latency below 600 ms, network included.
- 99.9% availability. Losing one accelerator host must not produce user-visible errors.
What to cover
- The end-to-end request path with each component named.
- The batch-forming policy: what causes a batch to launch, and how this differs at low versus high load.
- Capacity math: replica count at peak with headroom, and the queueing delay it implies.
- How outputs of a finished batch reach the right waiting connection, and what happens if that caller is gone.
- Failure handling: replica crash mid-batch, traffic spikes, loss of a region.
- Critique the fixed 250 ms premise. What might that number really include? What goes wrong when prompt and output lengths vary widely, and how would you change the design?
Clarifying questions you might raise
- Is the 250 ms for prefill only, for full generation, or for the entire round trip?
- Is it the same for batch size 1 and batch size 64, and for short and long prompts?
- Is there a single model, or several that cannot be batched together?
Hints
Hint 1
Start with throughput per replica (batch size divided by batch time), then divide the peak load by it and add utilization headroom and redundancy across regions.
Hint 2
Under a fixed-cost model, a partial batch costs the same as a full one, so think about when waiting for more requests is pointless. Then add a maximum wait and a deadline-aware drop rule for cancelled or expired requests.
Hint 3
For the critique, separate prefill from decoding: decoding costs one forward pass per output token, so batch time depends on the longest output. Think about iteration-level (continuous) batching and KV-cache memory as the real capacity limit.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Request path
Editor extension --gRPC/HTTP2--> Edge load balancer --> Gateway
(auth, rate limits, tier tagging, deadline stamping)
--> Router (chooses model pool and replica using reported queue depth)
--> Replica scheduler (on the accelerator host: priority queues + batcher)
--> Executor (runs the batch)
--> result routed back to the gateway holding the caller's stream
- Gateway: terminates the client stream, keeps a
request_id -> streammap in memory, and stamps a deadline (for example now + 550 ms). - Router: sends work to the replica with the lowest reported queue depth or estimated wait. This reacts to a slow replica better than round-robin.
- Replica scheduler: co-located with the accelerator so forming a batch adds no network hop. It keeps two queues, paid and free.
2. Batch-forming policy
Whenever the executor is idle, launch a batch if any of these holds:
- The queue has at least 64 requests (full batch).
- The oldest request has waited
max_wait(say 20 to 30 ms). - The queue is non-empty and the device would otherwise idle. With fixed cost per batch, waiting buys nothing once the hardware is free.
Low load: rule 3 dominates, so latency is about one batch time plus network. High load: batches fill while the previous one runs, so the device stays saturated and the batch is naturally full.
Fill order: paid first, but cap the paid share (for example 75%) so free traffic is not starved. Before filling, discard cancelled or deadline-expired entries so they do not consume slots.
3. Capacity math
- Per replica: 64 / 0.25 s = 256 req/s.
- Peak: 40,000 / 256 ≈ 157 replicas at 100% utilization.
- At a 70% utilization target: ≈ 225 replicas.
- Spread across at least 3 regions with N+1 headroom per region: about 260 replicas.
Latency budget (worst case): network 60 ms + gateway/router 10 ms + queue wait up to one batch period (250 ms) + execution 250 ms ≈ 570 ms, inside the 600 ms target. Average queue wait is about half a batch (about 125 ms) for a request arriving mid-batch. The key insight: queue wait plus execution is roughly 2x the batch time, so the p99 lever is keeping queue wait below one batch period, which means keeping utilization under control.
4. Returning results
Each output is tagged with request_id and gateway_id. The scheduler pushes results to the owning gateway over a persistent connection; the gateway finds the stream and writes the response. If the stream is gone (cancel or timeout), the result is dropped and a "wasted slot" counter increments. Cancels are also forwarded to the scheduler so a still-queued request is removed before it takes a slot. A cancel that arrives after the batch has launched cannot be reclaimed, which is why the wasted-slot metric matters.
5. Failure handling
- Replica crash mid-batch: the gateway notices via a stream error or its deadline. Inference is side-effect free, so it retries once on another replica, only if enough deadline remains.
- Overload spike: admission control at the router. If estimated queue wait exceeds the remaining deadline, fail fast (429 or "no suggestion"). A dropped suggestion is better than a late one. Shed free traffic first, then autoscale.
- Region loss: GeoDNS or anycast failover. The headroom in surviving regions absorbs the load while autoscaling adds capacity. Accelerators take minutes to start, so keep warm spares.
- Poison prompts: if a request has been in two failed batches, quarantine it so it cannot repeatedly kill replicas.
- Host loss with 99.9% target: health checks eject a bad host from routing within seconds; in-flight requests are retried.
6. Challenging the 250 ms assumption
Questions to ask: does it include prefill only or full generation, queueing, and network? Does it hold at batch size 1 and 64, and across prompt lengths?
In reality it is not constant:
- Prefill cost grows with prompt tokens.
- Decoding takes one forward pass per generated token, so a batch generating 200 tokens takes far longer than one generating 5.
- With static batching, every request waits for the slowest in its batch (head-of-line blocking), and short requests waste slots on padding.
Redesign:
- Use continuous (iteration-level) batching: the scheduler runs per decoding step (roughly 20 to 40 ms). Finished sequences leave immediately; waiting requests join at the next step.
- The capacity limit becomes KV-cache memory, not a request count. Admission control asks "are enough KV blocks free?", and paged KV allocation reduces fragmentation.
- Measure what users feel: time to first token and time per output token, not batch time.
- If prompt lengths vary a lot, consider separate prefill and decode pools, and cap maximum output tokens (completions are short anyway).
- If static batching must remain, bucket by length to reduce padding waste.
- Capacity planning then uses measured tokens/second per replica at a target latency, not 64 / 0.25.
Observability
Track per replica: queue depth, batch fill ratio, wait time, execution time, cancelled and discarded results. Track p50/p99 per tier. Alert when fill ratio is high and queue wait approaches one batch period, since that signals saturation.
Common mistakes
- Waiting to fill a batch even when the device is idle.
- Forgetting that queue wait adds a full extra batch period to p99.
- Sizing at 100% utilization with no regional redundancy.
- Retrying blindly during overload, which amplifies the spike.
- Treating the fixed-time assumption as true in production.