Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← FoundationsAI guideIntermediate#foundations#context#caching#long-context
Frame · ai-engineering / foundations / 04-context-windows-and-prompt-caching.mdGuide 004 / 103

Context windows, context engineering and prompt caching

The context window is the total number of tokens a model can consider in one request: system prompt, tool definitions, conversation history, documents, and the output it generates. In 2026 a million tokens is a normal ceiling for frontier models, which tempts people to stuff everything in. The skill that matters is the opposite one: choosing the smallest set of tokens that gets the job done, and making the repeated parts cheap with caching.

Why it matters

Three forces push against "just use the whole window". Cost scales with input tokens on every call. Latency scales too, because prefill time grows with prompt length. And quality can degrade: research such as "Lost in the Middle" showed models use information at the start and end of a long context better than information buried in the middle, and Anthropic's context engineering guide describes "context rot", where recall gets less reliable as the window fills. Long context is a powerful tool, not a substitute for retrieval and curation.

How it works

Everything in the request shares one budget. Anthropic's docs spell this out: the system prompt, every message (including tool results, images and documents), tool definitions and the output all count, so a 128K response in a 1M window leaves 872K for input. Window sizes differ per model, so read the model table rather than assuming. Anthropic lists 1M windows for its current Opus and Sonnet generations at standard pricing, with some older models at 200K. Google's Gemini docs say many Gemini models offer 1M or more tokens.

Context engineering

Anthropic frames context engineering as curating the optimal set of tokens at inference time, not just writing a good prompt. The practical patterns:

  • Keep system prompts specific but not brittle. Explain the goal and constraints, not a hundred if-then rules.
  • Keep tools few, non-overlapping and token-efficient. Every tool description is paid for on every call.
  • Load data just in time. Give the model identifiers (file paths, document ids) and a tool to fetch them, instead of preloading everything.
  • Compact long histories. Summarize older turns and drop stale tool results.
  • Use sub-agents with clean windows for deep work, and return only a condensed summary to the main thread.
Rendering diagram…

Prompt caching

Prompt caching lets the provider reuse the processed state of a prompt prefix it has seen recently. The rule is prefix matching: the cached part must be byte-identical and at the start of the request. So order your request from most stable to least stable: tools, system prompt, long reference documents, then history, then the new user message.

Providers expose it differently:

  • Anthropic: you mark breakpoints with cache_control: {"type": "ephemeral"}. The default lifetime is 5 minutes with a 1-hour option. Cache reads are billed at roughly a tenth of base input price, and writes carry a premium (1.25x for the 5-minute TTL, 2x for 1 hour, per the pricing multipliers in the docs). The response reports cache_creation_input_tokens and cache_read_input_tokens.
  • Google Gemini: implicit caching is on by default for Gemini 2.5 and newer, with no guaranteed saving; explicit caching lets you create a named cache with a TTL (default 1 hour) and pay for storage. There are minimum token thresholds per model.
  • OpenAI applies automatic caching to repeated prefixes on supported models.

Reference architecture

A multi-turn assistant with a large stable prefix benefits most. The first call writes the cache, later calls inside the TTL read it.

Rendering diagram…

Code

This Python example caches a long product manual in the system prompt using the Anthropic SDK, then asks two questions and prints the cache counters.

import anthropic

client = anthropic.Anthropic()
manual = open("product_manual.md").read()  # tens of thousands of tokens

system = [
    {"type": "text", "text": "You answer questions using only the manual below. Cite section names."},
    {"type": "text", "text": manual, "cache_control": {"type": "ephemeral"}},
]

def ask(question: str):
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=512,
        system=system,
        messages=[{"role": "user", "content": question}],
    )
    u = response.usage
    print(f"write={u.cache_creation_input_tokens} read={u.cache_read_input_tokens} fresh={u.input_tokens}")
    return response.content[0].text

ask("How do I reset the device to factory settings?")
ask("What does the amber status light mean?")

On the second call you should see a large read and a small fresh count. If you see a second write instead, something in the prefix changed: a timestamp in the system prompt is the classic culprit.

Trade-offs and pitfalls

  • Cache busting. Dynamic values (dates, user names, request ids) placed early in the prompt break every cache hit. Move them to the end.
  • Write premium. If a prefix is rarely reused within the TTL, caching costs more than it saves. Measure hit rates.
  • Minimum sizes. Small prompts below the provider minimum are not cached at all.
  • Tool and parameter changes. On Anthropic, changing tool definitions or tool_choice invalidates cached blocks after that point.
  • Long context versus RAG. Stuffing a whole corpus can work for a few hundred pages with caching, but retrieval scales further and is easier to audit. Many systems combine both.
  • Position effects. Put the most important instructions at the start or end, and repeat the critical constraint near the question for very long prompts.
  • Output reservation. Leave room for the answer, especially with reasoning models that use output budget for thinking.

Checklist

  • You know the exact window and max output for each model you use.
  • Requests are ordered stable-first so the prefix can be cached.
  • No timestamps or per-request ids appear before the cache breakpoint.
  • Cache read and write tokens are logged and the hit rate is on a dashboard.
  • Long histories are compacted past a token threshold.
  • Large corpora go through retrieval, not blind stuffing.
  • Tool catalogs are pruned to what the task needs.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.