Continuous batching lets queued LLM requests start before earlier requests finish. After each model pass, the scheduler removes finished requests and admits new work - but only when token, active-sequence and KV-cache limits allow it.
Unlike fixed batching, the request group can change between passes. Decode usually generates one token per active sequence per pass; prompt processing, called prefill, can run in chunks alongside it.
The scheduling loop needs to:
- Track request state and release cache memory safely after completion or cancellation.
- Share capacity between prefill and decode without leaving requests waiting indefinitely.
- Limit queue growth and handle shutdown.
- Test mixed workloads and measure throughput alongside time to first token, gaps between tokens and p95/p99 latency.
The aim is more useful work per pass - not higher GPU utilisation at the cost of longer waits.
Continuous Batching and LLM Scheduling: Algorithmic Foundations Explained | Uplatz
How requests join and leave each iteration
::: @figure
{How Continuous Batching Schedules LLM Requests}
:::
With request state tracked, the scheduler checks the queue again at each iteration boundary.
A request moves through queued → admitted → prefilling → decoding → completed, unless cancellation or an error ends it sooner.[1][4][5] This keeps the batch moving without waiting for every request to finish. Requests join or leave only between GPU passes, once the current iteration ends.[1][7][4]
Admit requests within token and memory limits
Use FIFO as the baseline: admit the oldest queued request only when active-sequence, token-budget and KV-cache limits allow it. Count the prompt or prefill chunk scheduled for this pass, plus expected cache growth during generation.[1][4][8]
The token budget limits work per pass; KV-cache capacity limits how many requests can remain active.[4][3][5] Prefill and decode can share a pass. Split long prompts into chunks when they would crowd out decode work.[1][4][6]
Remove finished requests and free capacity
At each boundary, check for end-of-sequence tokens, stop conditions, output limits, cancellations, deadline expiry and errors. Mark affected requests as terminal, remove them from the next batch and release their private KV-cache blocks.[1][4][7]
If cancellation arrives during a GPU pass, flag it and wait until the pass ends to clean up. Make cleanup safe to run twice, so cancellation and completion cannot free the same blocks twice. Keep shared prefix-cache blocks under the cache policy.[1][4][7]
Trace batch changes across iterations
The same boundary rule applies when a batch mixes prefill and decode work.
Example:
Scheduling point Decode work Prefill and membership changes Iteration 1 A and B each produce one token C remains queued Boundary 1 A’s end-of-sequence token marks it completed Release A’s private cache blocks; admit C Iteration 2 B continues decoding C processes its prompt in prefill Iteration 3 B and C decode C uses its own prepared KV cache
C joins the next batch rather than replacing A mid-pass. It can start before B finishes.[1][4][7]
Compare continuous and fixed request batching
With join-and-leave rules defined, the next step is to compare continuous batching with a fixed batch.
Fixed batching keeps the same request group until every member finishes. Individual requests can return results early, but that does not change the batch.[11][13]
| Dimension | Fixed request batching | Continuous token batching |
|---|---|---|
| Scheduling unit | The whole request batch; all members advance together. | Each decode iteration or token step; the batch can change after each token. |
| When requests join and leave | Results can return individually, but replacements wait until the batch ends. | Finished requests leave at the next boundary; queued requests join if capacity allows. |
| GPU utilisation | Uneven output lengths leave unused slots or padding while longer requests continue. | Refilling free capacity keeps more useful work active when requests are queued. |
| Latency behaviour | New arrivals wait for the current batch to finish. | Queue wait can fall, but a larger token budget per iteration can increase inter-token latency. |
| Implementation complexity | Simpler batch formation, masking and completion handling. | Needs per-request state, KV-cache accounting, admission control and fairness or starvation protection. |
Use fixed batching for offline workloads with similar request lengths. Choose continuous batching when lengths vary and new work keeps arriving.[10][12][11][15]
Weigh throughput gains against latency
Refilling capacity can increase useful output tokens per second. But higher throughput does not guarantee faster responses.[13] Queue wait and gaps between streamed tokens can grow when prefill competes with decode.[13]
When demand is low, the queue may not contain enough requests to refill every slot.[15]
For interactive workloads, set time to first token and p95/p99 latency limits before increasing admission budgets. Measure output tokens per second alongside queue wait, inter-token latency and completion latency. Accept a throughput gain only if those response targets still hold: GPU utilisation alone cannot tell you whether users are waiting too long.[5][13][14]
These trade-offs shape the admission and cleanup rules in the batching loop.
Build the continuous batching loop
The loop turns the join-and-leave rules into decisions at each forward pass, admitting new requests only between passes.[16][17][18]
# Implements boundary-based admission, completion and cleanup
while accepting_requests or waiting_queue not empty or active_set not empty:
if shutdown_requested:
stop_accepting_new_requests()
if accepting_requests:
ingest_new_requests()
remove_cancelled_requests(waiting_queue)
cleanup_active_requests(active_set)
available = capacity_limits(
token_budget,
active_sequences,
kv_cache_free_blocks
)
# Admit new work only between passes
while waiting_queue has requests:
request = peek_next_by_policy(waiting_queue)
if not fits_token_and_memory_limits(request, available):
break
admit(request)
allocate_kv_cache(request)
move request to active_set
prefill_work = choose_prefill(active_set, available)
decode_work = choose_decode(active_set, available)
outputs = model_forward(prefill_work, decode_work)
for request, output in outputs:
update_prompt_position(request, output)
append_generated_tokens(request, output)
update_kv_cache_accounting(request)
if hit_stop_token(request) or hit_length_limit(request):
request.finished = true
cleanup_active_requests(active_set)
if shutdown_requested:
apply_drain_or_terminate_policy()
cleanup_active_requests releases private KV-cache allocations, sends results or cancellation notices and removes requests in a terminal state. Make it safe to run twice.[16][17][18]
Track request state and per-pass budgets
For each request, track its ID, queue priority, prompt position, generated-token count, output limit, stop rule, cancellation state, completion state and KV-cache allocation. Keep it in prefill until its prompt has been processed. It then enters decode, where each iteration usually produces one next-token step.[16][9]
Budget tokens, active sequences and KV-cache memory separately. Set explicit limits for total tokens per pass, prefill tokens and active sequences.[16][3] Check the cache needed for the selected prompt tokens and the expected growth from future generated tokens. Leave headroom for activations, temporary tensors and allocator overhead.[9]
Handle long prompts, queue limits and shutdown
Use chunked prefill to process long prompts in bounded pieces. Save the prompt position so processing can resume across passes. Interleave these chunks with decode work so one long prompt cannot monopolise the forward pass. Document whether decode takes priority, whether prefills get a minimum service share and how requests receive a fair share of processing time.[9]
Set limits on queued request count, queued prompt tokens, estimated cache demand and request age. When a limit is reached, follow an explicit policy: return a busy response, reject the request with retry guidance or time out the client. Don't let the queue keep growing.[9][16]
The next section checks these state changes and limits.
For shutdown, stop accepting new requests, then drain or terminate accepted work under a fixed policy. Complete accepted work within its deadline or terminate it, notify clients and release its allocations. Keep the loop running until all accepted work has completed or been terminated.[16][17][18]
Verify scheduling and review the results
Test mixed workloads and inspect iteration traces
Use the trace to check that admission and cleanup rules work as intended. Replay a workload with a fixed seed and mixed prompt and output lengths. Include arrivals during decoding, cancellations, end-of-sequence completions, output-limit completions and capacity deferrals.
For each iteration, log request state, batch membership, prefill-token and decode-token counts, active-sequence count, and allocated and free KV-cache blocks. Then compare what the scheduler admitted with what the hardware actually handled.
Check behaviour, not just throughput. Short requests should finish while longer ones continue. Each departure should release its cache allocation so waiting work can join at an iteration boundary when capacity allows [19].
Measure queue wait, TTFT, inter-token latency, end-to-end latency, request completions per second, generated tokens per second, and admission deferral count and duration. Define TTFT consistently from arrival. Report p50, p95 and p99 for TTFT, inter-token latency and end-to-end latency: averages can hide stalls [20][21].
Check bottlenecks before increasing limits
Read utilisation alongside the trace, not on its own. An empty queue suggests low demand. Waiting requests with unused token or KV-cache capacity suggest admission rules are too restrictive. Inter-token latency spikes during prefill suggest prefill/decode contention [19].
A growing queue with saturated resources suggests overload. Older requests repeatedly being overtaken suggests the scheduling policy isn't treating requests fairly. For out-of-memory errors, check KV-cache allocations, temporary buffers and allocator fragmentation before increasing limits [19].
Change one setting at a time, then replay the same workload on the same model and hardware, keeping latency targets unchanged. Compare iteration traces, throughput, tail latency and peak memory - not utilisation alone.
FAQs
Can strict FIFO scheduling delay shorter requests?
Yes. With strict First-In, First-Out (FIFO) scheduling, a short request behind a long-running batch job must wait until that job finishes. That wait increases the request’s latency [1].
To cut delays and prevent higher-priority or shorter tasks from being starved of processing time, use weighted priority queues, reserve capacity for critical work, or apply ageing to increase tasks’ effective priority the longer they wait [2].
What happens if an active request outgrows its KV-cache budget?
Token-aware scheduling reserves capacity as each request joins a batch, then tracks token demand against the shared budget. If an active request exceeds its reserved KV-cache budget, the system must trigger an overload response to protect the rest of the batch.
That may mean dropping or rejecting the request to prevent memory exhaustion, or enforcing strict task deadlines so one request cannot put the others at risk.
How do I balance throughput against streaming latency?
Treat latency as a hard limit for interactive LLM workloads. Prioritise p95 or p99 latency and time-to-first-token. Once you meet those limits, use continuous batching to increase throughput and GPU utilisation without a matching increase in costs.
Base autoscaling on queue depth, tail latency and tokens per second, not raw GPU utilisation. Keep a small reserved baseline and scale up aggressively when demand spikes. Use longer cooldowns - typically 5 minutes - to stop performance swinging back and forth.