Context windows, caching and cost control

Budgeting tokens, where long-context models fail, prompt caching, and routing work to the right model.

Intermediate about 4 h

The picture

  1. 01

    Static prefix

    instructions, docs

  2. 02

    Cache breakpoint

    reuse across calls

  3. 03

    Dynamic suffix

    the question

  4. 04

    Trim / summarise

    keep within budget

  5. 05

    Route

    cheap vs strong model

Context is a budget

Everything you send, plus everything the model writes, must fit in the context window, and every token costs money and time. Treat context like memory in a systems program: allocate it deliberately.

Long context is not perfect recall

Models tend to use information at the start and end of a long prompt better than information in the middle, and accuracy can degrade as irrelevant text is added. Put the key instruction and the key evidence where they will be seen, retrieve rather than dump, and test recall on your data.

Prompt caching

If many requests share a long, identical prefix (system prompt, tool definitions, a reference document), the provider can reuse the computed state for that prefix, which makes input tokens cheaper and first-token latency lower. The cached part must be an exact prefix, so put static content first and the changing question last.

import anthropic
client = anthropic.Anthropic()

SPEC = open("policy_handbook.txt").read()          # large and static

def ask(question: str):
    resp = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=500,
        system=[
            {"type": "text", "text": "Answer using only the handbook. Quote the clause you used."},
            {"type": "text", "text": SPEC, "cache_control": {"type": "ephemeral"}},   # cache breakpoint
        ],
        messages=[{"role": "user", "content": question}],
    )
    u = resp.usage
    print("cache write", u.cache_creation_input_tokens, "cache read", u.cache_read_input_tokens, "uncached input", u.input_tokens)
    return resp.content[0].text

ask("What is the notice period?")        # first call writes the cache
ask("Who approves exceptions?")          # later calls read it

Check the usage fields: if cache_read_input_tokens stays at zero, something in your prefix is changing between calls (a timestamp, a re-ordered tool list).

Managing a growing conversation

def trim(messages, budget_tokens, count):
    """Keep the system prompt and recent turns; drop or summarise the middle."""
    while sum(count(m) for m in messages) > budget_tokens and len(messages) > 3:
        messages.pop(1)                    # oldest non-system turn; better: replace with a running summary
    return messages

Better strategies keep a running summary, store facts in external memory (see the agent memory topic), and pin critical instructions.

Routing

Not every request needs the strongest model. A cheap model can handle classification, extraction and easy questions, and escalate to a stronger model when its confidence is low or validation fails. Measure the quality-cost frontier on your own test set before deciding.

A cost model

def cost(in_tok, out_tok, cached_in=0, p_in=3.0, p_out=15.0, p_cached=0.30):
    """Prices in USD per million tokens: placeholders, use your provider's current rates."""
    return ((in_tok - cached_in) * p_in + cached_in * p_cached + out_tok * p_out) / 1e6

Output tokens usually cost several times more than input tokens, so shorter answers and stricter formats save more than trimming the prompt.

Common mistakes

  • Putting a timestamp or request id at the top of the system prompt and breaking the cache.
  • Filling the window because it is available.
  • Choosing a model by leaderboard instead of by cost per correct answer on your task.

Exercises

  1. Run 20 questions over a long document with and without caching and report cost and latency.
  2. Plot answer accuracy as the relevant passage moves from the start to the middle to the end of a long prompt.

You are done when you can…

  • Place a cache breakpoint correctly and verify savings from the usage fields
  • Explain why accuracy can drop for facts in the middle of a long context
  • Estimate per-request cost and propose three ways to cut it