The Anatomy of an LLM Call: Tokens, Context Windows & Probabilistic Mechanics
Engineers routinely measure AI performance by total request time alone, missing the critical distinction between TTFT and TPS. This article dissects BPE tokenisation, KV cache mechanics, and the pre-fill vs decode phase split that defines every latency budget in the Workspace streaming gateway.
Full-Stack AI Architecture: From Streaming Foundations to Resilient Agentic Systems in Node.js & React
The Anatomy of an LLM Call: Tokens, Context Windows & Probabilistic Mechanics
Every engineering decision in this series — how we size streaming buffers, schedule context windows, price caching investments, and govern agent budgets — descends from a single source of truth: what exactly happens inside an LLM API call at the millisecond level. Engineers who skip this article treat latency as an opaque black box, then spend weeks chasing phantom performance bottlenecks. This article eliminates that opacity.
We dissect four interconnected mechanisms: Byte-Pair Encoding tokenisation, the pre-fill versus decode phase split, KV cache reuse, and the probabilistic sampling loop that converts a probability distribution into the next token. Each connects directly to concrete API decisions in Parts 4–7.
Who this is for: Full-stack engineers who call LLM APIs but measure performance only by total response time. After this article, you will instrument TTFT, ITL, and TPS as separate first-class metrics and make informed decisions about model selection, prompt structure, and caching strategy.
1. Tokenisation: From Characters to Vocabulary IDs
1.1 Byte-Pair Encoding (BPE) in Practice
LLMs do not see text. They see integer IDs from a fixed vocabulary. The tokeniser is the translation layer. Modern foundation models use BPE with vocabulary sizes between 50,000 and 256,000 tokens.
BPE encodes text by iteratively merging the most frequent character-pair sequences in training data until a target vocabulary size is reached. Common English words become single tokens; rare words, names, and non-ASCII characters fragment into multiple tokens.
The practical consequence: cost and latency are not proportional to character count. Code with heavy indentation, multilingual content, and long identifier names tokenises at 2–4× the cost of equivalent plain English prose.
1.2 The Three Cost Variables Engineers Control
| Variable | What You Control | Token Impact |
|---|---|---|
| System prompt length | Tool schema verbosity, instruction wordiness | Fixed per-request overhead; amortise with prefix caching |
| Conversation history length | How many prior turns you include | Linear growth; prune with summarisation (Part 14) |
| Output max_tokens | Upper bound on generation | Hard billing ceiling; set conservatively with stop sequences |
2. The Two Phases of Inference: Pre-fill and Decode
2.1 Phase Split and What It Means for Latency
A single LLM API call has two fundamentally different computational phases. Most engineers measure only the total time. That is the wrong metric.
| Metric | Phase | Scales With | Engineering Lever |
|---|---|---|---|
| TTFT (Time-to-First-Token) | Pre-fill | Input token count, model size, GPU memory | Prefix caching; shorter system prompts |
| ITL (Inter-Token Latency) | Decode | Memory bandwidth of GPU | Model quantisation; output length limits |
| TPS (Tokens Per Second) | Decode | 1 / ITL | Model selection; provider tier |
| Total Latency | Both | Input + Output tokens | All of the above |
For streaming chat UIs, TTFT is the metric users feel. A 5-second TTFT with fast ITL feels worse than a 1.5-second TTFT with moderate ITL. React 18 streaming UIs must report TTFT as a Span metric (Part 23) and adjust loading indicators accordingly — a spinner that disappears at TTFT, then progressive text, is dramatically better UX than waiting for total completion.
2.2 Measuring TTFT and ITL in the Gateway
3. KV Cache: The Billion-Dollar Optimisation
3.1 What the KV Cache Is
During the pre-fill phase, the transformer computes a Key (K) and Value (V) matrix for every token in every attention layer. These matrices are the memory of the attention mechanism. Without caching, every new decode step re-computes them for all prior tokens — quadratic complexity.
The KV cache stores these K/V matrices in GPU VRAM so the decode phase only computes new tokens. This is what makes autoregressive generation feasible at all. At the provider level, it is also the foundation of prompt prefix caching.
3.2 Prompt Prefix Caching: The Cost Reduction That Pays for Itself
Modern providers (Anthropic, OpenAI) extend KV caching across API requests. If consecutive requests share an identical byte-prefix in the prompt, the provider reuses the cached K/V matrices — reducing pre-fill compute cost by 80–90% for the cached portion.
The critical constraint: the cached prefix must be byte-identical. A single character change anywhere in the system prompt or tool schemas invalidates the entire cache for all tokens after that point.
3.3 Practical KV Cache Sizing and VRAM
This is why long-context models are expensive to host — KV cache memory grows linearly with context length. Every 10k tokens of context you add costs approximately 3.2 GB of VRAM. At the API level, you pay for this with higher per-token pricing on longer contexts.
4. The Sampling Loop: Probability to Token
4.1 How Temperature and Top-P Shape Output
After pre-fill, each decode step runs the same process:
- Forward pass through the transformer with current K/V cache → produces a logit vector (one scalar per vocabulary token).
- Apply temperature scaling:
logits / temperature. - Apply Top-P nucleus sampling: keep only the smallest token set whose cumulative probability ≥ p.
- Sample from the remaining probability distribution.
- Append the sampled token ID to the sequence; update K/V cache.
- If the token is the EOS token (or
max_tokensreached), stop.
4.2 What This Means for API Configuration
| Parameter | Effect | Production Recommendation |
|---|---|---|
temperature: 0.0 |
Deterministic argmax (greedy) | Structured output tasks: schema generation, SQL, code |
temperature: 0.3–0.7 |
Controlled creativity | Document drafting, summarisation in the Workspace |
temperature: 1.0+ |
High diversity, frequent incoherence | Avoid in production; useful only for synthetic data generation |
top_p: 0.95 |
Standard nucleus — good default | Use with temperature, not instead of it |
max_tokens |
Hard decode stop | Always set; no default protects against runaway generation |
5. Connecting Mechanics to Architecture: The Workspace Implications
Every mechanism in this article has a direct architectural consequence in the Workspace system:
| Mechanism | Workspace Impact | Series Article |
|---|---|---|
| BPE cost variability | Code-heavy prompts cost 2–4× more; tool schemas need size discipline | Part 3, Part 16 |
| TTFT ≠ Total Latency | SSE clients must show first-token spinner, not completion spinner | Part 6 |
| Pre-fill scales with input | RAG chunks are expensive to stuff; budget is mandatory | Part 14 |
| Prefix caching requires stability | System prompt and tool schemas serialised deterministically | Part 3, Part 14 |
| KV cache is VRAM-bound | Long-context is not free; context window scheduling is an economic lever | Part 14 |
| Sampling is stochastic | temperature: 0 for schema tasks; never assume repeatability |
Part 3 |
Summary
| Concept | Rule |
|---|---|
| Token Cost | Count tokens, not characters. Code, non-ASCII text, and indentation tokenise at 2–4× premium. |
| TTFT | The metric users feel in streaming UIs. Reduce by shortening system prompts and leveraging prefix caching. |
| Pre-fill | Scales with input length. Every RAG chunk, history turn, and tool schema has a pre-fill cost. |
| Prefix Cache | Maximise by placing stable content (system prompt, tool schemas) first and byte-identically across requests. |
| Temperature | Set 0 for structured/schema tasks; 0.3–0.7 for prose; always set max_tokens. |
What's Next
Part 3 converts the probabilistic mechanics into a formal contract system. We implement grammar-constrained decoding, Zod strict schema validation with
.strict(), and an AST self-repair pipeline that recovers from streaming truncation — the structural invariant gate that sits at the heart of the Workspace trust boundary.
This article was developed with AI-assisted deep search, specification cross-referencing, and technical research synthesis.