Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 90/ 160
05. AI System Design

Continuous Batching

Dynamically add/remove requests mid-decode to keep GPUs saturated.

AdvancedDynamic Batch · GPU Saturation3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The server doesn't wait for everyone in a group to finish; as soon as one answer is done, it starts a new request in that spot so the GPU is never idle.

Think of it like…

A restaurant that seats a new party the moment any table frees up, instead of seating groups in waves and waiting for the slowest table in each wave to finish.

Where you’ve seen it

Four requests in a static batch need 20, 40, 80 and 400 output tokens. The batch runs 400 steps because the longest request sets the length, but only 20 + 40 + 80 + 400 = 540 of the 4 × 400 = 1,600 slot-steps do useful work: 33.8% utilisation. At a 20 ms step time a new request that arrives just after the batch starts waits up to 400 × 20 ms = 8.0 s before it can even begin. With continuous batching, the 20-token request frees its slot after 20 steps (0.4 s) and the next queued request takes it immediately; the 40- and 80-token requests do likewise, so slots stay almost fully used and the new arrival waits at most one step (20 ms) plus its prefill. The scheduler also caps tokens per step at 2,048 with chunked prefill, so a 3,100-token prompt is processed in two chunks mixed with ongoing decodes rather than stalling every running stream for 0.39 s.

Words you’ll hear

Iteration-level scheduling
Re-deciding the batch composition at every decoding step.
Static batching
Processing a fixed group of requests until all of them are finished.
Chunked prefill
Splitting a long prompt's prefill into pieces that share steps with decoding.
Preemption
Pausing or evicting a running sequence (and recomputing or swapping its KV cache) when memory runs out.

Visual diagram

Loading interactive diagram

Theory & deep dive

From static to continuous batching

A generative request is a sequence of steps: one prefill pass followed by one decode step per output token, with an unknown number of steps because the model decides when to stop. In static batching, requests are grouped and padded, and the group runs until every member finishes; short requests idle (their slots produce padding), and new requests wait for the next batch, so utilisation and TTFT both suffer when lengths vary. The Orca paper introduced iteration-level scheduling: after every decode step the scheduler removes finished sequences, admits waiting ones and runs the next step on the updated set, so each step uses all available slots.

Because attention needs each sequence's own KV cache, continuous batching depends on flexible KV memory, which is what PagedAttention provides: new sequences can be started and finished without reshuffling large contiguous buffers. The scheduler maintains running and waiting queues and admits a waiting request only when enough free KV blocks exist for its prompt (and some decode headroom). If memory runs out mid-generation, it preempts a running sequence: either swapping its blocks to CPU memory or dropping them and recomputing later, which hurts that request's latency but keeps the system alive.

Utilisation arithmetic

Static batch of four with lengths 20, 40, 80, 400: useful slot-steps = 540; total slot-steps = 4 × 400 = 1,600; utilisation = 540/1,600 = 33.8%. With continuous batching and enough queued work, each freed slot is refilled within a step, pushing utilisation toward 90% or more.

Key takeaway: Per-step scheduling removes padding waste and queue delay; paged KV memory makes it practical.

Prefill interference, fairness and tuning

Prefill is compute-heavy and decode is memory-bound, and running a long prefill in one step can stall every running sequence's next token, creating latency spikes (a 3,100-token prefill is about 0.39 s on a large model). Chunked prefill limits the tokens processed per step (for example max_num_batched_tokens = 2,048): long prompts are processed over several steps mixed with ongoing decodes, which smooths inter-token latency at the price of slightly higher TTFT for the long prompt. Some systems go further and disaggregate prefill and decode onto separate GPU pools so each phase can be tuned and scaled independently, transferring the KV cache between them.

