1.2 Context Windows, Self-Attention & KV Caching
Understand how Transformer Self-Attention, Prefill vs Decode phases, KV Caching, and the 'Lost in the Middle' effect govern latency, accuracy, and 90% prompt-caching discounts.
1. What Actually Lives Inside the Context Window?
Beginners think a 128k or 1M token context window is just "how long my question can be." In reality, an LLM is 100% stateless between HTTP requests — it has no hidden session memory on the server. Every single turn, the context window acts as one shared, finite working-RAM buffer holding everything:
- System Instructions & Persona (
500 – 3,000tokens) - Tool / MCP JSON Schemas (
1,000 – 15,000tokens — 30 tools easily eat 10k tokens before the user says "Hi"!) - Retrieved RAG Documents / Code Files (
2,000 – 60,000tokens) - Full Multi-Turn Chat History (every prior user message, assistant reply, and tool output)
- Hidden Reasoning / Thinking Tokens (for reasoning models like
o3, Gemini Thinking, or Claude Extended Thinking) - The New Output Tokens Being Generated Right Now
If Input + Thinking + Output > Context Limit, the API either throws 400 context_length_exceeded or truncates your output mid-JSON!
2. Self-Attention in Plain English (Why Long Prompts Cost More)
How does a Transformer know that in "The database rejected the query because it lacked an index", the word "it" refers to "query" and not "database"?
Inside every Transformer layer, each token projects its vector into three roles:
- Query (
Q): "What context am I looking for?" - Key (
K): "What label describes what I contain?" - Value (
V): "What actual payload do I pass forward if selected?"
Every token computes a dot-product relevance score against the Keys of all preceding tokens (Attention = softmax(Q · Kᵀ / √d) · V). Because token N compares against all 1..N tokens, processing a full prompt of N tokens requires O(N²) pairwise comparisons! Doubling your prompt from 10k → 40k tokens multiplies attention compute by 16×.
3. Prefill vs. Decode & The Magic of the KV Cache
Every LLM inference call splits into two dramatically different hardware phases:
- Phase 1 — Prefill (Compute-Bound): All
Nprompt tokens are already known, so the GPU computes theirQ, K, Vmatrices in parallel in one giant matrix multiplication. The duration of Prefill determines your Time To First Token (TTFT). Crucially, the GPU saves the resultingKandVtensors for every layer in VRAM — this is the KV Cache. - Phase 2 — Decode (Memory-Bandwidth-Bound): To generate token
N+1, the GPU does not recomputeKandVfor the firstNtokens! It computesQ, K, Vfor only the 1 newest token, attends against the saved KV Cache, emits 1 token, appends itsK, Vto the cache, and repeats.
The #1 Production Optimization: Prompt Caching (Prefix Reuse)
OpenAI, Anthropic, and Google Gemini all persist KV Caches across requests for 5 to 60 minutes whenever two requests share the exact same byte-for-byte prefix (typically >= 1,024 tokens)!
- Discount: Cached prefix tokens are 50% to 90% cheaper and skip Prefill compute (cutting
TTFTon a 50k-token prompt from3.5sdown to0.4s!). - The Golden Ordering Rule: Even 1 changed character (like
Current timestamp: 2026-11-27T10:01:05Zat line 1 of your system prompt!) invalidates the entire KV cache downstream of that character!
❌ CACHE-BUSTING PROMPT ORDER (0% Cache Hit Rate!)
[1. Dynamic Timestamp & User ID] -> [2. Static System Rules] -> [3. 20 Tool Schemas] -> [4. User Query]
✅ CACHE-OPTIMIZED PROMPT ORDER (90% Cache Hit Rate!)
[1. Static System Rules] -> [2. Static Tool Schemas] -> [3. Shared Reference Docs] -> [4. Dynamic User Context & Query]
4. Why 1M Context ≠ 100% Accuracy ("Lost in the Middle")
Even if a model accepts 200k or 1M tokens without crashing, empirical Stanford/multi-provider benchmarks ("Needle in a Haystack" & multi-hop reasoning) consistently show a U-shaped recall curve:
Models attend strongest to the Primacy Zone (very beginning of the prompt) and the Recency Zone (very end of the prompt), while facts buried in the middle of 40 irrelevant documents suffer context rot / attention dilution.
Engineering Mitigations:
- Retrieve top 5–8 high-signal chunks via Hybrid RAG + Reranking instead of dumping 80 noisy PDFs into the prompt.
- Put non-negotiable constraints at the top of the System Prompt, and repeat the critical output schema + highest-ranked evidence right above the final user question.
5. Interactive Trace: Watching Prompt Caching Slash Latency & Cost
Click Next to compare Request #1 (Cold KV Cache) vs Request #2 (Warm Prefix Cache Hit) vs a Broken Cache-Busted Prompt:
Computes K, V tensors for all 8,012 tokens and hashes the 8,000-token static prefix into distributed cache.
6. Production SDK Code: Enabling & Verifying Prompt Caching
OpenAI and Gemini cache long prefixes automatically (>= 1,024 tokens), while Anthropic gives you explicit cache_control breakpoints for surgical control:
from openai import OpenAI
client = OpenAI()
# Automatic Prompt Caching triggers on exact prefixes >= 1,024 tokens!
# Keep static rules + schemas FIRST; put dynamic user input LAST.
resp = client.responses.create(
model="gpt-4o",
instructions=LARGE_STATIC_SYSTEM_SPEC, # e.g., 4,000-token rubric
input="Audit this SQL query: SELECT * FROM orders WHERE YEAR(created_at) = 2026",
)
cached = resp.usage.input_tokens_details.cached_tokens
total_in = resp.usage.input_tokens
print(f"Cached: {cached}/{total_in} tokens ({100 * cached / total_in:.1f}% hit!)")7. What Breaks in Production (War Stories)
- Unordered Dict Keys Busting Tool Caches: In dynamic languages or microservices where tool definitions are assembled from hash sets in non-deterministic order, the JSON schema order changes across servers — dropping your prompt cache hit rate to 0%. Always sort tool schemas deterministically by
name! - Unbounded Chat History Growth (
O(T²)Cost Curve): Appending every message forever means Turn 30 re-sends Turns 1–29! On a 30-turn coding session, cumulative billed tokens grow quadratically (1k + 2k + 3k + ... + 30k = 465k tokens). Use a rolling summary + sliding window of the last K raw turns once history crosses a threshold. - Reasoning Token Starvation: On reasoning models (
o3, Gemini Thinking), settingmax_output_tokens=300when the model spends300tokens on internal chain-of-thought produces an empty visible answer (finish_reason: "length"). Budget generously (2,048–8,192) on reasoning calls.
Module 1.2 Mastery Check — Context Windows & KV Caching
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.