When batching and tail latency compete for accelerator cycles, input tokens run in parallel during compute-bound Prefill (affecting TTFT); output tokens run sequentially during memory-bandwidth-bound Decode (affecting TPOT and costing 3x–5x more).
TL;DR30-second simplified summary▾
Understand how BPE tokenization splits text into subwords, why input tokens (Prefill) and output tokens (Decode) have radically different latency, KV-cache, and pricing profiles, and how to budget.
Why does a 4,000-token RAG prompt answer in 150ms for the first word, yet take 8 seconds to finish streaming 400 words—and cost 4x more per output token?
Input tokens run in parallel during compute-bound Prefill (affecting TTFT); output tokens run sequentially during memory-bandwidth-bound Decode (affecting TPOT and costing 3x–5x more).
The idea & core mechanics.
Why this matters: Understand how BPE tokenization splits text into subwords, why input tokens (Prefill) and output tokens (Decode) have radically different latency, KV-cache, and pricing profiles, and how to budget context windows.
Why does a 4,000-token RAG prompt answer in 150ms for the first word, yet take 8 seconds to finish streaming 400 words—and cost 4x more per output token? Because LLM inference runs two completely different workloads: all input tokens fly through GPU tensor cores in parallel (Prefill), whereas every output token must stream model weights and the KV cache from HBM memory one token at a time (Decode). See how production gateways budget prompts and prefix caches in Design an Enterprise RAG Gateway.
| Choice | What it buys | What it costs |
|---|---|---|
| Good candidate | Budgeting context windows across system prompt, RAG chunks, chat history, and max_tokens output reserve. | |
| Good candidate | Structuring prompts with static prefixes first to trigger provider KV/prompt caching. | |
| Think twice | Estimating token budgets by word count alone—code, JSON, and non-English text expand 2x–4x in token count. |
Principle 1
Subword tokenization (BPE / SentencePiece): ~1 English token ≈ 4 chars (~0.75 words), whereas JSON punctuation, whitespace, and non-Latin scripts consume far more tokens per character.
Principle 2
Input tokens (Prompt): Processed in parallel in one Prefill pass—compute-bound (O(N²) attention), driving Time To First Token (TTFT).
Principle 3
Output tokens (Completion): Generated autoregressively one token at a time—HBM memory-bandwidth-bound, driving Time Per Output Token (TPOT) and total generation time.
Principle 4
Context window = Input tokens + Output tokens: both must fit inside max_context_len, and both allocate KV-cache memory for the duration of the request.
Token Lifecycle: Tokenization → Prefill → Decode
Walkthrough & implementation.
A RAG assistant sends 6,000 input tokens (system prompt + 8 retrieved chunks) and generates 400 output tokens.
RAG Prompt Budget & Cost Asymmetry.
A RAG assistant sends 6,000 input tokens (system prompt + 8 retrieved chunks) and generates 400 output tokens.
Input vs. Output tokens at a glance
| Dimension | Input Tokens (Prefill) | Output Tokens (Decode) |
|---|---|---|
| Execution | Parallel across prompt | Sequential (1 token per step) |
| Hardware Bottleneck | GPU Tensor Core FLOPs | GPU HBM Memory Bandwidth |
| Latency Metric | TTFT (Time To First Token) | TPOT (Time Per Output Token) |
| Typical API Price | 1x baseline | 3x–5x higher per token |
| Caching | Prompt / KV prefix cacheable | Must be generated (unless speculative) |
Reference implementation (Python — Context Window & Output Reserve Budgeter)
# Deterministic context-window budgeter preventing output truncation (Python)
def fit_rag_chunks(system_tokens: int, query_tokens: int, chunks: list[tuple[str, int]],
max_context: int = 8192, reserve_output: int = 1024) -> list[str]:
budget = max_context - reserve_output - system_tokens - query_tokens
selected = []
for text, tok_len in chunks:
if tok_len <= budget:
selected.append(text)
budget -= tok_len
return selected
Prefill, KV Cache & Decode Stepper
Step 1: Subword Tokenization
Prompt text is encoded into integer token IDs (~4 chars/token in English; denser in JSON/code).
Weighing architectural trade-offs.
Every design choice in Input & Output Tokens trades off latency, throughput, operational complexity, or consistency guarantees.
| Choice | What it buys | What it costs |
|---|---|---|
| Long Context vs. Reranked Top-K | Fewer retrieval misses | Higher TTFT, larger KV cache, and 'lost-in-the-middle' dilution |
| Verbose Chain-of-Thought Output | Higher reasoning accuracy on hard tasks | Linearly increases TPOT latency and 3x–5x output token cost |
Context & Output Token Budget Simulator
Failure modes & mitigations.
How Input & Output Tokens breaks under concurrency, partial network partitions, or overload—and how production systems recover.
Silent Output Truncation
Input + output exceeds context window or hits max_tokens, cutting off JSON mid-object. Mitigation: Reserve max_tokens upfront from the context budget and trim retrieved chunks/history before calling the model.
Prompt Cache Busting
Placing a dynamic timestamp or user ID at the start of the system prompt invalidates KV prefix caching on every request. Mitigation: Put all static instructions and tool schemas first; append dynamic user/RAG context at the end.
Production checklist & case study.
Operational guardrails, common interview pitfalls, and production verification steps for Input & Output Tokens.
Production Readiness Audit Checklist
0 / 3 verified- Assuming 1 word = 1 token across JSON, SQL, or multilingual text.
- Placing dynamic variables at the top of the prompt, defeating KV prefix caching.
Put Input & Output Tokens together
Put static system instructions first to hit KV prefix caches, reserve `max_tokens` before stuffing RAG chunks, and keep outputs concise.
Reference Topology & Execution Flow
- Count tokens with the target tokenizer and reserve output
max_tokensfirst. - Put static instructions/tools first for KV prefix caching; place dynamic RAG/user text last.
- Track TTFT (Prefill) and TPOT (Decode) separately in production telemetry.
Key Production Takeaway
Predictable latency, zero JSON truncation, and 50%+ lower inference spend.
Verify invariants with bounded retries, timeouts, and observability.
Practice: Make the trade-off yourself.
Practice Check
Test your understanding
Why does placing request_timestamp at the very beginning of a 3,000-token system prompt hurt latency and cost?