Long context vs retrieval
Put the whole corpus in the prompt or retrieve five chunks: measure accuracy, cost and latency for both on the same questions, find where the information in the middle gets lost, and see how prompt caching moves the break-even
Your docqa corpus is 20,000 tokens. Questions arrive several times a minute. On claude-opus-5-5, which is cheaper in input cost per question: the whole corpus in a cached system block, or RAG with five chunks (about 2,500 tokens, uncached because every prompt differs)?
You have two ways to answer a question about a document collection. Retrieval picks a few chunks and sends only those; the previous chapters made it good at that. Long context sends the collection itself and lets attention do the retrieval. The second is simpler to build, has no retrieval failures by construction, and handles questions that need the whole corpus. It also has a cost that grows with the corpus, a latency that grows with it, and an accuracy that does not stay flat as the prompt gets longer.
Which one wins depends on four things you can measure: corpus size, traffic, question type, and how often the corpus changes. The lab measures them on docqa.
Two architectures, one task
Hold the task fixed: the 30 questions from rag-done-properly, the same corpus, the same model, the same instruction to answer from the documents or say they do not contain the answer. Change one thing:
- RAG:
struct-rerankretrieves five chunks, about 2,500 tokens with the question and instructions, and the model answers from them. - Long context (LC): the five corpus files, about 20,000 tokens, go into the system prompt in
<document source="...">tags with a cache breakpoint, and the question goes in the user turn.
To make the long-context case honest at scale, the lab then hides the same five files inside 130,000 tokens of filler, the ATLAS lessons, which are technical, real, and about other systems. The filler contains its own ports, Postgres versions and environment variables, so it is a haystack of plausible distractors rather than random text. You will move the five files from the start of the prompt to the end and watch accuracy.
What long context does well
It does not miss. Every failure class from rag-done-properly that came from retrieval (a fact split across a chunk boundary, a chunk that lost its heading, an identifier the embedding could not see) does not exist when the whole document is present.
It answers questions that retrieval structurally cannot:
- Aggregation. ‘How many chapters does module A3 have?’ needs every row of a table that the chunker split across chunks. ‘Which documents mention Supabase?’ needs every document.
- Multi-hop. ‘Which port does the store that holds the payments service’s idempotency keys listen on?’ needs Redis from the service description and 6379 from the ports list. Top-k retrieval finds the first hop and not the second unless the two happen to share a chunk.
- Negatives. ‘Which lab does not use Postgres?’ needs everything that does.
Li and colleagues (2024) compared RAG and long context across public long-document benchmarks and found long context ahead on average when the model and budget allowed it, with RAG far cheaper. They proposed Self-Route: answer with RAG, let the model say when the retrieved chunks are insufficient, and only then send the long context. Most questions are lookups, so most go the cheap way.
What it does badly: the middle
Lost in the Middle (Liu and colleagues, 2023) gave models 10 to 30 retrieved documents with one containing the answer, and moved that document through the list. Accuracy traced a U: highest with the answer first or last, lowest in the middle. For one model at 20 documents, middle-position accuracy fell below its closed-book score, as if the documents had made it worse. The cause is in how models are trained and how attention distributes over long inputs, and newer models flatten the U considerably on simple lookups.
Simple lookups are also the easy case. Three later results are the ones to remember:
- RULER (Hsieh and colleagues, 2024) kept the needle test but added multi-needle retrieval, variable tracing across hops, and aggregation. Models that scored near 100% on the single needle dropped sharply as length grew; of the long-context models tested, only about half held satisfactory performance at 32K tokens. The advertised window and the effective window are different numbers.
- NoLiMa (Modarressi and colleagues, 2025) removed literal word overlap between question and needle, so the model has to make an association rather than match a string. At 32K tokens, 11 of 13 models fell below half their short-context score.
- Context Rot (Chroma, 2025) tested 18 models and found performance declining with input length on every experiment, faster when the question and the answer share little vocabulary, and worse with each topically similar distractor added.
So the position effect on your docqa lookups, which mostly share exact tokens with their answers, will be small on a current model, and the lab may show no U at all. That is a result, not a failure of the experiment. The effect returns when questions paraphrase, when distractors are close, and when the task is aggregation over the whole prompt. Your production questions are probably some of each, which is why you measure on them and not on a needle benchmark.
Two practical rules follow. Put the most important material at the start or the end: instructions and the most-used documents first, the question last. And do not treat a million-token window as a million tokens of reliable reading; measure the effective length for your task.
Cost: the arithmetic
Prices at the time of writing, per million tokens, from the pricing page:
| Model | Input | 5-min cache write | Cache read | Output |
|---|---|---|---|---|
Claude Haiku 5.5 (claude-haiku-5-5), prompt up to 100K tokens |
$0.10 | $0.125 | $0.01 | $0.50 |
| Claude Haiku 5.5, prompt over 100K tokens | $0.50 | $0.625 | $0.05 | $2.50 |
Claude Opus 5.5 (claude-opus-5-5), any length |
$4.00 | $5.00 | $0.20 | $20.00 |
Two details in that table decide most outcomes. Haiku 5.5 has two rate cards, chosen by prompt length: a 101,000-token prompt bills every token at five times the rate of a 99,000-token one. And Opus 5.5 reads its cache at 0.05x the input price rather than the usual 0.1x, which makes cached long context unusually cheap on it.
Per question, with 40 tokens of question and 150 of answer, the lab’s economics.py gives:
| Model | Corpus | RAG (2,500 tokens) | LC, no cache | LC cached, 1 q/hour | LC cached, 120 q/hour |
|---|---|---|---|---|---|
| Haiku 5.5 | 20K | $0.0003 | $0.0021 | $0.0024 | $0.0003 |
| Haiku 5.5 | 150K | $0.0003 | $0.0754 | $0.0872 | $0.0079 |
| Opus 5.5 | 20K | $0.0130 | $0.0832 | $0.0955 | $0.0072 |
| Opus 5.5 | 150K | $0.0130 | $0.6032 | $0.6956 | $0.0332 |
| Opus 5.5 | 800K | $0.0130 | $3.20 | $3.70 | $0.16 |
Read the columns in pairs:
- Uncached long context is never competitive above a few thousand tokens. Every question pays for the corpus at full price.
- Cached long context at one question an hour costs more than uncached. The cache lives 5 minutes, refreshed by each read. If the next question arrives later, it pays the 1.25x write again and reads nothing. The
exp(−λ × 5 min)term ineconomics.pyis the share of questions that arrive to a cold cache under random arrivals. Bursty internal tools live here; the 1-hour TTL (2x write) or a keep-alive helps only if gaps are under an hour. - Cached at steady traffic, small corpora favour long context. The break-even corpus size is the RAG prompt times the input price over the read price: 2,500 × 0.10 / 0.01 = 25,000 tokens on Haiku 5.5, and 2,500 × 4 / 0.20 = 50,000 on Opus 5.5. Below it, the cached corpus is cheaper than retrieval and has no retrieval failures.
- Large corpora favour RAG even cached. At 150K tokens on Haiku 5.5 the cached read is 26 times the RAG prompt, and the long-prompt rate card applies. At 800K on Opus it is a sixth of a dollar per question.
Batch processing halves these prices for offline work, and the comparison scales with it.
Latency
Time to first token is mostly prefill: the model processes every input token before it writes one. Prefill cost grows at least linearly with prompt length and the attention part grows faster (chapter three of module A1). A 150,000-token prompt takes seconds to prefill where a 2,500-token one takes a fraction of a second. The lab measures it, and the numbers depend on load, so treat any figure as yours, not the provider’s.
Caching changes latency as well as cost. A cache read skips prefill of the cached prefix, so the second and later questions against a warm 150K-token cache start much sooner than the first. The first question after a cold period pays the full prefill and the write. If latency matters and traffic is bursty, pre-warm the cache with a max_tokens: 0 request when a session starts, as the caching chapter showed.
RAG’s latency has its own floor: embedding the question, the vector and lexical queries, and the cross-encoder, which was a few hundred milliseconds on a laptop CPU in the previous chapter. For small corpora, cached long context can be faster end to end because it skips all of that.
Making long context cacheable
Caching is a prefix match, so long context is only cheap when the corpus is byte-identical across requests and placed before everything that varies:
- Order. Tools, then system instructions, then the corpus with the breakpoint at its end, then the question. Anything per-request before the breakpoint (a timestamp, a user name, the question) makes every request a write.
- Determinism. Build the corpus text the same way every time: sorted file order, stable separators, no generated dates. The lab’s
haystack.pysorts its inputs for this reason. - Updates. Changing one document invalidates the cache from that document onwards. Put the documents that change least first, so an edit to the newest one rewrites only the tail. A corpus that changes every minute is not a caching candidate.
- Scope. Caches are per model and per workspace. Two models, or a corpus per customer, multiply the writes. A per-tenant corpus of 50,000 tokens with one question per tenant per day is the cold-cache row of the table, every time.
- Size floor. The minimum cacheable prefix on the current models is 512 tokens; below it the breakpoint is silently ignored. Not a concern for a corpus, but it explains a small test that never caches.
Hybrids
The two architectures combine in four common ways, ordered by how much they change your pipeline:
- Retrieve documents, not chunks. Use retrieval to choose the 3 to 10 relevant documents, then send them whole. Chunk-boundary failures disappear, the prompt stays at tens of thousands of tokens, and retrieval over a few hundred document summaries is easier than over a hundred thousand chunks.
- Cache the hot set. Keep the 20 most-used documents in a cached system block and retrieve from the long tail. Most questions in a support product hit a small set of policies.
- Route. Self-Route, or a cheaper heuristic: aggregation and comparison questions go to long context, lookups to RAG. A classifier on Haiku 5.5 costs a fraction of a cent.
- Search as a tool. Give the model a search tool and let it retrieve, read and search again (the agents chapter in module A2). It handles multi-hop questions that one-shot retrieval misses, at the cost of several model calls per question.
A decision rule
| Situation | Choose |
|---|---|
| Corpus under the break-even size (about 25K tokens on Haiku 5.5, 50K on Opus 5.5) and steady traffic | Cached long context; delete the retrieval pipeline |
| Corpus under a few hundred thousand tokens, many aggregation or multi-hop questions, cost tolerable | Long context, or route those question types to it |
| Corpus larger than the window, or much larger than the effective window for your task | RAG; retrieve documents rather than chunks where they fit |
| Low or bursty traffic on a large corpus | RAG: the cache will be cold most of the time |
| Corpus changes continuously | RAG, with incremental re-indexing |
| Per-tenant corpora with few questions each | RAG, unless the tenant’s session asks many questions within minutes |
The numbers in the first row move with every price change, and both architectures are only as good as their measured accuracy on your questions. Run the comparison again when either changes.
Work in labs/ai/docqa/. Every run answers the same questions with the same instructions on the same model; only the context changes. Runs are sequential so that the first call writes the cache and the rest read it.
1. How big is the corpus? Count it with the counting endpoint, for both models you will use:
ANTHROPIC_API_KEY=... uv run python - <<'PY'
import pathlib, anthropic
client = anthropic.Anthropic()
text = "\n\n".join(p.read_text() for p in sorted(pathlib.Path("corpus").glob("*.md")))
for model in ("claude-haiku-5-5", "claude-opus-5-5"):
n = client.messages.count_tokens(model=model, system=text,
messages=[{"role": "user", "content": "x"}]).input_tokens
print(f"{model}: {n:,} tokens, {len(text):,} characters")
PY2. Build the haystacks. Create haystack.py. It wraps every file in <document> tags, takes ATLAS lessons in sorted order as filler up to a token target, and puts the five corpus files as one block at a chosen depth.
"""Place the five corpus files at a chosen depth inside filler documents, up to a target size."""
import argparse, pathlib, anthropic
MODEL = "claude-haiku-5-5"
FILLER = pathlib.Path("../../../src/content/lessons") # real, technical, about other systems
client = anthropic.Anthropic()
def count(text):
return client.messages.count_tokens(model=MODEL, system=text,
messages=[{"role": "user", "content": "x"}]).input_tokens
def wrap(path):
return f'<document source="{path.name}">\n{path.read_text()}\n</document>'
ap = argparse.ArgumentParser()
ap.add_argument("--tokens", type=int, default=150_000, help="0 for the corpus alone")
ap.add_argument("--depth", type=float, default=0.5, help="0 puts the corpus first, 1 last")
a = ap.parse_args()
corpus = "\n\n".join(wrap(p) for p in sorted(pathlib.Path("corpus").glob("*.md")))
n_corpus, picked = count(corpus), []
if a.tokens:
filler = [wrap(p) for p in sorted(FILLER.glob("*.mdx"))] # sorted: the same bytes every build
sample = "\n\n".join(filler[:20])
budget = (a.tokens - n_corpus) * len(sample) / count(sample) # characters of filler to add
for d in filler:
if sum(map(len, picked)) + len(d) > budget:
break
picked.append(d)
at = round(a.depth * len(picked))
text = "\n\n".join(picked[:at] + [corpus] + picked[at:])
name = f"haystack-{a.tokens // 1000}k-d{round(a.depth * 100)}.txt" if a.tokens else "haystack-corpus.txt"
pathlib.Path(name).write_text(text)
print(f"{name}: corpus ({n_corpus:,} tokens) after document {at} of {len(picked)}; total {count(text):,} tokens")ANTHROPIC_API_KEY=... uv run haystack.py --tokens 0
for d in 0 0.25 0.5 0.75 1; do ANTHROPIC_API_KEY=... uv run haystack.py --tokens 150000 --depth $d; donehaystack-corpus.txt is the corpus alone, about 20,000 tokens. The five haystack-150k-d*.txt files each total close to 150,000 tokens (within a few per cent, because the filler is cut at document boundaries), with the corpus after document 0, about 15, 30, 45 and 60 of roughly 60 lessons. Every file is over 100,000 tokens, so every request against it is billed on Haiku 5.5’s long-prompt rate card. Counting is free, so rebuild as often as you like; the output is byte-identical each time, which is what makes it cacheable.3. The runner. Create long_context.py. With --haystack it puts the file in a cached system block; without it, it runs RAG through struct-rerank and A1’s build_prompt. It streams to time the first token, prices every call from usage, and saves the rows.
"""Answer questions with a whole haystack in context, or with RAG; time, price and save each call."""
import argparse, json, pathlib, re, statistics, time, anthropic
from qa import build_prompt
from retrieve_v2 import PIPELINES
ABSTAIN = "The passages do not contain the answer."
RULES = ("Answer the question using only the documents provided. Answer in one or two sentences and "
f"name the source file. If the documents do not contain the answer, reply exactly: {ABSTAIN}")
# $ per 1M tokens: input, 5-minute cache write, cache read, output. Check the pricing page.
PRICE = {"claude-haiku-5-5": {"short": (0.10, 0.125, 0.01, 0.50), "long": (0.50, 0.625, 0.05, 2.50)},
"claude-opus-5-5": {"short": (4.00, 5.00, 0.20, 20.00), "long": (4.00, 5.00, 0.20, 20.00)}}
norm = lambda s: re.sub(r"\s+", " ", s).strip().lower()
client = anthropic.Anthropic()
def cost(model, u):
w, r = u.cache_creation_input_tokens or 0, u.cache_read_input_tokens or 0
p = PRICE[model]["long" if u.input_tokens + w + r > 100_000 else "short"] # Haiku 5.5's two cards
return (u.input_tokens * p[0] + w * p[1] + r * p[2] + u.output_tokens * p[3]) / 1e6
def ask(model, system, question):
# Haiku 5.5: thinking off (allowed at effort high or below), no server-side fallback.
# Opus 5.5: thinking cannot be disabled; low effort keeps it short; fallback on a refusal.
extra = ({"thinking": {"type": "disabled"}} if model.startswith("claude-haiku") else
{"betas": ["server-side-fallback-2026-07-01"], "fallbacks": "default"})
t0, ttft = time.perf_counter(), None
with client.beta.messages.stream(model=model, max_tokens=1024, output_config={"effort": "low"},
system=system, messages=[{"role": "user", "content": question}],
**extra) as stream:
for _ in stream.text_stream:
if ttft is None:
ttft = time.perf_counter() - t0
m = stream.get_final_message()
text = ("(declined)" if m.stop_reason == "refusal"
else "".join(b.text for b in m.content if b.type == "text"))
return text, ttft or time.perf_counter() - t0, m.usage
ap = argparse.ArgumentParser()
ap.add_argument("--model", default="claude-haiku-5-5", choices=list(PRICE))
ap.add_argument("--haystack", help="a file from haystack.py; omit to run RAG")
ap.add_argument("--questions", default="questions-v2.json")
ap.add_argument("--limit", type=int)
a = ap.parse_args()
QS = json.load(open(a.questions))[: a.limit]
if a.haystack:
system = [{"type": "text", "text": RULES},
{"type": "text", "text": pathlib.Path(a.haystack).read_text(),
"cache_control": {"type": "ephemeral"}}] # breakpoint at the end of the corpus
rows = []
for i, x in enumerate(QS, 1):
t0 = time.perf_counter()
if a.haystack:
retrieve_s = 0.0
text, ttft, u = ask(a.model, system, x["q"])
else:
chunks = PIPELINES["struct-rerank"](x["q"], 5)
retrieve_s = time.perf_counter() - t0
text, ttft, u = ask(a.model, [{"type": "text", "text": RULES}], build_prompt(x["q"], chunks))
rows.append({"q": x["q"], "gold": x["answer"], "answer": text, "correct": None,
"gold_in_answer": norm(x["answer"]) in norm(text), "retrieve_s": retrieve_s,
"ttft": ttft, "cost": cost(a.model, u), "read": u.cache_read_input_tokens or 0,
"write": u.cache_creation_input_tokens or 0, "input": u.input_tokens})
r = rows[-1]
print(f"{i:>2} {'G' if r['gold_in_answer'] else '.'} first token {retrieve_s + ttft:5.2f}s "
f"in {r['input']:>6} write {r['write']:>7} read {r['read']:>7} ${r['cost']:.4f} {text[:50]!r}")
tag = f"{pathlib.Path(a.haystack).stem if a.haystack else 'rag'}-{a.model}-{pathlib.Path(a.questions).stem}"
json.dump(rows, open(f"lc-{tag}.json", "w"), indent=1, ensure_ascii=False)
later = [r["retrieve_s"] + r["ttft"] for r in rows[1:]] or [rows[0]["retrieve_s"] + rows[0]["ttft"]]
print(f"{tag}: gold {sum(r['gold_in_answer'] for r in rows)}/{len(rows)} "
f"first call {rows[0]['retrieve_s'] + rows[0]['ttft']:.2f}s later p50 {statistics.median(later):.2f}s "
f"${sum(r['cost'] for r in rows):.4f} total, ${sum(r['cost'] for r in rows) / len(rows):.5f} per question")4. Small corpus: long context against RAG.
ANTHROPIC_API_KEY=... uv run long_context.py
ANTHROPIC_API_KEY=... uv run long_context.py --haystack haystack-corpus.txtwrite near 20,000, rows 2 to 30 show read near 20,000 and in of a few dozen tokens; gold 26 to 30 of 30, often including a question RAG missed because its chunk was not retrieved; per question about $0.0003 to $0.0004, the same as RAG, as the cost table predicted for a corpus near Haiku’s break-even. First token on the later calls is comparable to RAG’s. At this size the retrieval pipeline buys nothing you can measure.5. The haystack, and the middle. Run the 150K files, middle first:
ANTHROPIC_API_KEY=... uv run long_context.py --haystack haystack-150k-d50.txt
for d in 0 25 75 100; do ANTHROPIC_API_KEY=... uv run long_context.py --haystack haystack-150k-d$d.txt | tail -1; donewrite near 150,000 and costs about $0.09 (150,000 tokens at the long-prompt write rate of $0.625 per million); later rows read 150,000 tokens at $0.05 per million, about $0.008 each, and the summary is about $0.32 for 30 questions, against roughly $2.25 if nothing were cached. The first call’s time to first token is several times the later ones’: that is prefill of 150,000 tokens, which the cache skips. Accuracy across the five depths is usually within one or two questions of the small-corpus run, and the U-shape from Liu et al. is faint or absent on these lookups because most questions share exact tokens with their answers. Look at the rows that changed between depths: they are usually questions whose answer has a near-duplicate in the filler (another lesson’s Postgres version or port), the distractor effect from Context Rot. Write the five gold counts into RESULTS.md.6. Questions retrieval cannot answer. Four aggregation questions, marked by hand (the answer string is only a hint for the G column):
cat > questions-agg.json <<'JSON'
[
{"q": "How many chapters does module A3 of the AI Engineering course have? Count the rows of its table.", "answer": "10"},
{"q": "List every port number used by the observability stack's services and tools.", "answer": "3200"},
{"q": "Which modules, across all three courses, are at the Principal level?", "answer": "A5"},
{"q": "Which of the documents mention Supabase?", "answer": "DESIGN.md"}
]
JSON
ANTHROPIC_API_KEY=... uv run long_context.py --questions questions-agg.json
ANTHROPIC_API_KEY=... uv run long_context.py --questions questions-agg.json --haystack haystack-corpus.txtLABS.md’s ports line; O5, D5 and A5; DESIGN.md and DEPLOY.md. RAG typically gets one or two of four: it finds a chunk of the A3 table and counts only that chunk’s rows, finds DEPLOY.md’s Supabase section and misses DESIGN.md, and finds one or two of the Principal modules. Long context typically gets three or four. This is the case where the cost table’s tie becomes a decision: at this corpus size long context is no more expensive and answers a class of question that RAG cannot.7. The economics, with your numbers. Create economics.py; set RAG_PROMPT to the mean input of your RAG run and the corpus sizes to your counts from steps 1 and 2.
"""Cost per question: RAG against long context, uncached and cached, by corpus size and traffic. No API calls."""
import math
# $ per 1M tokens: input, 5-minute cache write, cache read, output. Check the pricing page.
HAIKU_SHORT = (0.10, 0.125, 0.01, 0.50) # claude-haiku-5-5, prompt up to 100K tokens
HAIKU_LONG = (0.50, 0.625, 0.05, 2.50) # claude-haiku-5-5, prompt over 100K tokens
OPUS = (4.00, 5.00, 0.20, 20.00) # claude-opus-5-5, any length
QUESTION, OUTPUT, RAG_PROMPT = 40, 150, 2_500 # tokens
def rates(model, prompt_tokens):
if model == "opus":
return OPUS
return HAIKU_LONG if prompt_tokens > 100_000 else HAIKU_SHORT
def rag(model):
i, _, _, o = rates(model, RAG_PROMPT)
return (RAG_PROMPT * i + OUTPUT * o) / 1e6
def long_uncached(model, corpus):
i, _, _, o = rates(model, corpus + QUESTION)
return ((corpus + QUESTION) * i + OUTPUT * o) / 1e6
def long_cached(model, corpus, per_hour):
"""Random arrivals: a question finds the cache cold if the previous one came over 5 minutes ago."""
i, w, r, o = rates(model, corpus + QUESTION)
p_cold = math.exp(-per_hour * 5 / 60)
return ((p_cold * w + (1 - p_cold) * r) * corpus + QUESTION * i + OUTPUT * o) / 1e6
print(f"{'model':6} {'corpus':>7} {'RAG':>8} {'LC no cache':>11} cached at 1/h 12/h 120/h 1200/h")
for model in ("haiku", "opus"):
for corpus in (20_000, 150_000, 800_000):
cached = " ".join(f"{long_cached(model, corpus, q):8.4f}" for q in (1, 12, 120, 1200))
print(f"{model:6} {corpus:>7,} {rag(model):8.4f} {long_uncached(model, corpus):11.4f} {cached}")uv run economics.pyhaiku 150,000 0.0003 0.0754 0.0872 0.0396 0.0079 0.0079 and opus 20,000 0.0130 0.0832 0.0955 0.0425 0.0072 0.0072. Compare the cached 120/h figures with the per-question costs your runs measured in steps 4 and 5; they should agree to within the output-length difference. Then find the traffic at which cached long context on your 20K corpus stops being cheaper than RAG on Haiku 5.5: change the list of rates until the cached column crosses the RAG column. It is a few questions per hour.8. Optional: the same haystack on Opus 5.5. About $2.20: the haystack run is a $0.75 write, 29 reads at $0.03 and about $0.20 of output including thinking, and the RAG run is about $0.40.
ANTHROPIC_API_KEY=... uv run long_context.py --model claude-opus-5-5 --haystack haystack-150k-d50.txt
ANTHROPIC_API_KEY=... uv run long_context.py --model claude-opus-5-5RESULTS.md should name a model and an architecture together, since the break-even depends on both.long_context.py, change the long-context call to ask(a.model, [{"type": "text", "text": f"Question {i}."}] + system, x["q"]), which puts a per-request line before the corpus, and run uv run long_context.py --haystack haystack-150k-d50.txt --limit 5. Every row now shows write near 150,000 and read 0, every row costs about $0.09 instead of $0.008, and every first token is as slow as the first call was. A long-context architecture is only as cheap as its cache hit rate, and one changed byte before the breakpoint sets it to zero. Remove the line; the next run reads from cache again on its second call.Template
# ADR-<number>: <decision in one line>
Status: proposed | accepted | superseded. Date: <date>. Decider: <role>. Author: <role>.
## 1. Context and decision needed
<The task, the corpus (tokens), the traffic (questions an hour, and when), how often the corpus changes. The decision needed, from whom, by when.>
## 2. Options
| | RAG (five chunks) | Long context (whole corpus, cached) |
|---|---|---|
| Accuracy (gold of <n>, same questions) | | |
| Aggregation questions (of <n>) | | |
| Cost per question (model, traffic) | | |
| Latency: first token | | |
Source for every cell: <run file, lab step or assumption>.
## 3. Decision
We choose <architecture> on <model>, because <two reasons from the table>.
## 4. Consequences
- Gained: <what>
- Accepted: <what it costs or can no longer do>
- Out of scope: <what this record does not decide>
## 5. How this could be wrong
<One way, and what would show it.>
## 6. Revisit when
<Corpus size, traffic, price change or accuracy drop that reopens this.>
Approved <name, date>. WORKED EXAMPLE
The support lead (or the head of engineering) writes this record for the docqa assistant; the head of engineering approves it.
ADR-001: Answer docqa questions from the cached corpus on claude-haiku-5-5. Status: proposed. Date: 23 November 2026. Decider: head of engineering. Author: support lead. Decision needed before the pipeline is next re-indexed. Out of scope: any corpus other than the five docqa files.
Context. The corpus is five files, about 20,000 tokens. Assumed: steady traffic of 120 questions an hour in working hours; the corpus changes rarely.
Options, on the same 30 questions. RAG with struct-rerank scored 24 to 28 of 30 (the lab’s printed range; write your own count here), at about $0.0003 per question, with a first token around a second including a few hundred milliseconds of retrieval. Cached long context scored 26 to 30 of 30 at about $0.0003 to $0.0004 per question, with later first tokens comparable to RAG’s. On the four aggregation questions RAG typically got one or two, long context three or four. Sources: lab steps 4 and 6, and the chapter’s cost table.
Decision. Cached long context on Haiku 5.5. Cost and latency tie at this size, and it answers aggregation questions that retrieval cannot.
Consequences. We can retire the chunker and reranker. We accept that the first call after a cold cache pays the write, and that at 150K tokens the same design costs $0.0079 per question at 120 questions an hour against $0.0003 for RAG.
How this could be wrong. If traffic falls to a few questions an hour, the cache goes cold; the 1-question-an-hour column ($0.0024 against $0.0003) would show it.
Revisit when the corpus passes 25,000 tokens on Haiku 5.5 (the break-even from the chapter), or prices change.
Approved: head of engineering, 24 November 2026.
Now you
Kilnworth, the 60-person creative and media agency in Lekki, Lagos, wants an internal assistant that answers staff questions about its brand guidelines and its archive of past campaigns for clients such as Crustwell, Owoleaf and Lumora Mobile. Questions range from lookups (‘what is the approved logo clearance?’) to aggregations (‘which past campaigns used a voice-over?’).
You do not know the corpus size or traffic, so measure or assume them: get a token count for the guidelines and archive (the counting endpoint, or an estimate from the lab’s ratio of about 70,000 characters to 20,000 tokens), state an assumed number of questions an hour, and say how often the archive grows. Reuse the lab’s cost table and economics.py. Its step 6 aggregation results come from the docqa corpus, so label them as a proxy for Kilnworth’s questions, not a measurement of them. Write the record that chooses between long context, RAG or a hybrid from the chapter. It is read by the head of production and the person who owns the tooling, who must choose before anything is built.
Self-check
An HR assistant answers employees' questions about the company handbook: 120,000 tokens across 40 policies, edited about twice a month. Traffic is 3,000 questions a day, almost all between 9:00 and 18:00, on claude-sonnet-5-5 ($2 input, $2.50 cache write, $0.10 cache read per million tokens). An internal review found that the current RAG system answers 'how many days of leave do I get if...' questions wrongly when the answer combines two policies. Which architecture do you propose?
- PAPER Lost in the Middle: How Language Models Use Long Contexts Liu, Lin, Hewitt, Paranjape, Bevilacqua, Petroni and Liang, 2023
The experiment behind step 5: one relevant document moved through a list of distractors, and the U-shaped accuracy curve. Note which models and lengths; current models flatten the curve on lookups, which is exactly what you test for. Read: sections 1 and 2 and figure 1 for the multi-document QA result; section 4 for why, and what query placement does.
- PAPER RULER: What's the Real Context Size of Your Long-Context Language Models? Hsieh et al., 2024
Why a needle test is not evidence for your task: multi-needle, tracing and aggregation tasks expose an effective context far shorter than the advertised one. Borrow its task types for your own long-context eval. Read: section 3 for the task categories; the main results table for effective length per model.
- PAPER Retrieval Augmented Generation or Long-Context LLMs? A Comprehensive Study and Hybrid Approach Li, Li, Zhang, Mei and Bendersky, 2024
A head-to-head comparison on public benchmarks, with the finding that long context wins on accuracy and RAG on cost, and a routing method that gets most of both. Published at EMNLP 2024. Read: the comparison results and the Self-Route section; the failure analysis of why RAG misses.
- PAPER NoLiMa: Long-Context Evaluation Beyond Literal Matching Modarressi et al., 2025
Removes word overlap between question and answer, and the long-context scores fall by half at 32K tokens. Read it before trusting a long-context result on questions that share tokens with their answers, like most of docqa's. Read: the introduction and the main results figure.
- POST Context Rot: How Increasing Input Tokens Impacts LLM Performance Hong, Troynikov and Huber (Chroma), 2025
Eighteen models, controlled experiments on distractors, question-answer similarity and haystack structure. The distractor results explain the questions that flip between depths in step 5.
- DOC Prompt caching Anthropic
Prefix matching, breakpoint placement, TTLs, minimum lengths and the pricing multipliers that the economics in this chapter rest on. Read the sections on what invalidates the cache and on the 1-hour TTL.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.