Forward Deployed EngineeringAI EngineeringContext Architecture
When do you use long context, RAG, or prompt caching, and what are the failure modes of each?
Question 61 of 73 · Updated
On this page
- Interview-ready answer
- 1. Architecture selection
- Practical selection questions
- 2. Failure modes and discriminating tests
- 3. Quantify the trade-off at the workload level
- Tested Python: expected input and retrieval cost
- 4. Build hybrids around the customer's task
- 5. Make the production decision with evidence
Interview-ready answer#
I separate two architectural decisions: which evidence the model should see and how much repeated inference work I can avoid. Long context and RAG address the first; prompt caching addresses the second. They are not mutually exclusive alternatives.
I use long context when the relevant, authorized material is bounded and cross-document reasoning or comprehensive coverage matters. I use RAG when the corpus is large, frequently changing or contains data that must be selected by permissions and relevance. I add prompt caching when measured traffic reuses a substantial compatible prefix often enough to improve latency or cost.
The final choice depends on evidence recall, answer correctness, freshness requirements, workload distribution and total cost per successful task. A cheaper architecture that misses a decisive contractual exception is not a better architecture.
1. Architecture selection#
| Approach | Best fit | Principal failure mode |
|---|---|---|
| Long context | Bounded document set; analysis requiring broad coverage or relationships across sections | Relevant information is present but overlooked, confused with distractors or truncated |
| RAG | Large or changing knowledge base; targeted questions over authorized sources | Essential evidence never enters the context |
| Prompt caching | Repeated stable instructions, tool schemas or authorized document snapshots | Low reusable-token fraction, cache eviction or invalid scope |
| Hybrid | Repeated work over a large corpus with bounded relevant subsets | Extra routing complexity and inconsistent evidence versions |
A long-context window is a capacity limit, not a guarantee of effective attention or faithful reasoning. RAG limits the evidence supplied to the model, which can improve focus but makes retrieval completeness a dependency. Caching compatible prefilled state does not retrieve new documents, resolve contradictions, increase the logical context window or guarantee answer correctness.
Practical selection questions#
- Evidence scope: Can the full relevant corpus fit with room for instructions, conversation and output? If not, select evidence or decompose the task.
- Question type: Is the user asking for one fact, a relationship across a few documents, or exhaustive coverage of a collection?
- Freshness: Are sources stable during a session, or must every request reflect newly changed records?
- Reuse: How many input tokens are shared across requests within the supported cache lifetime and isolation boundary?
- Risk: What happens if the model omits evidence? Can the answer be verified independently?
For exhaustive questions over a corpus larger than the context window, a top-k retrieval call is rarely sufficient. Use explicit enumeration, structured queries or partitioned extraction with coverage tracking and aggregation. A long-context model can help synthesize the selected evidence but cannot certify completeness simply by accepting more tokens.
2. Failure modes and discriminating tests#
| Failure | Diagnostic | Mitigation |
|---|---|---|
| Long context misses a buried exception | Place the same required evidence at several valid positions and vary distractor load | Structure evidence, preserve headings and references, use targeted extraction and verification |
| Long context silently loses material | Inspect effective serialized token count and truncation behavior | Reserve output capacity and reject or decompose oversized inputs |
| RAG misses a cross-reference or rare exact term | Compare retrieved passages with labeled evidence; replay with oracle evidence | Use lexical and dense retrieval, metadata filtering, section expansion or bounded multi-step retrieval |
| RAG retrieves obsolete or unauthorized evidence | Inspect source revisions, index freshness and effective access filters | Enforce permissions before disclosure, version documents and monitor ingestion lag |
| Cache hit rate collapses | Compare cached-token ratios, prefix revisions, request timing and routing | Keep stable content stable where semantics permit; measure actual reuse and expiry |
| Cached artifact is stale or crosses an access boundary | Test revision changes and permission revocation | Bind reuse to compatible versions and the correct trust scope; perform authorization on each request |
The oracle-evidence test is especially useful: if the model answers correctly with the missing authoritative evidence, the original failure was upstream of generation or involved an interaction with context construction. It is not enough to conclude that a retrieval algorithm alone caused the failure without checking the source, index and filters.
For cache behavior, distinguish inference-prefix caching from application response caching. With correct prefix matching, changed tokens require new computation for the affected suffix. A stale response cache or an incorrectly selected document snapshot is a separate application-level correctness problem.
3. Quantify the trade-off at the workload level#
Consider a hypothetical enterprise document assistant. One approach sends a 50,000-token document snapshot; another retrieves 5,000 tokens per request. Assume an input price of $2 per million tokens, a cache-read multiplier of 0.1, no cache-write premium or storage fee, and a retrieval service cost of $0.004 per request. Assume all 50,000 tokens are reused on a hit. Common instructions, output, retries and other costs are excluded from this comparison.
| Approach | Expected evidence-processing cost per request |
|---|---|
| Long context, cold | $0.100 |
| Long context, 90% complete-prefix hit rate | $0.019 |
| RAG, uncached evidence | $0.014 |
| Long context, 100% complete-prefix hits | $0.010 |
The cached long-context path costs 0.10 × (1 − 0.9h), where h is the probability of a complete-prefix hit. It equals the RAG cost at h = 43/45, or approximately 95.56%. It is cheaper above that point under these assumptions, but a 90% hit rate is not enough.
The important lesson is that a strong caching discount does not automatically make a large input economical. Partial hits, cache-write premiums, storage fees, retrieval infrastructure, repeated evidence searches, retries and output length can move the break-even point. Compare measured cost per correct completed task, not just input-token prices.
Tested Python: expected input and retrieval cost#
PYTHONfrom fractions import Fraction as F def expected_cost(tokens, price, hit_rate, read_ratio, extra=0): p,h,r,e=map(F,(price,hit_rate,read_ratio,extra)) if type(tokens) is not int or tokens<0 or p<0 or not 0<=h<=1 or not 0<=r<=1 or e<0: raise ValueError('invalid inputs') return F(tokens,1_000_000)*p*(1-h+h*r)+e
Use decimal strings or exact fractions for monetary inputs. The helper models full-prefix hits, ordinary input pricing on misses and an optional fixed per-request fee; it deliberately omits premium writes, storage and partial hits. Python 3.13.5 passed 3,879 checks: 3,872 parameter combinations compared against independently enumerated hit/miss costs, six invalid inputs and the worked example including its break-even threshold. Prices are illustrative, not current provider rates.
4. Build hybrids around the customer's task#
| Customer workload | Architecture I would start with |
|---|---|
| A legal team compares clauses in a small set of approved contracts | Supply the bounded documents in long context; cache compatible repeated prefixes for follow-up questions |
| Support staff ask narrow questions over thousands of changing policies | Retrieve current applicable passages; cache stable instructions and tool definitions |
| A researcher synthesizes several related reports selected from a huge collection | Retrieve relevant report IDs, expand to authorized sections or full bounded reports, then use long-context synthesis |
| An auditor must identify every affected record across a large collection | Enumerate records using structured queries or partitioned workflows; use the model for local extraction or synthesis, not as proof of exhaustive search |
A hybrid should route according to explicit task requirements, corpus size and evidence sufficiency, not rely solely on a model deciding whether it needs more context. For example, a targeted lookup can expand from a chunk to its parent section if essential qualifiers are missing. If the expanded set fits, a long-context pass can reason across it. If decisive evidence still cannot be established, return a bounded answer or escalate rather than silently guessing.
Caching is orthogonal to this routing: both branches may reuse a stable prefix. Where document content or permissions change, fetch the current authorized revision. Do not extend cache lifetime or preserve stale material to protect hit rate.
5. Make the production decision with evidence#
Run the candidate designs on the same representative tasks, including global synthesis, rare-term lookup, recent document changes, contradictory evidence and unanswerable questions. Keep the model and expected outcomes comparable. Measure:
- Evidence coverage and claim support, with decisive omissions reported separately.
- Correct task completion and appropriate abstention by question type.
- Cold and warm time to first token, end-to-end p95 latency, timeout rate and throughput at realistic concurrency.
- Actual cached input tokens, retrieval and indexing costs, and cost per successful task.
A retrieval round trip may be slower than a warm bounded-context call; long-context prefill may be slower than retrieving a small evidence set. Neither ranking is universal. Include queueing, reranking, context construction and generation in the measurement, and use realistic query arrival patterns instead of testing only warmed-up caches.
I would choose the simplest design that meets the customer's evidence and safety requirements, add the second retrieval or context path only where it materially improves outcomes, and enable caching where real reuse justifies it. FDE-0046 covers general cache-write economics; the focus here is architecture selection and measured end-to-end trade-offs.
References
- 1.
- 2.
- 3.OpenAI — Prompt caching (not live-verified)platform.openai.com
- 4.
- 5.
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models