RAG — Context Engineering
Context Engineering for Production LLM Apps
Direct answer
Context engineering is deciding exactly which tokens the model sees on each call — system instructions, tool definitions, retrieved documents, memory, conversation history and the user's turn — and keeping that set small and high-signal. In production that means five habits: give every context slot a token budget, retrieve just in time instead of preloading, compact long histories into summaries, put stable content first so it can be cached, and measure answer quality with evals every time the context recipe changes.
Most LLM features that work in a demo and fail in production don't have a prompt problem — they have a context problem. The model is fed too much, the wrong thing, or the right thing in the wrong order. This guide is the checklist I use when designing or auditing the context layer of an LLM feature: what goes in, how much of it, in what order, and how you prove a change made things better instead of just different.
Key facts, with sources
- Anthropic defines context engineering as “the set of strategies for curating and maintaining the optimal set of tokens (information) during LLM inference” — and describes LLMs as having a finite “attention budget” that every new token depletes. (Anthropic Engineering, Sep 2025)
- Chroma's July 2025 “Context Rot” report tested 18 models (including GPT-4.1, Claude 4, Gemini 2.5 and Qwen3) and found performance varies significantly — and non-uniformly — as input length grows, even on deliberately simple tasks. (Chroma Research, Jul 2025)
- Claude prompt caching bills 5-minute cache writes at 1.25× the base input price and cache reads at 0.1× for most models; the default cache lifetime is 5 minutes and refreshes on every hit. (Claude API docs)
Prompt engineering vs context engineering
Prompt engineering is about the words in one instruction. Context engineering is about the whole input the model receives on every call, which in a real product is mostly not your prompt: it is tool schemas, retrieved chunks, user profile data, prior turns and tool results that piled up during an agent loop. A two-paragraph system prompt can easily sit inside 40,000 tokens of other material.
That matters because more context is not free accuracy. Long inputs cost money and latency on every call, and the research on context rot shows models get less reliable as inputs grow — especially when the extra material is topically close to the answer but not the answer. The goal is not the biggest context the window allows; it is the smallest context that still contains everything the model needs for this specific turn.
| Question | Prompt engineering | Context engineering |
|---|---|---|
| Unit of work | One instruction | Everything sent on each call |
| Main lever | Wording, examples, format | Selection, ordering, budget, compaction |
| Changes when | You rewrite the prompt | Every turn (retrieval, history, tool results) |
| Typical failure | Model misreads the instruction | Right answer buried, stale or missing |
| How you test it | A handful of examples | Eval set + per-slot token logs |
Treat the context window as a budget with slots
The most useful mental model is a budget. Split the context into named slots and give each a ceiling, so one noisy source can't crowd out the rest. A retrieval step that suddenly returns twenty long chunks, or a chat that has run for two hundred turns, then gets trimmed in its own slot instead of silently pushing the system instructions out of the model's attention.
The numbers below are an illustrative starting point for a support assistant on a large-window model, not a rule — tune them against your eval set. The point is that every slot has an owner and a limit, and the assembler enforces it in code rather than trusting each feature to behave.
| Slot | Illustrative budget | Strategy when over budget |
|---|---|---|
| System instructions | 1–3K tokens | Rewrite; never truncate silently |
| Tool definitions | 1–5K tokens | Expose only tools relevant to this task |
| Retrieved documents | 4–12K tokens | Fewer, better chunks (re-rank, dedupe) |
| Memory / notes | 0.5–2K tokens | Keep structured facts, drop prose |
| Conversation history | 2–8K tokens | Summarize older turns (compaction) |
| User turn | As sent | Ask the user to split very large pastes |
from dataclasses import dataclass
import tiktoken # any tokenizer close to your model's is fine for budgeting
enc = tiktoken.get_encoding("o200k_base")
def count(text: str) -> int:
return len(enc.encode(text))
@dataclass
class Slot:
name: str
items: list[str] # ordered most-relevant first
budget: int
def fit(slot: Slot) -> tuple[str, int]:
"""Keep whole items in priority order until the slot budget is used."""
kept, used = [], 0
for item in slot.items:
n = count(item)
if used + n > slot.budget:
break
kept.append(item)
used += n
return "\n\n".join(kept), used
def assemble(slots: list[Slot]) -> tuple[list[str], dict[str, int]]:
parts, usage = [], {}
for slot in slots:
text, used = fit(slot)
usage[slot.name] = used
if text:
parts.append(text)
return parts, usage # log `usage` on every callOrder for caching: stable prefix first, volatile content last
Providers cache the longest identical prefix of a request. If the system prompt, tool definitions and long reference material come first and never change between calls, they become a cached prefix: Claude bills cached reads at a fraction of the normal input price, and cached prefixes are faster to process. If you interpolate the user's name or today's date into the top of the system prompt, you break that prefix on every request and pay full price for all of it.
The practical rule: static instructions, then tool definitions, then large shared documents, then per-user memory, then conversation history, then the new turn. Anything that varies per request belongs as late as possible. Mark the end of the stable block as a cache breakpoint and check the usage fields in the response to confirm the cache is actually being hit.
import os
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model=os.environ["LLM_MODEL"], # pin per environment, not in code
max_tokens=1024,
system=[
{"type": "text", "text": STATIC_INSTRUCTIONS},
{
"type": "text",
"text": PRODUCT_HANDBOOK, # large, identical on every call
"cache_control": {"type": "ephemeral"}, # cache breakpoint
},
],
messages=[*compacted_history, {"role": "user", "content": user_turn}],
)
u = response.usage
log.info(
"tokens",
cache_write=u.cache_creation_input_tokens,
cache_read=u.cache_read_input_tokens,
uncached=u.input_tokens,
)Retrieve just in time instead of preloading everything
The tempting design is to stuff everything that might be relevant into the context up front: the full knowledge base section, the user's last fifty orders, every policy document. It feels safe and it is the main source of context rot. The alternative, which Anthropic describes as just-in-time context, is to keep lightweight references (IDs, file paths, saved queries) in context and let the model pull details through tools only when the turn actually needs them.
For a classic RAG feature the same idea applies at the retrieval step: retrieve more candidates than you need, re-rank them, drop near-duplicates, and only then spend tokens on the best few. Five excellent chunks beat twenty mediocre ones on both cost and accuracy, and they make failures debuggable because you can see exactly what the model was given.
Long conversations: compaction and structured notes
Chat history grows without limit, so every production assistant needs a policy for it. Dropping old turns loses facts the user stated once and expects you to remember. Keeping everything eventually blows the budget and degrades answers. Compaction sits between the two: once history passes its slot budget, summarize the older turns into a short block that preserves decisions, facts and open questions, and keep only the most recent turns verbatim.
For agents that run many steps, add structured notes: a small, typed memory (a JSON object or a notes file) that the agent writes to as it works and that is re-injected each turn. Structured notes survive compaction cleanly because they are facts, not prose, and they are easy to inspect when something goes wrong.
KEEP_RECENT = 6 # turns kept verbatim
def compact(history: list[dict], budget: int, summarize) -> list[dict]:
total = sum(count(m["content"]) for m in history)
if total <= budget or len(history) <= KEEP_RECENT:
return history
older, recent = history[:-KEEP_RECENT], history[-KEEP_RECENT:]
summary = summarize(
"Summarize this conversation for a future assistant. Keep: user facts, "
"decisions made, open questions, IDs mentioned. Drop small talk.",
older,
)
return [
{"role": "user", "content": "Summary of earlier conversation:\n" + summary},
{"role": "assistant", "content": "Understood."},
*recent,
]Prove it: evals and per-slot logging
Context changes are invisible in code review. Raising a retrieval top-k from 5 to 10 or adding one more tool is a one-line diff that can move answer quality in either direction. The only defence is a fixed eval set — real questions with known good answers or grading rubrics — that runs whenever the context recipe changes, plus logging of token usage per slot on every production call.
With both in place, questions like “did adding the order history slot help?” get answered with numbers: accuracy before and after, tokens per call before and after, cache hit rate before and after. Without them, context engineering turns into guesswork, and the context quietly grows release after release because nobody can prove any slot is safe to cut.
When to hire senior help
Context engineering expertise pays off when agent or RAG quality regresses at scale, such as degraded answers in long sessions or ballooning token bills, because the fixes involve caching structure, compaction, and retrieval budgets rather than model swaps. A senior review of your context layout can often cut inference spend substantially while improving accuracy, which quickly recovers the cost of the engagement. If your stack includes React Native + Python + AI, a senior engineer who owns the full product beats coordinating multiple juniors.
Bottom line
Dhairya Senjaliya ships RAG — Context Engineering projects worldwide — book a scoping call to discuss your specific situation.
Common pitfalls to avoid
- ✕Stuffing the full document set into a million-token window and assuming accuracy holds, when Chroma measured degradation starting around 50K tokens.
- ✕Placing the most important instructions or evidence mid-prompt, exactly where lost-in-the-middle effects hit hardest.
- ✕Rebuilding the entire prompt on every call instead of structuring stable prefixes for prompt caching, paying 10x more input cost than necessary.
- ✕Fixing missed answers by retrieving more chunks, which increases distractor interference and often lowers answer quality instead of raising it.
Frequently asked questions
What is context engineering in simple terms?
Choosing, ordering and limiting everything the model sees on each call — instructions, tools, retrieved documents, memory and history — so it gets the smallest set of information that still lets it answer well.
Is a bigger context window always better?
No. A bigger window raises the ceiling, but research such as Chroma's Context Rot report shows reliability varies as inputs grow. Use the window as headroom, not as a target, and fill it only with material that improves answers on your eval set.
How is context engineering different from RAG?
RAG is one input to the context — the retrieved documents slot. Context engineering covers all slots together: how much budget retrieval gets versus history, tools and memory, what order they appear in, and how they are compacted over time.
Does prompt caching change how I should structure context?
Yes. Caching rewards a stable prefix, so static instructions, tool definitions and large shared documents should come first and stay byte-identical across calls, with per-user and per-turn content placed last.
What should I log to debug context problems?
Token counts per slot, which documents and tools were included, cache read and write tokens, and the model's answer. With those you can replay a bad answer and see whether the right information was missing, buried or never retrieved.
With million-token context windows, is RAG obsolete?
No: a 2026 benchmark measured long-context prompting at roughly 26 times the per-query cost of RAG, and Chroma's research shows accuracy degrades as inputs grow regardless of advertised window size. Long context is useful for single-document analysis, while retrieval remains cheaper and more reliable for large or frequently changing corpora.
What is context engineering versus prompt engineering?
Prompt engineering focuses on instruction wording; context engineering manages everything occupying the model's context window, including retrieved documents, tool outputs, conversation history, and memory. In agent systems it covers compaction, note-taking, and sub-agent isolation to keep the window under control over long sessions.
How much context should we give the model per query?
Only what earns its place: retrieval studies consistently show a handful of high-relevance chunks beats large dumps, because semantically similar but irrelevant text actively misleads models. Measure with an evaluation set as you vary retrieved chunk count, since the optimum differs by task and corpus.
Bottom line: Dhairya Senjaliya ships RAG — Context Engineering projects worldwide. Book a scoping call at https://dhairyasenjaliya.com/#book-call.