SysDesignAtlas

Inference Engines & Continuous Batching

The scheduler at the heart of every LLM server — why static batching wastes most of a GPU, how iteration-level scheduling fixes it, and the prefill/decode interference nobody warns you about.

HLDHard12 min readaiinferencebatchingscheduling
Confidence

#What an inference engine does

Between your HTTP handler and the GPU sits a scheduler making one decision, thousands of times a second: which requests run in the next forward pass?

That decision determines throughput, latency, and cost. Everything else in an inference engine — the kernels, the memory allocator, the API surface — supports it.

#Why static batching fails

The obvious approach: collect N requests, run them together, return when all are done.

   STATIC BATCHING

   req A ████████████████████████ 500 output tokens
   req B ███░░░░░░░░░░░░░░░░░░░░░  20 tokens, then IDLE
   req C ████░░░░░░░░░░░░░░░░░░░░  30 tokens, then IDLE
   req D ██░░░░░░░░░░░░░░░░░░░░░░  15 tokens, then IDLE
                                   ░ = wasted slot

   The batch runs until the SLOWEST member finishes.
   Generation lengths vary by 10-50× in real traffic.

   → In this batch, ~70% of the slot-time is idle.

Two compounding problems: finished requests hold their slot doing nothing, and new arrivals wait for the whole batch to drain before they can start. Both get worse as length variance grows, and length variance in real chat traffic is enormous.

#Continuous batching

The fix is to schedule at the iteration level rather than the request level.

   CONTINUOUS BATCHING (in-flight batching)

   After EVERY decode step:
     · evict any request that emitted its stop token
     · admit a waiting request into the freed slot
     · run the next step on whatever is currently resident

   req A ████████████████████████
   req B ███▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓   B finishes → E admitted here
   req C ████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓   C finishes → F admitted
   req D ██▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
                                   ▓ = a different request

   → the batch stays full; no slot idles

This works because of a property established in inference arithmetic: each decode step is an independent forward pass over the current batch. There is no requirement that the batch membership stay constant between steps — the weights are read once regardless, and the batch dimension is just how many token vectors they multiply against.

Reported throughput improvements are typically 2–4× over static batching, sometimes far more with high length variance. It is the single highest-impact technique in LLM serving, and it costs nothing but scheduler complexity.

#Prefill/decode interference

The subtlety that makes real schedulers complicated.

Prefill is the first phase of a request: the model reads the whole prompt in one pass, processing every position at once, which makes it compute-bound. Decode is everything after: generating one token per step, which is memory-bound. Both run in the same forward pass, so if a step includes a large prefill, every ongoing decode in that step has to wait for the prefill to finish.

   A request with a 32,000-token prompt is admitted.

   Its prefill takes ~2 seconds of GPU time.

   Meanwhile 60 users mid-conversation are streaming at
   one token every 8 ms.

   → all 60 streams STALL for 2 seconds.
     Every one of them sees a visible stutter because
     somebody else pasted a long document.

Chunked prefill is the standard fix: split a long prefill into chunks of, say, 512 tokens, and interleave them with decode steps.

   WITHOUT CHUNKING          WITH CHUNKING

   [────── prefill ──────]   [pf][d][pf][d][pf][d][pf][d]
   [d][d][d][d][d][d]

   decode stalls 2 s          each decode step delayed by
                              one chunk's worth (~30 ms)
                              prefill takes slightly longer
                              overall, nobody stutters

This is the same idea as spreading a database checkpoint over its interval rather than storming the disk: convert one large disruptive operation into many small ones with bounded impact.

Disaggregation takes it further — run prefill and decode on different GPU pools, transferring the KV cache between them. Each pool can then be sized, batched, and even hardware-matched for its own characteristics. It costs a KV cache transfer over the interconnect and is developed further in KV cache management.

#Disaggregation became the default at scale

By 2025–26, large deployments routinely split serving into separate roles:

   router ──► prefill pool    compute-heavy; big batches of prompt tokens
     │            │
     │            │  KV cache shipped over NVLink / RDMA
     │            ▼
     └──────► decode pool     bandwidth-heavy; many concurrent streams

