Course
AI · Module 01: How LLMs Work Under the HoodTutorial 2 of 21
AI Course·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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:

  1. System Instructions & Persona (500 – 3,000 tokens)
  2. Tool / MCP JSON Schemas (1,000 – 15,000 tokens — 30 tools easily eat 10k tokens before the user says "Hi"!)
  3. Retrieved RAG Documents / Code Files (2,000 – 60,000 tokens)
  4. Full Multi-Turn Chat History (every prior user message, assistant reply, and tool output)
  5. Hidden Reasoning / Thinking Tokens (for reasoning models like o3, Gemini Thinking, or Claude Extended Thinking)
  6. 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 (PARALLEL · COMPUTE-BOUND)Processes all N prompt tokens at once → determines TTFT[System Rules + 10k Docs + User Question]KV CACHE SAVED IN GPU VRAMStatic prefix K, V tensors cached (50%–90% cheaper!)PHASE 2: DECODE (1 TOKEN AT A TIME · MEMORY-BOUND)Each output token attends to cached K,V + appends its ownToken #1Token #2Token #KWHY OUTPUT TOKENS COST 3×–5× MORESequential loop reloads model weights per generated token!
Figure: Input tokens run in parallel (Prefill), while output tokens generate sequentially one by one (Decode) — explaining both latency and API pricing.
  • Phase 1 — Prefill (Compute-Bound): All N prompt tokens are already known, so the GPU computes their Q, K, V matrices in parallel in one giant matrix multiplication. The duration of Prefill determines your Time To First Token (TTFT). Crucially, the GPU saves the resulting K and V tensors 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 recompute K and V for the first N tokens! It computes Q, K, V for only the 1 newest token, attends against the saved KV Cache, emits 1 token, appends its K, V to 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 TTFT on a 50k-token prompt from 3.5s down to 0.4s!).
  • The Golden Ordering Rule: Even 1 changed character (like Current timestamp: 2026-11-27T10:01:05Z at line 1 of your system prompt!) invalidates the entire KV cache downstream of that character!
TEXT
❌ 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:

THE "LOST IN THE MIDDLE" U-CURVE (RETRIEVAL RECALL ACROSS LONG PROMPTS)95%55%Primacy Zone (Top System Rules)Middle Trough (Buried Docs Ignored!)Recency Zone (Final Instructions)Token 0 (Start of Prompt)Middle of 128k WindowEnd of Prompt
Figure: Put non-negotiable system constraints at the very top and repeat critical output instructions + highest-relevance RAG chunks right at the bottom.

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:

  1. Retrieve top 5–8 high-signal chunks via Hybrid RAG + Reranking instead of dumping 80 noisy PDFs into the prompt.
  2. 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:

Tracing KV Prefix Caching Across Multi-Request Traffic
Interactive LLM Pipeline Tracer · Step 1 of 3 (1. Cold Request (Prefill Populates KV Cache))
Wire Telemetry:in=8012 tokkv_cached=0 tokout=45 toklatency=1120mscost=$0.0247
1→STATIC_PREFIX = SYSTEM_RULES + TOOL_SCHEMAS # 8,000 tokens
2→# Request 1: Cold start (computes & stores KV Cache)
3→r1 = call_llm(STATIC_PREFIX + "User A: Reset password?")
4# Request 2: Exact prefix match -> 90% KV Cache HIT!
5r2 = call_llm(STATIC_PREFIX + "User B: Upgrade plan?")
6# Anti-pattern: Injecting timestamp at top busts cache!
7bad = call_llm(f"Now={time.time()}" + STATIC_PREFIX + "Hi")
GPU Prefill Work0% Cached
Computes K, V tensors for all 8,012 tokens and hashes the 8,000-token static prefix into distributed cache.
What's Happening: Request #1 pays full Prefill latency (1,120ms) and full input price — but automatically warms the prefix cache for every user who arrives next!

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:

SDK:
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)

  1. 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!
  2. 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.
  3. Reasoning Token Starvation: On reasoning models (o3, Gemini Thinking), setting max_output_tokens=300 when the model spends 300 tokens 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

Q1.Why does inserting `Current time: 2026-11-27 14:03:22` at the VERY FIRST LINE of a 10,000-token system prompt destroy Prompt Caching?
Q2.What does the 'Lost in the Middle' phenomenon describe in long-context LLMs?
Q3.Which phase of LLM inference determines Time To First Token (TTFT)?
Q4.In a 25-turn stateful chat app, why does naive history appending cause runaway bills even if each user message is only 50 tokens?

Keep Exploring: Related Lessons & Tools

All Courses →