esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Let’s talk

I’ll build the agent for it.

Design Single-GPU Inference Batching

How to design batching for one GPU: the serving loop, the three limits, long prompts and the wait time, explained simply for your AI interview.

In short

Batching lets one GPU work on many requests in the same step, so the chip stays busy. Design it around three limits: the memory the cache can hold, the most requests per step, and how long a request may wait to join a batch.

13 min readAdvancedOccasional · estimateFacts checked 27 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

I would design the batcher as a loop. Requests wait in a queue. Each step, the builder fills a batch under the memory budget and a cap on requests. When the GPU is idle, a short wait lets a batch fill. The GPU writes one token for each request, finished replies leave, and the room refills at once. The hard part is the trade-off. Bigger batches give more work per second, but users wait longer, and a long prompt can stall chat users. I would measure latency first, then tune the wait time and split the long reads.

What is batching on one GPU, in plain words?

A GPU is built to do many small jobs side by side. When it handles one request at a time, much of its capacity can sit idle. Batching means the GPU works on several requests in the same step.

Two measures matter. Throughput is how much work the GPU finishes each second. Latency is how long one user waits. Batching raises throughput, but every extra request in the batch can make each user wait a little longer, so the design sits between the two.

Think of a courier depot loading a van. The van leaves when it is full, or when the first parcel has waited too long. An AI claims assistant faces the same choice. One chat user types "Where is my refund for claim 88412 and when will it land?" while a long contract summary is also in the queue. The batcher must serve both, keep memory safe, and answer the chat quickly.

Key words

Token
The small piece of text a model reads and writes. Often a word, or part of one.
KV cache
Memory that keeps the earlier tokens of each request, so the model does not recompute them at every step.
Prefill
The step where the model reads the prompt. A long prompt can be read in chunks over several steps.
Decode
The later steps, when the model writes one new token at a time.
Time to first token
How long a user waits before the first word appears. Often shortened to TTFT.

How does one batch step work?

The batcher keeps a queue. Each step it builds a batch from the front of the queue, runs the GPU for one token per request, and looks again. Finished requests leave and new ones join at the next step. Once replies are flowing, newcomers join at the next step instead of waiting for the whole batch to finish. Hugging Face describes the idea in its library documentation:

  • “Continuous batching maximizes GPU utilization by dynamically rescheduling the batch at every generation step.”

    Hugging Face, Transformers documentation

  1. 1

    Take requests from the queue

    Add requests in arrival order while the limits allow.

  2. 2

    Run one step

    The GPU writes the next token for every request in the batch.

  3. 3

    Return what is done

    Finished requests send their reply and free their memory.

  4. 4

    Top up and repeat

    Fill the freed room from the queue before the next step.

One GPU, one serving loop

Waiting requests

long and short requests mixed

Batch builder

checks memory, count and wait

GPU runs one step

one new token for each request

Replies finish

finished requests leave

  1. 1The builder takes the next requests from the queue.
  2. 2It hands one batch to the GPU for a single step.
  3. 3Unfinished requests go back to the builder for the next step.
  4. 4Requests that have finished leave with their replies.
Requests queue up. The builder hands one batch to the GPU, and after each step it refills the room from the queue. A finished reply leaves at once, so a short reply does not hold its slot until the longest reply ends.

What limits how big a batch can be?

Memory comes first. Each request keeps a KV cache, and that cache grows with every token the request writes. The vLLM team's paper on its serving system explains why this limits the batch:

  • “However, existing systems struggle because the key-value cache (KV cache) memory for each request is huge and grows and shrinks dynamically.”

    vLLM paper, PagedAttention (2023)

There are two ways to protect that memory. The safe way reserves each request's worst case, the full prompt plus the longest reply it may write. Memory then never runs out, as long as the server caps reply length, but fewer requests fit. The other way admits requests more freely and copes when memory runs short. vLLM's guide says that in such cases it can pause requests to free up KV cache space, and recompute them later. For a claims assistant I would start with the safe way. vLLM's optimisation guide also warns about setting the KV cache size by hand: a conservative value caps how many requests run together, and an optimistic one fails when memory is allocated.

The second limit is a cap on requests per step. The third is a wait limit. NVIDIA's Triton server has a dynamic batcher that combines inference requests into one batch. By default it creates batches as large as possible and does not delay. It holds a batch only while no request has waited past a delay you set. In our token loop design, that wait only matters while the GPU is idle.

Three limits decide each batch

Queue of requests

a 3,400-token job sits among chats

Builder checks

KV memory budget

the cache must still fit

Max requests per step

a fixed cap on the batch

Max wait time

an idle GPU holds none past it

Run the batch now

full, memory-blocked or someone late

Wait to fill the batch

only while the GPU is idle

  1. 1Requests line up, long and short mixed together.
  2. 2A full or memory-blocked batch, or a late request, sends it now.
  3. 3With the GPU idle, room left and nobody late, it waits a moment.
Before each step, the builder checks memory, the request cap and the wait time. A full or memory-blocked batch, or a late request, sends it now. With the GPU idle, room left and nobody late, the builder waits a moment for more requests.

