Concept notebookChecking saved investigationReading browser-local route memory before showing a continuation.

LLM Serving at Scale: Prefill, Decode & Continuous Batching

A systems mental model for LLM inference: prefill vs decode, TTFT vs TPOT, batching/scheduling, and why KV cache memory dominates.

published · difficulty 4/5 · 22 min read

01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

Serving an LLM is not "run the model once." It's running the model for many users at once, while trying to keep latency low and the GPU busy.

Two phases dominate everything:

  • Prefill: process the prompt in parallel (big matrix multiplies, lots of compute).
  • Decode: generate one token at a time (small matmuls, but heavy KV cache reads).

This is why a system can feel fast on short prompts but collapse on long context: decode becomes memory-bandwidth bound, and the KV cache becomes the main resource you schedule around.

The practical goal is not raw throughput. It's goodput: how many requests you can serve while meeting latency SLOs.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

Latency decomposition (a serving mental model)

Let ToutT_{out}Tout be the number of generated tokens. A simple but useful decomposition is:

LatencyTTFTtime to first token+(Tout1)TPOTtime per output token.\text{Latency} \approx \underbrace{\text{TTFT}}_{\text{time to first token}} + (T_{out}-1)\cdot\underbrace{\text{TPOT}}_{\text{time per output token}}.Latencytime to first tokenTTFT+(Tout1)time per output tokenTPOT.
  • In this serving mental model, TTFT often tracks prefill.
  • TPOT often tracks decode (and KV cache reads).

KV cache memory scaling (why long prompts hurt)

Across a batch of BBB sequences and LLL layers, storing keys and values for TTT tokens costs roughly:

MemKVBLTHkvdhead2bytes.\mathrm{Mem}_{KV} \approx B\cdot L\cdot T\cdot H_{kv}\cdot d_{head}\cdot 2 \cdot \mathrm{bytes}.MemKVBLTHkvdhead2bytes.

The factor of 2 is for storing both KKK and VVV.

Goodput (a serving SLO mental model)

If you have SLO thresholds STTFT,STPOTS_{TTFT}, S_{TPOT}STTFT,STPOT, a common objective is:

Goodput=Throughput×Pr ⁣(TTFTSTTFTTPOTSTPOT).\text{Goodput} = \text{Throughput} \times \Pr\!\left(\text{TTFT} \le S_{TTFT} \wedge \text{TPOT} \le S_{TPOT}\right).Goodput=Throughput×Pr(TTFTSTTFTTPOTSTPOT).

This captures the reality that "fast on average" is not good enough if tail latency violates SLOs.

Paging / fragmentation waste

If KV memory is allocated in blocks/pages of size PPP (tokens per block), then for a sequence length TTT:

allocated(T)=TPP,waste(T)=allocated(T)T.\text{allocated}(T) = \left\lceil \frac{T}{P} \right\rceil P,\qquad \text{waste}(T) = \text{allocated}(T) - T.allocated(T)=PTP,waste(T)=allocated(T)T.

Block-based allocators (PagedAttention-style) make growth predictable and reduce fragmentation under continuous batching.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.
import numpy as np

def kv_gb(T, layers, h_kv, d_head, batch=1, bytes_per_elem=2):
    elems = batch * layers * T * h_kv * d_head * 2  # K and V
    return elems * bytes_per_elem / 1e9

def waste_tokens(T, P):
    return int(np.ceil(T / P) * P - T)

L, Hkv, dh, B = 80, 8, 128, 16  # example: 80 layers, GQA with 8 KV heads, fp16
for T in [2048, 8192, 32768, 131072]:
    print("T=", T, "KV~", round(kv_gb(T, L, Hkv, dh, batch=B), 2), "GB")

P = 256  # tokens per page/block
for T in [2000, 8192, 20000]:
    print("T=", T, "waste_tokens=", waste_tokens(T, P))
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

ManipulateChange one control and predict the visible response before reveal.Leave with the observed invariant or a repaired model.

Live Concept Demo

Explore LLM Serving at Scale: Prefill, Decode & Continuous Batching

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5undergraduatecode-aligned
Demo inquiry checkpoint

Manipulate one control and predict the visible change.

01Choose lensTrace a quantity
02ObserveDemo state pending
03GroundName the equation, invariant, or control that explains it.
04CarryNext: Speculative Decoding: Lossless Multi-Token Generation

Choose what to inspect in LLM Serving at Scale: Prefill, Decode & Continuous Batching. This shared fallback is an observation guide, not evidence of learning.

Loading interactive demo...

Use the demo to explore TTFT vs TPOT tradeoffs, how batching affects goodput, and how repeated KV cache reads shape decode latency in this toy lab.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

Concept: LLM Serving at Scale: Prefill, Decode & Continuous Batching

What is the smallest example that makes LLM Serving at Scale: Prefill, Decode & Continuous Batching click without losing the math?

