Skip to main content
← CONCEPTS / AI & MACHINE LEARNING
An end-to-end domain learning journey

Input &
Output Tokens.

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.
Start the journey5 sections
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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).

Full walkthrough · 5 stages
01
AI & MACHINE LEARNING · STAGE 01L4 · FUNDAMENTALS

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.

ChoiceWhat it buysWhat it costs
Good candidateBudgeting context windows across system prompt, RAG chunks, chat history, and max_tokens output reserve.
Good candidateStructuring prompts with static prefixes first to trigger provider KV/prompt caching.
Think twiceEstimating 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.

Interactive Architecture Explorer

Token Lifecycle: Tokenization → Prefill → Decode

BPE TokenizerPrefill EngineKV Cache (HBM)Decode Loop
BPE Tokenizer
Text -> Subword IDs
Prefill Engine
Compute-bound (TTFT)
KV Cache (HBM)
Stores K/V per token
Decode Loop
Bandwidth-bound (TPOT)
Text is tokenized via BPE, processed in parallel during Prefill to populate the KV cache, and then decoded one output token at a time.
02
AI & MACHINE LEARNING · STAGE 02L5 · APPLIED DESIGN

Walkthrough & implementation.

A RAG assistant sends 6,000 input tokens (system prompt + 8 retrieved chunks) and generates 400 output tokens.

Order platform / RAG Prompt Budget & Cost Asymmetry

RAG Prompt Budget & Cost Asymmetry.

A RAG assistant sends 6,000 input tokens (system prompt + 8 retrieved chunks) and generates 400 output tokens.

Lesson: Prefill processes all 6,000 input tokens in ~120ms (TTFT). Decode takes 400 sequential steps (~20ms/token = 8 seconds total). At $2.50/1M input and $10/1M output, the 400 output tokens cost ~$0.004 while the 6,000 input tokens cost ~$0.015—and caching the 2,000-token system prefix cuts input cost and TTFT further.

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
Interactive Walkthrough

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).

Context Window Budget (8,192 max)Input + Output <= 8,192
Static System PCACHEABLERAG + User QuerDYNAMIC
Static System Prefix1,500 tokens
CACHEABLE
RAG + User Query2,500 tokens
DYNAMIC
Total Input Tokens
4,000 tokens
Remaining Context
4,192 tokens for output
03
AI & MACHINE LEARNING · STAGE 03L6 · SCALE & TRADE-OFFS

Weighing architectural trade-offs.

Every design choice in Input & Output Tokens trades off latency, throughput, operational complexity, or consistency guarantees.

ChoiceWhat it buysWhat it costs
Long Context vs. Reranked Top-KFewer retrieval missesHigher TTFT, larger KV cache, and 'lost-in-the-middle' dilution
Verbose Chain-of-Thought OutputHigher reasoning accuracy on hard tasksLinearly increases TPOT latency and 3x–5x output token cost
Interactive Trade-Off Simulator

Context & Output Token Budget Simulator

Tune parameters to inspect latency vs. safety
Reasoning Depth & Context →End-to-End Latency & Cost →YOU ARE HERE
p99 Tail Latency9.6 ms
Sustained Throughput5,445 ops/s
Safety & Invariant Score100 / 100
Large input increases TTFT and KV-cache RAM per concurrent user.
04
AI & MACHINE LEARNING · STAGE 04L6 · SCALE & TRADE-OFFS

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.

INPUT + OUTPUT > MAX_CONTEXTNo output reserveHalf-written JSONFIX: RESERVE MAX_TOKENS BEFORE TRIMMING
DYNAMIC FIELD AT LINE 1Timestamp changes0% KV prefix reuseFIX: STATIC PREFIX FIRST, DYNAMIC LAST
05
AI & MACHINE LEARNING · STAGE 05L7 · STAFF / PRINCIPAL

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 it together · Synthesis

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.

A candidate architecture, not a universal answer

Reference Topology & Execution Flow

Step 1
Step 2
Step 3
  1. Count tokens with the target tokenizer and reserve output max_tokens first.
  2. Put static instructions/tools first for KV prefix caching; place dynamic RAG/user text last.
  3. Track TTFT (Prefill) and TPOT (Decode) separately in production telemetry.
Predictable latency, zero JSON truncation, and 50%+ lower inference spend.
Key Production Takeaway

Predictable latency, zero JSON truncation, and 50%+ lower inference spend.

Verify invariants with bounded retries, timeouts, and observability.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Practice Check

Test your understanding

Question 1 of 1

Why does placing request_timestamp at the very beginning of a 3,000-token system prompt hurt latency and cost?

Recommended Learning Flow