Open-source orchestration layers above the engines — NVIDIA Dynamo, and the Kubernetes-native llm-d, accepted into the CNCF in 2026 — supply the pieces:

  • a KV-aware router that sends each request to a replica already holding its prefix in cache. If a conversation's earlier turns (or a shared system prompt) are already cached on replica 3, sending the next turn there skips recomputing them;
  • a transfer library (NVIDIA's NIXL) that moves KV blocks between GPUs and storage tiers;
  • independent scaling of the prefill and decode pools.

The ratio of prefill to decode GPUs becomes a tuning knob set by your traffic: long prompts with short answers need more prefill capacity, chatty generation needs more decode. Research systems push the split further, putting MoE models' attention and expert layers on different GPUs.

The trade is a KV transfer per request — hundreds of megabytes for a long prompt — and more moving parts. For one node or modest traffic, chunked prefill on shared GPUs is still the simpler answer.

Reasoning models push the mix further toward decode — thousands of output tokens per request — which changes the pool ratio, admission and timeouts; see serving reasoning models.

#The scheduler's decisions

Every iteration, the scheduler must decide:

DecisionConsiderations
Admit a waiting request?Is there KV cache for its prompt plus expected generation? Would admitting it starve running requests?
How much prefill this step?Doing more of a new prompt at once gets that user their first token sooner (TTFT — time to first token), but stalls everyone already streaming
Preempt anyone?Under memory pressure: evict a request's KV and re-prefill later, or swap it to host memory
Which waiting request first?FIFO, shortest-first, priority class, or deadline
Stop this request?Stop token, max length, client disconnect, or budget exceeded

#Preemption

Requests grow as they generate — each new token adds to that request's KV cache. So a batch that fitted comfortably when admitted can run the GPU out of memory mid-flight, with no request having done anything wrong. Preemption is evicting a partly-finished request to make room, and there are two ways to do it.

   Option 1 — RECOMPUTE
     drop the request's KV blocks entirely
     when resumed, re-prefill its whole context
     cost: one full prefill (expensive for long contexts)
     benefit: frees memory immediately, no transfer

   Option 2 — SWAP
     copy KV blocks to host memory over PCIe
     copy back on resume
     cost: 2 × transfer over ~64 GB/s PCIe
     benefit: no recomputation

   Crossover: swapping wins when the context is long enough
   that re-prefill costs more than 2× the PCIe transfer.
   For short contexts, recompute is cheaper.

   Option 3 — DON'T GET HERE
     admission control that keeps a memory reserve

The third is the real answer. Preemption is a safety valve, and a system that preempts regularly is a system whose admission control is too loose.

#Scheduling policy and fairness

FCFS is the default and is vulnerable to head-of-line blocking — a 100K-token prompt at the front delays everyone behind it.

Shortest-job-first minimises average waiting time (a classic result), but you don't know job length in advance and long requests can starve.

Priority lanes are what production systems actually do: separate interactive traffic from batch, give interactive smaller batches and admission preference, and let batch traffic run at large batch sizes in the leftover capacity. This resolves the throughput/TTFT tension by refusing to pick one — the same reasoning as separating fast and slow endpoints to reduce queueing variance.

Fairness across tenants needs explicit accounting. A single user submitting a thousand long requests will consume the whole batch under FCFS. Per-tenant token budgets with weighted fair queueing is the standard answer. The unit must be tokens rather than requests, because one 100K-token request costs as much GPU time as hundreds of short ones.

#What to measure

MetricMeaningWatch for
TTFTTime to first tokenDominated by queue wait under load, not prefill
TPOTTime per output tokenShould be stable; spikes mean interference
ThroughputTotal tokens/s across all usersYour cost denominator
GoodputTokens/s meeting SLAThe honest number
KV cache utilisationFraction of cache in useThe real capacity signal
Preemption rateRequests evicted per minuteAbove ~0 means admission is too loose
Queue depth and waitRequests waiting, and for how longWait time is the actionable one

#The engines

EngineEmphasis
vLLMPagedAttention, continuous batching, broad model support. The common default
TensorRT-LLMCompiled kernels, lowest latency on NVIDIA hardware, heavier build step
SGLangRadixAttention for aggressive prefix caching (reusing the KV cache of any prompt start already seen); strong on structured and multi-turn workloads
TGIHugging Face's server; good ergonomics and ecosystem integration
llama.cppCPU and consumer GPU, aggressive quantization, local deployment
Dynamo / llm-dNot engines but the layer above them: disaggregated prefill/decode, KV-aware routing, KV transfer between pools

They differ far less than they used to — every serious engine now has continuous batching and paged KV cache. Current differentiation is in prefix caching sophistication, quantization support, structured output, and how well the scheduler handles mixed workloads.

#Check yourself

Why does static batching waste the GPU?Show answer
The batch runs until its slowest member finishes; output lengths vary 10–50×, so finished requests idle in their slots and new arrivals wait for the batch to drain.
What is continuous batching?Show answer
Iteration-level scheduling: after every decode step, evict finished requests and admit waiting ones, so the batch stays full — typically 2–4× throughput.
Why doesn't adding a request slow the others in decode?Show answer
Step time is set by reading the weights once; extra token vectors cost almost nothing until compute or KV memory saturates. So batch as much as memory allows.
What is prefill/decode interference, and its fixes?Show answer
A long prefill in the same step stalls every streaming decode (a 32K prompt ≈ 2 s). Chunked prefill interleaves ~512-token chunks with decode steps; disaggregation moves prefill to a separate pool.
What does disaggregated serving add?Show answer
Separate prefill and decode pools linked by KV-cache transfer, a KV-aware router, and independent scaling with a prefill:decode ratio tuned to your traffic (Dynamo, llm-d).
How does admission work without knowing output length?Show answer
Optimistic admission with preemption (best throughput), conservative reservation for max_tokens (underutilised), or prediction. Most engines are optimistic; honest max_tokens helps.
Recompute or swap when preempting?Show answer
Recompute drops KV and re-prefills later (cheap for short contexts); swap copies KV to host memory over PCIe (better for long contexts). Regular preemption means admission is too loose.
Which scheduling policies resolve fairness and the TTFT tension?Show answer
Priority lanes — interactive with small batches and admission preference, batch traffic in leftover capacity — plus per-tenant token budgets with weighted fair queueing.

#What to carry forward

  • Static batching wastes most of the GPU because generation lengths vary 10–50×.
  • Continuous batching schedules per iteration — evict and admit after every decode step. 2–4× throughput for free.
  • Adding to the batch doesn't slow the others — batch until memory runs out.
  • Prefill stalls decode. Chunked prefill bounds the damage; disaggregation eliminates it.
  • Admission control needs an output-length estimate you don't have. Be optimistic and preempt, or require honest max_tokens.
  • Priority lanes, not one setting, resolve the TTFT/throughput tension.
  • Measure goodput, not throughput. GPU capacity cannot be autoscaled reactively.
00:00
/ 12m