BeforeScaled Dot-Product Attention & Transformer LayersNow4/4 sections readyTryManipulate one control and predict the visible change.NextSpeculative Decoding: Lossless Multi-Token Generation
Object contextLLM Systems
ConceptLearner lens

LLM Serving at Scale: Prefill, Decode & Continuous Batching

What is the smallest example that makes LLM Serving at Scale: Prefill, Decode & Continuous Batching click without losing the math?

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
Carry inScaled Dot-Product Attention & Transformer Layers

Bring the mental model from Scaled Dot-Product Attention & Transformer Layers; this page will reuse it instead of restarting from zero.

Work hereLLM Serving at Scale: Prefill, Decode & Continuous Batching

A systems mental model for LLM inference: prefill vs decode, TTFT vs TPOT, batching/scheduling, and why KV cache memory dominates.

Carry outSpeculative Decoding: Lossless Multi-Token Generation

The next edge should feel earned: use the demo prediction here before following Speculative Decoding: Lossless Multi-Token Generation.

After The First Pass

Turn the concept into an inspected object.

The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the research question.
ConceptLLM Serving at Scale: Prefill, Decode & Continuous BatchingLLM Systems

Mechanism Storyboard

See the idea move before the page explains it

A systems mental model for LLM inference: prefill vs decode, TTFT vs TPOT, batching/scheduling, and why KV cache memory dominates.

Demo notes open01 / Intuition
Editorial systems illustration of prefill, KV cache shelves, continuous batching lanes, and decode token streams.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change LLM Serving at Scale: Prefill, Decode & Continuous Batching should make visible.

Visual Inquiry

Make the image answer a mathematical question

A systems mental model for LLM inference: prefill vs decode, TTFT vs TPOT, batching/scheduling, and why KV cache memory dominates.

4/4 stages readyDemo notes connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make LLM Serving at Scale: Prefill, Decode & Continuous Batching easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

Object - ConceptLLM Serving at Scale: Prefill, Decode & Continuous BatchingQuestion

What is the smallest example that makes LLM Serving at Scale: Prefill, Decode & Continuous Batching click without losing the math?

concept:llm-systems/llm-serving
Boundary

sources: yu-2022-orca, kwon-2023-pagedattention

Check

Open the closest source note before trusting the local explanation.

Evidence

2 selected-object sources shown first; 2 references total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · paper · 2022Orca: A Distributed Serving System for Transformer-Based Generative ModelsYu et al.
Located CF editorial boundary

Primary serving-scheduler source. Orca frames generative transformer inference as multi-iteration autoregressive serving, where each iteration generates one output token, and proposes iteration-level scheduling plus selective batching.

Used here as

Orca supports the scheduling part: generative Transformer serving is multi-iteration autoregressive inference with one output token per iteration, and fixed request-level batches motivate...

Caveat

Checks the serving mechanism only. TTFT/TPOT, goodput, KV formula, code, and demo are toy witnesses, not source-derived formulas or production benchmarks. Does not certify vendor latency,...

Open source
selected object source · paper · 2023Efficient Memory Management for Large Language Model Serving with PagedAttentionKwon et al.
Located CF editorial boundary

Primary KV-cache serving source. PagedAttention frames high-throughput LLM serving as constrained by huge dynamically growing KV caches, fragmentation, batch-size limits, and paged block allocation.

Used here as

Orca supports the scheduling part: generative Transformer serving is multi-iteration autoregressive inference with one output token per iteration, and fixed request-level batches motivate...

Caveat

Checks the serving mechanism only. TTFT/TPOT, goodput, KV formula, code, and demo are toy witnesses, not source-derived formulas or production benchmarks. Does not certify vendor latency,...

Open source

Claim Review

A systems mental model for LLM inference: prefill vs decode, TTFT vs TPOT, batching/scheduling, and why KV cache memory dominates.

Object - ConceptLLM Serving at Scale: Prefill, Decode & Continuous BatchingQuestion

What is the smallest example that makes LLM Serving at Scale: Prefill, Decode & Continuous Batching click without losing the math?

concept:llm-systems/llm-serving
Boundary

sources: yu-2022-orca, kwon-2023-pagedattention

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 2 references and 3 local witnesses are available for inspection.

LLM serving is a multi-iteration scheduling and memory-management problem: autoregressive decode advances one token at a time, batching must adapt between iterations, and KV cache memory can limit throughput.
Used here as

Orca supports the scheduling part: generative Transformer serving is multi-iteration autoregressive inference with one output token per iteration, and fixed request-level batches motivate iteration-level sch...