A worked example with made-up numbers: the assistant's cache holds 4,000 tokens, it runs at most 4 requests per step, and no one waits past 20 ms. Five requests are queued. chat-1 needs 1,100 tokens in the worst case, claim-2 needs 2,000, chat-3 needs 500, contract-4 needs 3,400 and chat-5 needs 550.

Python
# A made-up batch builder for one GPU. Token counts are made-up numbers.
KV_BUDGET = 4000  # tokens of KV cache the GPU memory can hold
MAX_BATCH = 4     # most requests in one step
MAX_WAIT_MS = 20  # longest a request may wait to join a batch

QUEUE = [  # id, prompt tokens, reply tokens reserved, ms waited
    ("chat-1", 800, 300, 35),
    ("claim-2", 1500, 500, 5),
    ("chat-3", 300, 200, 0),
    ("contract-4", 2600, 800, 12),
    ("chat-5", 400, 150, 2),
]

def plan_batch(queue):
    batch, used, waiting = [], 0, []
    for rid, prompt, reply, _ in queue:
        need = prompt + reply  # worst case: full prompt plus full reply
        if len(batch) < MAX_BATCH and used + need <= KV_BUDGET:
            batch.append(rid)
            used += need
        else:
            waiting.append(rid)
    late = max(item[3] for item in queue) >= MAX_WAIT_MS
    decision = "run now" if waiting or late else "wait for more"
    return batch, waiting, used, decision
batch, waiting, used, decision = plan_batch(QUEUE)
print("in batch:", ", ".join(batch))
print("waiting:", ", ".join(waiting))
print(f"KV used: {used} of {KV_BUDGET} tokens")
print("decision:", decision)

Output

in batch: chat-1, claim-2, chat-3
waiting: contract-4, chat-5
KV used: 3600 of 4000 tokens
decision: run now

The GPU is idle, so the builder is forming its first batch. The first three fit in 3,600 tokens. contract-4 would push the total to 7,000, and chat-5 to 4,150, so both wait. The oldest request has waited 35 ms, past the 20 ms limit, so the batch starts now.

How do you trade speed for throughput?

  • Push up

    Bigger batch, longer wait

    More work each second, and the GPU stays busier. Each user waits a little longer, and memory is tighter.

  • Keep down

    Small batch, short wait

    Each user gets a quick start, but the GPU often runs with empty slots, so each reply tends to cost more to serve.

The hard part is the long prompt. Reading a 2,600-token contract in one step holds the GPU, and every chat user sharing it waits. vLLM's guide describes the fix, called chunked prefill.

Chunked prefill splits the big read into pieces and mixes each piece with the decode steps of other users. The guide says the scheduler, the part that picks each step's work, favours decode requests. When the step's token budget has room left, the pending read fills it. In vLLM V1, chunked prefill is on by default whenever possible.

Tip

Say which steps go first. In vLLM the chat users' decode requests are scheduled first, so the long read only uses the room that is left.

When memory runs short, vLLM can pause requests and recompute them later. Its guide warns that this can hurt end-to-end latency, so the memory budget should leave room for spikes.

Measure before you tune. Triton's guide suggests measuring latency and throughput with the default setup first, then raising the delay in steps until the latency budget is exceeded.

How would you set limits for a live support chat?

Start from the promise to the user. Suppose the made-up target is that the first word appears within one second for most chats. Then I work back from it.

  1. 1

    Keep the wait limit small

    A few milliseconds, and only while the GPU is idle, so no chat waits long for a batch to fill.

  2. 2

    Split the long reads

    Contracts and claim files are read in pieces, so decode steps keep running.

  3. 3

    Admit only what fits

    Check the worst case against the cache budget, with room left for spikes.

  4. 4

    Watch the numbers

    Track time to first token and the share of chats over target. If that share climbs, lower the cap.

What does the interviewer want to hear?

A strong answer covers

  • A plain loop: a queue, a batch builder, one step, finished replies leave.
  • The three limits: cache memory, request count and wait time.
  • Why the cache is the hard limit, and that worst cases must fit.
  • Long prompts stall chat users unless the read is split.
  • The trade-off stated in latency and throughput, with numbers you measured.
  • Time to first token (TTFT) and steady speed as the numbers to watch.

Common traps

  • Trap"Bigger batches are always faster."

    BetterBigger batches raise throughput, but they can push memory over budget and make each user wait longer.

  • Trap"Set the wait to zero and forget it."

    BetterA wait only matters while the GPU is idle. Set it from your latency target, then measure the result.

  • Trap"The model fits on the GPU, so we are fine."

    BetterThe weights fit, but each live request's cache grows. Plan the budget for the worst case.

Can you spot the risky design?

Spot the risk

A teammate's batcher design is up for review. Which line is the risky one?

Quick check

Chat replies slow down whenever someone uploads a long document. Which change helps most?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q314Static vs continuous batching?12 min
  2. Q316TTFT vs tokens/sec vs total latency?12 min
  3. Q317The latency vs throughput trade-off?10 min
  4. Q335What is prefill/decode disaggregation?11 min
  5. Q344What is a p95/p99 latency budget?11 min
  6. Q055What is the KV cache, and why does it speed up generation?12 min

Learn it in depth

Last updated on 27 November 2026

Building a model server that has to be fast and affordable?

I design and build AI products and agents, including the UI and the system behind them. Book a short call and tell me your traffic, your latency target and the hardware you have.