Scheduler policy matters for fairness and priority. First-come-first-served is simple but lets a flood of long requests starve short ones; priority classes let interactive chat preempt batch jobs; per-tenant limits prevent one customer from monopolising slots. Key knobs are the maximum number of concurrent sequences, the token budget per step, queue length and timeouts, and the preemption mode. Monitor running and waiting counts, KV-cache utilisation, preemption rate (high rates signal memory pressure), TTFT, inter-token latency and the distribution of prompt and output lengths. Continuous batching doesn't remove the throughput-latency trade-off; it moves the whole curve up by eliminating waste.

Chunked prefill

A 3,100-token prompt arrives while 30 streams are decoding. Unchunked, prefill takes about 0.39 s in a single step and every stream stalls for that time. With a 2,048-token budget, the prompt takes two steps (2,048 then 1,052 tokens), each shared with decoding, so no stream stalls longer than about 0.26 s and the new request's TTFT rises only a little.

Key takeaway: Chunk long prefills, use priorities for fairness and watch preemptions as the sign of memory pressure.

How it works, step by step

Step 1 of 4
Scheduler

1. Accept requests into queues

Place new requests in the waiting queue with priority and tenant information.

waiting queue + priority classes
Key numbers at this step
Limits
per tenant

When to use it & trade-offs

What it is

Continuous batching (also called iteration-level or in-flight batching) lets an LLM server change its batch at every decoding step: sequences that finish leave immediately, and waiting requests join as soon as there is capacity. This contrasts with static batching, where a fixed group of requests is processed together until the *longest* one finishes, leaving the GPU partly idle and making new arrivals wait for the whole batch. Combined with chunked prefill (splitting long prompts so they don't block decoding) and a scheduler with priorities and memory-aware admission, it keeps GPUs saturated and TTFT low for mixed-length traffic.

Why it matters: Output lengths vary enormously (a yes/no answer versus a 1,000-token essay), so static batches waste compute and add large queue delays. Continuous batching is the main reason modern servers (vLLM, TGI, TensorRT-LLM, SGLang) achieve multiples of the throughput of naive serving. Knowing how it works explains why throughput scales with load, why a very long prompt can still hurt other users' latency and what scheduler settings control fairness.

When to reach for it

  • Interactive chat and API serving
  • Mixed-length workloads
  • Raising GPU utilisation without adding hardware

When to avoid or be careful

  • Static batching for variable-length traffic
  • Unlimited prefill tokens per step
  • First-come-first-served only when tenants differ greatly

Batching strategies

Continuous batching
Best for: Online serving with variable lengths

Strengths: High utilisation; low queue delay.

Watch out: Needs flexible KV memory and a smarter scheduler.

Static batching
Best for: Simple offline jobs with similar lengths

Strengths: Easy to implement.

Watch out: Padding waste and long waits under varied lengths.

Disaggregated prefill and decode
Best for: Very large deployments with strict latency SLOs

Strengths: Independent tuning and scaling of each phase.

Watch out: KV transfer cost and operational complexity.

Interview signals & numbers to know

When this topic comes up

  • “New requests wait for the whole batch”
  • “GPU utilisation is low”
  • Iteration-level scheduling
  • Chunked prefill
  • Preemption rate

Benchmarks & rules of thumb

540 / 1,600 = 33.8% -
utilisation of the static batch example
8.0 s -
worst-case wait of a new request behind a 400-step batch at 20 ms
2,048 -
example token budget per step for chunked prefill

Common mistakes & follow-ups

Common interview mistakes

  • Letting very long prompts block decode for every running stream.
  • Ignoring preemption metrics and wondering why latency spikes.
  • Assuming continuous batching removes the throughput-latency trade-off.

Likely interviewer follow-ups

  • How does continuous batching differ from static batching?
  • Why is chunked prefill useful?
  • What happens when GPU memory fills up during generation?
Interview tip: Give the 540 out of 1,600 utilisation example. It makes the waste of static batching concrete in one line.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Continuous Batching with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Inference Serving with vLLM
Next topic
PagedAttention