Local witness
Equation 1
LatencyTTFTtime to first token+(Tout1)TPOTtime per output token.\text{Latency} \approx \underbrace{\text{TTFT}}_{\text{time to first token}} + (T_{out}-1)\cdot\underbrace{\text{TPOT}}_{\text{time per output token}}.
Equation 2
MemKVBLTHkvdhead2bytes.\mathrm{Mem}_{KV} \approx B\cdot L\cdot T\cdot H_{kv}\cdot d_{head}\cdot 2 \cdot \mathrm{bytes}.
Caveat

Checks the serving mechanism only. TTFT/TPOT, goodput, KV formula, code, and demo are toy witnesses, not source-derived formulas or production benchmarks. Does not certify vendor latency, scheduler optimalit...

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. Check caveats and exact source scope.

Checked Orca and PagedAttention: Orca supports autoregressive generative Transformer serving as multi-iteration inference where each iteration emits one token, motivating iteration-level scheduling and selective batching because fixed request-level batches waste capacity. PagedAttention supports KV cache memory as large, dynamic, fragmentation-prone state that can limit batch size and throughput. Local latency/KV math, code, and demo are toy serving witnesses only.

Reviewer: codex+oracle; reviewed 2026-05-07

Practice notebook

Use the idea, then test it somewhere new

A systems mental model for LLM inference: prefill vs decode, TTFT vs TPOT, batching/scheduling, and why KV cache memory dominates.

AttemptNo learning claim inferred
Object - ConceptLLM Serving at Scale: Prefill, Decode & Continuous BatchingQuestion

What is the smallest example that makes LLM Serving at Scale: Prefill, Decode & Continuous Batching click without losing the math?

concept:llm-systems/llm-serving
Boundary

sources: yu-2022-orca, kwon-2023-pagedattention

Check

Use one state from LLM Serving at Scale: Prefill, Decode & Continuous Batching to explain what changes, why it changes, and which assumption the explanation needs.

Evidence

No learner move yet; no learning state is inferred.

Next move

Write first, use only the help you need, then try a new case without it.

Explain

Use one state from LLM Serving at Scale: Prefill, Decode & Continuous Batching to explain what changes, why it changes, and which assumption the explanation needs.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded object roomClose
Selected object routeAsk from this object; carry one invariant back.sources: yu-2022-orca, kwon-2023-pagedattention
  1. ObjectConceptLLM Serving at Scale: Prefill, Decode & Continuous Batching
  2. PredictBefore revealLLM Serving at Scale: Prefill, Decode & Continuous Batching prediction
  3. WitnessCompare codeLLM Serving at Scale: Prefill, Decode & Continuous Batching code witn...
  4. RoomAsk groundedChecking local snapshot
ConceptLLM Serving at Scale: Prefill, Decode & Continuous BatchingLLM Systems

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptLLM Systems

LLM Serving at Scale: Prefill, Decode & Continuous Batching

Anchored question

What is the smallest example that makes LLM Serving at Scale: Prefill, Decode & Continuous Batching click without losing the math?

Source boundaryInspect source ids: yu-2022-orca, kwon-2023-pagedattentionStable content-object key attached
Role lenses for this object

These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

Learner evidence requestAsk what would make "LLM Serving at Scale: Prefill, Decode & Continuous Batching" feel predictable rather than familiar.
Assumption

Source ids yu-2022-orca, kwon-2023-pagedattention must support the exact object, not just the surrounding topic.

Source-checking summary

Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.

Proposed experiment

Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.

Next action

The learner can state the mechanism in their own words

Evidence4 checks
PredictionChecking carried observation
ActionReady for one action
AILearner handoff ready
Open source object
01PredictionChecking browser-local route memory
02EvidenceChecking for a carried observation
03BoundaryInspect source ids: yu-2022-orca, kwon-2023-pagedattention
04Next moveSave one next action
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:llm-systems/llm-serving.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: yu-2022-orca, kwon-2023-pagedattention
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Object-attached AI handoff

I am working in Continuous Function's research reading room. Object: concept - LLM Serving at Scale: Prefill, Decode & Continuous Batching Object key: concept:llm-systems/llm-serving Context: LLM Systems Anchor id: concept/concept-notebook/llm-systems/llm-serving Open question: What is the smallest example that makes LLM Serving at Scale: Prefill, Decode & Continuous Batching click without losing the math? Evidence to inspect: - Source ids to inspect: yu-2022-orca, kwon-2023-pagedattention - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids yu-2022-orca, kwon-2023-pagedattention must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "LLM Serving at Scale: Prefill, Decode & Continuous Batching" feel predictable rather than familiar." | assumption: Source ids yu-2022-orca, kwon-2023-pagedattention must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: yu-2022-orca, kwon-2023-pagedattention" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "LLM Serving at Scale: Prefill, Decode & Continuous Batching" feel predictable rather than familiar. - Assumption to keep visible: Source ids yu-2022-orca, kwon-2023-pagedattention must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words

concept/concept-notebook/llm-systems/llm-serving concept:llm-systems/llm-serving