Continuous Batching

A language model generates its answer one token at a time. Each forward pass over the model, called an iteration or decode step, produces one new token for every request currently being served, and a request needs as many iterations as its answer has tokens. Nobody knows that count in advance, so one request in a batch may finish after 8 tokens and another after 400.

Static batching keeps batch membership fixed until every member has finished before admitting new work. Results may still be streamed or returned as individual requests finish; the example below assumes that all results are returned together at the batch boundary. Continuous batching makes the scheduling decision after every iteration instead: finished requests are removed and their results returned immediately, and waiting requests take the freed slots. The Orca paper (Yu et al., OSDI 2022) called this iteration-level scheduling, and the term continuous batching is now used for the same idea in serving engines. The batch has no fixed boundary, because its membership can change at each step.

A traced example

The trace below uses two slots and four requests that need 3, 6, 2, and 2 output tokens, all waiting before the first iteration. Each iteration is one time unit and emits one token per active request. This is a scheduling toy, not a measurement of any engine. Environment: Python 3.12 on macOS (Darwin 25.6).

# One iteration = one forward pass that emits one token for every active request.
reqs = {"A": 3, "B": 6, "C": 2, "D": 2}     # output tokens each request needs; all arrive before iteration 1
SLOTS = 2

def static(reqs):
    waiting, t, done, rows = list(reqs), 0, {}, []
    while waiting:
        batch = [waiting.pop(0) for _ in range(min(SLOTS, len(waiting)))]
        for _ in range(max(reqs[r] for r in batch)):
            t += 1
            rows.append((t, list(batch)))
        for r in batch: done[r] = t           # results returned when the whole batch ends
    return rows, done

def continuous(reqs):
    waiting, active, left, t, done, rows = list(reqs), [], dict(reqs), 0, {}, []
    while waiting or active:
        while waiting and len(active) < SLOTS: active.append(waiting.pop(0))   # admit at the iteration boundary
        t += 1
        rows.append((t, list(active)))
        for r in list(active):
            left[r] -= 1
            if left[r] == 0: active.remove(r); done[r] = t                     # return at once, free the slot
    return rows, done

for name, f in (("static", static), ("continuous", continuous)):
    rows, done = f(reqs)
    print(name)
    for t, act in rows: print(f"  iteration {t}: {' '.join(act)}")
    n = rows[-1][0]
    print(f"  finished at iteration: {done}")
    print(f"  {n} iterations, {sum(reqs.values())} useful tokens in {SLOTS*n} slot-iterations ({sum(reqs.values())/(SLOTS*n):.0%})")
static
  iteration 1: A B
  iteration 2: A B
  iteration 3: A B
  iteration 4: A B
  iteration 5: A B
  iteration 6: A B
  iteration 7: C D
  iteration 8: C D
  finished at iteration: {'A': 6, 'B': 6, 'C': 8, 'D': 8}
  8 iterations, 13 useful tokens in 16 slot-iterations (81%)
continuous
  iteration 1: A B
  iteration 2: A B
  iteration 3: A B
  iteration 4: B C
  iteration 5: B C
  iteration 6: B D
  iteration 7: D
  finished at iteration: {'A': 3, 'C': 5, 'B': 6, 'D': 7}
  7 iterations, 13 useful tokens in 14 slot-iterations (93%)

Under the example’s static batching and batch-level return policy, request A needs only 3 iterations but holds its slot until B finishes at iteration 6, and its result is not returned until then. C and D cannot start until the first batch is done, so they finish at iteration 8. Under continuous batching A returns at iteration 3, C takes its slot immediately and finishes at 5, and D enters at iteration 6 through the slot C freed at the end of iteration 5, while B is still active. The same work takes 7 iterations instead of 8, and 93 percent of the occupied slot-time produces a useful token instead of 81 percent. Short requests also see their results sooner, which matters for interactive use.

What limits the batch in practice

The toy treats slots as free. In a real engine each active request holds a key-value (KV) cache, the stored attention state for every token so far, and that cache grows by one entry per generated token. The number of requests that can run together is bounded by accelerator memory rather than by a fixed slot count, so the scheduler admits a request only if its cache can be accommodated, and it has to decide what to do when memory runs out mid-generation. A new request also needs its prompt processed before it can generate, and that work is heavier than a decode step; scheduling it into an iteration that other requests share delays their next token. Engines differ in how they balance these, and the balance shows up as time to first token and inter-token latency rather than as throughput alone.

Continuous batching differs from the dynamic batching used for models with a fixed cost per request. There a server holds requests briefly to fill a batch and runs it once. For token-by-token generation, the unit of joining is the iteration, so a request does not wait for a batching window; it waits only for a free slot and available memory.

References


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.