---
title: Design, and partly code, a single-GPU inference service that batches incoming requests up to a maximum batch size while…
url: https://gurkanozkan.ai/learn/questions/applied-llm-srv-10/
markdown: https://gurkanozkan.ai/learn/questions/applied-llm-srv-10.md
kind: question
role: Applied LLM
stage: Technical
difficulty: Hard
json: https://gurkanozkan.ai/api/learn/questions/applied-llm-srv-10.json
robots: noindex
---

# Design, and partly code, a single-GPU inference service that batches incoming requests up to a maximum batch size while each caller waits synchronously for its own result. How do you trade latency against throughput?

Applied LLM · Technical · Hard

Theme reported publicly: [Anthropic](https://interviewing.io/anthropic-interview-questions)

## Answer

*Model answer, written in a candidate's voice*

### In short

- Bounded queue; batcher fires on max batch size or max wait; per-request futures resolve results (asyncio sketch)
- Larger batches raise throughput but add queueing delay; adaptive max_wait by load; never wait for a full batch at low traffic
- Bucket/pad by sequence length to reduce padding waste
- Backpressure: 429 with Retry-After when the queue is full, per-request deadlines, skip abandoned requests
- Generative models: iteration-level continuous batching beats request-level batching
- One bad item must not fail the batch: validate first, rerun items individually on batch failure
- Metrics: batch-size histogram, queue time, latency, rejects, timeouts, cancellations, padding waste

### In full

I would put a bounded in-memory queue in front of a single-GPU worker. Each caller submits a request and awaits a future; the batching loop fires when it has max_batch items or when max_wait has elapsed since the first item arrived, runs one forward pass, and resolves each future with that request's result or error.

```python
import asyncio, time

class OverloadedError(Exception):
    """Mapped to HTTP 429 with Retry-After by the web layer."""

class Batcher:
    def __init__(self, model_fn, max_batch=16, max_wait_s=0.01, max_queue=1024):
        self.model_fn = model_fn                 # list of inputs -> list of outputs, one GPU pass
        self.max_batch, self.max_wait_s = max_batch, max_wait_s
        self.queue = asyncio.Queue(maxsize=max_queue)   # bounded: backpressure

    async def submit(self, x, timeout_s=5.0):
        fut = asyncio.get_running_loop().create_future()
        try:
            self.queue.put_nowait((x, fut))
        except asyncio.QueueFull:
            raise OverloadedError()
        return await asyncio.wait_for(fut, timeout_s)   # a timeout cancels the future

    async def run(self):
        while True:
            batch = [await self.queue.get()]
            deadline = time.monotonic() + self.max_wait_s
            while len(batch) < self.max_batch:   # fire on max size OR max wait
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    break
                try:
                    batch.append(await asyncio.wait_for(self.queue.get(), remaining))
                except asyncio.TimeoutError:
                    break
            batch = [(x, f) for x, f in batch if not f.done()]   # skip abandoned callers
            if not batch:
                continue
            inputs = [x for x, _ in batch]
            try:
                results = await asyncio.to_thread(self.model_fn, inputs)
            except Exception:
                results = []                     # isolate the bad item, keep the rest
                for x in inputs:
                    try:
                        results.append((await asyncio.to_thread(self.model_fn, [x]))[0])
                    except Exception as e:
                        results.append(e)
            for (_, f), r in zip(batch, results):
                if f.done():
                    continue
                if isinstance(r, Exception):
                    f.set_exception(r)
                else:
                    f.set_result(r)
```

The core trade-off is that larger batches improve GPU utilisation and throughput but add queueing delay and tail latency. I would make max_wait adaptive: short under low load so a lone request is not held waiting for a batch that never fills, longer under high load when the batch fills quickly anyway. I would also bucket or pad by sequence length so short inputs do not pay for long ones.

Backpressure is explicit: when the queue is full the service returns 429 with Retry-After, each request has a deadline, and a cancelled or timed-out request is skipped rather than computed for nobody. For generative models I would not use request-level batching as the main design: iteration-level (continuous) batching schedules active sequences at every decoding step, so new requests join and finished ones leave between steps and variable-length outputs do not hold the whole batch hostage. One bad item must not fail the batch: validate inputs before batching and, if a batched call still fails, rerun the items individually so only the bad one gets an error. I would track a batch-size histogram, queue wait time, end-to-end latency, rejects, timeouts, cancellations and per-bucket padding waste, and tune max_batch and max_wait from those curves rather than from a fixed guess.

*Corrected by an independent AI reviewer.*

## What a strong answer covers

- Bounded queue; batcher fires on max batch size **or** max wait time; per-request futures resolve results
- Larger batches raise throughput and queueing delay; adaptive wait by load; bucket/pad by sequence length
- Backpressure: reject or 429 when full, timeouts, cancel abandoned requests
- For generative models, iteration-level (continuous) batching beats request-level batching
- One bad item must not fail the batch; metrics on batch-size histogram and queue time

## Common mistakes

- Unbounded queues
- waiting for a full batch at low traffic so latency explodes

## Topic guides

- [LLM inference: decoding, batching, quantisation and speculative decoding](https://gurkanozkan.ai/learn/topics/inference.md)
- [LLM serving: latency, throughput and operations](https://gurkanozkan.ai/learn/topics/serving.md)
- [ML and LLM system design](https://gurkanozkan.ai/learn/topics/system-design.md)
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
