Lesson 4 · Production AI systems
Context engineering
KV cache prefix alignment, prompt caching economics, prefix discipline, and long-context architecture.
Step 1 of 5
Select
From history, retrieved documents, tools and examples, rank by relevance to this request and keep what fits the token budget.
More context is not better context: every stage trades tokens for signal, cost and safety.
What is context engineering?
Context engineering is the production discipline of managing what enters an LLM's context window, how it is ordered, and how it aligns with the underlying inference engine's Key-Value (KV) cache.
Modern inference engines (Anthropic prompt caching, OpenAI prefix caching, Gemini context caching, vLLM RadixAttention, SGLang) cache the computed KV tensors of prompt prefixes in GPU memory. When a new request shares a bit-identical prefix with a previous request, the model skips prefill computation for those tokens. Cache reads typically cost 75–90% less than standard input tokens and drop time-to-first-token (TTFT) from seconds to milliseconds.
To exploit this, context engineering demands strict prefix discipline: ordering context components from most static to most dynamic:
1. Static system instructions (role, rules, output schema)
2. Tool definitions and schemas (deterministically sorted)
3. Static reference documents and few-shot examples (cache breakpoint)
4. Conversation history (sliding window of turns)
5. Dynamic user query and runtime variables (timestamps, UUIDs)
Any dynamic variable inserted before the cache breakpoint invalidates the cryptographic prefix hash, causing a 0% cache hit rate and forcing full prefill recomputation.
Why context engineering matters
Three forces make KV-cache-aware context engineering foundational:
1. Economics: with 20k–100k token prompts (system docs, tool definitions, agent instructions), paying full input token pricing on every conversational turn is unsustainable. Prompt caching cuts input costs by 80–90%.
2. Latency: prefill latency scales with prompt length. Uncached 50k token prompts take 2–5 seconds of TTFT; cached prefixes return tokens in under 300ms.
3. The invalidation cascade: placing a single dynamic timestamp (such as inserting the current time into a system prompt) breaks prefix alignment for every downstream token, turning a 90% cache hit rate into 0% across all users.
KV cache prefix alignment pipeline
Monotonically dynamic prefix pipeline:
[1. Static system prompt: role, security boundaries] (~1k tok) ── Bit-identical across ALL requests
↓
[2. Tool schemas: sorted JSON keys, static definitions] (~2k tok) ── Bit-identical across ALL requests
↓
[3. Domain documentation & few-shot examples] (~15k+ tok) ── CACHE BREAKPOINT (ephemeral TTL)
↓
[4. Conversation history: past turns with summarisation] (~3k tok) ── Extends prefix monotonically
↓
[5. User message & dynamic variables: timestamp, session ID] ── Strictly at the dynamic tail
By keeping steps 1–3 strictly immutable, all users and all turns share the warm KV cache.
Prefix-aligned prompt assembly
import datetime
def assemble_naive(system_docs: str, history: list[dict], query: str, session_id: str) -> list[dict]:
# CRITICAL BUG: Dynamic timestamp and session ID placed at the top of the prompt!
# Because datetime changes on every turn, the prefix hash NEVER matches.
# Result: 0% KV cache hit rate, 8x higher latency, and full input token bills on 30k tokens.
system_prompt = f"""You are an enterprise technical assistant.
Current Time: {datetime.datetime.now().isoformat()}
Session ID: {session_id}
Documentation:
{system_docs}"""
return [
{"role": "system", "content": system_prompt},
*history,
{"role": "user", "content": query},
]Experiment: KV cache alignment
See how prompt structure and dynamic variable placement impact cache hit rate, TTFT, and cost.
What to observe
Prefix caching depends on cryptographic hash matching. A single dynamic character before the cache breakpoint invalidates all subsequent tokens. Moving timestamps and user IDs from the system prompt to the user query tail immediately restores cache hit rates to >90%, collapsing latency and slashing operational costs.
Production context engineering
Production rules: enforce strict prefix discipline (static instructions -> tools -> docs -> history -> query). Ensure prompts exceed provider minimum cache thresholds (e.g. 1,024 tokens). Serialize tool definitions with sorted keys to prevent hashing mismatches. Keep warm caches alive for periodic tasks using background pings within the 5-minute TTL window. Log cache_read vs cache_write telemetry on every request.
Challenge
Your support assistant has a 40k token knowledge base in its system prompt. Costs are 8x higher than projected and TTFT is over 3 seconds per turn. Telemetry reports cache_read_input_tokens = 0 on every request. Find the offending variable in the system prompt template and refactor it into an aligned prefix architecture.
Production checklist
Production checklist
0 of 8 checked
Knowledge check
Your model forgets content in the middle of a long prompt. What's the fix?
Complete
You can now engineer context for maximal KV cache alignment, low latency, and cost efficiency. Next: AI safety, bias and content moderation.
Mark this chapter as complete
Track your progress and unlock the next chapter.