On this page
TLDR
Context window management is how you keep long conversations within limits without dropping critical facts. Patterns: case-facts blocks, progressive summarization, retrieval.
What you are deciding
Context is a finite working budget, not storage. When it grows, decide what stays verbatim, what is retrieved on demand, what is summarized and what is removed, and measure the budget in tokens rather than characters.
As the context grows, which content stays, which is retrieved later, and which is summarized or dropped?
What it is
The context window is the maximum token budget Claude can process in a single request. The window size differs by model, so read it from Anthropic's models overview (https://platform.claude.com/docs/en/about-claude/models/overview) on the date you use it. It is a hard boundary: a request that does not fit cannot run as sent. Managing the window is core production architecture: inefficient windowing wastes budget; strategic windowing unlocks large-scale automation.
The window applies to total input tokens, including system prompt, all messages, all tool definitions. Example: system (500) + prior conversation (5000) + current request (1000) + tool definitions (2000) = 8500 used; subtract that from the model's window to see what remains. If you're building an agent loop and messages grow unchecked, you can hit the limit at turn 12. The window doesn't reset between turns; shared budget for the entire sequence.
Three production patterns manage the window: prompt caching (90% off repeated prefix), context windowing (summarize old turns into FACTS block, drop verbose history), and streaming output (doesn't reduce tokens but improves UX during long waits). The fourth, underutilized pattern: case-facts immutability (CASE_FACTS rewritten not appended at every turn).
The most-tested anti-pattern is windowing too late. If your loop runs for 12 turns and you window at turn 11, you've wasted tokens for 10 turns. Optimal: window at turn 5 if the conversation is verbose, or preemptively at turn 3 if each turn is expensive. Also tested: context starvation in subagents. Coordinator passes 100KB to a subagent; subagent spends a large part of its own window on irrelevant context. Mitigate: subagents receive only what they need in a compact TASK_CONTEXT block.
How each certification frames it
CCA-P: How CCA-P tests context and token management
CCARP-D2-O4Optimize context windows and manage token usage
The Professional objective is to optimize context windows and manage token usage (PDF page 4, Domain 2). Anthropic's context engineering guidance treats context as a finite resource with diminishing returns, so the aim is the smallest set of high-signal content, not the largest that fits.
Measure before you trim. The token counting endpoint returns an estimate for a full request including system prompt, tools, images and PDFs, and the documentation says to recount against the model you plan to use because newer tokenizers produce different counts for the same text.
CCD-F: How CCD-F tests drift recovery and summary fidelity
CCDVF-D6-O1Context Engineering: context and memory management techniques for Claude applications, including context window management, prevention of context drift and bloat (tool output pruning, compaction), and context isolation through subagents or multi-step agentic workflows
The Developer guide names prevention of context drift and bloat, with tool output pruning and compaction, and context isolation through subagents (PDF page 7, Domain 6). Clearing old tool results is described as a light, safe form of compaction.
A summary is lossy, so test its fidelity. Build a checklist from the source of facts that must survive, compare the summary against it, and add anything missing before the old turns are discarded.
CCA-A: How CCA-A tests restart, summarize or persist
CCAOF-D3-O4Understand and manage context limitations and memory considerations (when to restart, summarize, or persist)
The Associate guide asks you to understand and manage context limitations and memory considerations: when to restart, summarize or persist (PDF page 5, Domain 3). The context limit is the amount of material Claude can work with at one time, and long conversations eventually crowd it.
Restart when the topic changes. Summarize when you must continue the same task in a new conversation. Persist what you will need again, such as standing instructions or reference documents, in Project instructions and knowledge.
How it works
Token counting is deterministic: SDK provides count_tokens() endpoint that returns exact cost before you execute. Always call on large requests. Track at every turn; when remaining <20K, window immediately.
Windowing mechanics: at turn N, extract a summary of turns 1 through N-1 into a PRIOR_CONTEXT block, drop the verbose message history, append PRIOR_CONTEXT + current turn as the new message list. Before windowing, messages = [user_msg, asst_1, tool_1, ..., asst_4, tool_4, user_5]. After windowing at turn 5, messages = [{role: "user", content: "PRIOR_CONTEXT: ...\n\nCURRENT: {turn_5}"}]. The new list is 10% the size of the old list.
Prompt caching exploits that system prompt and tool definitions don't change between turns. Mark with cache_control: {type: "ephemeral"}. On first request, full price; turns 2+ pay only 10% of cache price. Save 88% over 9 turns.
Case-facts immutability means CASE_FACTS is rewritten at every turn, never appended. Turn 1: CASE_FACTS: {customer_id, amount}\nQUESTION: .... Turn 2: CASE_FACTS: {customer_id, amount, order_found: true}\nQUESTION: ... (facts updated, not accumulated). Prevents the block from growing unboundedly. Combined with windowing: production pattern for multi-turn customer service.

Worked example: a long support case near its budget
Authored teaching example, not a bank question.
A support agent has worked one customer case for many turns. The conversation holds raw order lookups, a long troubleshooting thread and promises made to the customer, and the request is close to the model's window.
| Content | Action | Why |
|---|---|---|
| Refund promised on day two | Keep verbatim in a facts block | An unmet obligation must not be paraphrased away |
| Raw order lookup from many turns ago | Remove after extracting fields | Old tool output adds tokens without adding signal |
| Policy handbook | Retrieve on demand by identifier | Load it only when a question needs it |
| Long troubleshooting thread | Summarize | The outcome matters, the full transcript does not |
The agent continues with the same commitments in less context. Check afterwards that every open obligation in the source appears in the summary and that the new token count fits the budget.
How this decision goes wrong
Estimating tokens from characters
Looks right: A fixed ratio of characters to tokens gives a quick budget.
Why it fails: Counts vary by content and by model generation, and tools and images add tokens too. A guess can overflow the window or waste space.
Instead: Use the token counting endpoint with the model you will call, and recount when the model changes.
A summary that drops constraints
Looks right: The summary reads well and is much shorter.
Why it fails: Short summaries tend to keep the story and lose conditions, such as a promise or a customer's limit, which then get violated later.
Instead: Summarize around open obligations and check the summary against a checklist from the source before deleting turns.
Treating caching as more context capacity
Looks right: A cached prefix is cheaper, so the conversation can grow without limit.
Why it fails: The caching documentation presents caching as a cost and latency feature and defines total input as cache reads plus cache writes plus uncached input. It does not describe extra capacity.
Instead: Manage the size of the prompt itself, and use caching to cheapen a stable prefix that still fits.
Where you'll see it
200-page contract analysis with windowing
Legal team uploads 200-page contract. Without windowing, loop dies at page 15 (context exhausted). With windowing at page 10: "Pages 1-10 analyzed; risks: X, Y, Z." Claude continues fresh on pages 11-20, final turn aggregates findings. ~50% of non-windowed cost despite same work.
Long-running customer support with case-facts immutability
Loop starts CASE_FACTS = {customer_id, order_id}. Turn 2: updated = {..., refund_amount: 150}. Turn 3: {..., policy_check: "under $500, approved", manager_approval: "needed"}. Each turn rewrites (not appends). Combined with windowing at turn 5, agent runs 20+ turns without exhaustion.
Show 2 more examples
Subagent context starvation mitigation
Coordinator delegates with full 150KB case context expecting inheritance. Subagent wastes 100KB on irrelevant history. Fix: coordinator extracts a 2KB TASK_CONTEXT ("Analyze competitor pricing; they offer X, Y, Z") and passes only that. Subagent has 198K for actual research.
Prompt caching for repeated system prompt + tools
Support agent loop runs 50 times/day. System (500 tokens) + 5 tools (2000) = 2500 tokens. Normal: 50 × $0.0375 = $1.875/day. Cached: 1 uncached + 49 cached @ 10% = $0.0375 + 49 × $0.00375 = $0.221/day. 88% savings.
Code examples
from anthropic import Anthropic
client = Anthropic()
def long_agent_with_windowing(case_facts: dict, max_turns: int = 50):
messages = []
turn = 0
system_prompt = """You are a support agent. Refunds >$500 require approval."""
tools = [
{"name": "verify_customer", "description": "Check customer exists", "input_schema": {"type": "object", "properties": {}}},
{"name": "lookup_order", "description": "Find order details", "input_schema": {"type": "object", "properties": {}}},
{"name": "process_refund", "description": "Issue refund (with policy)", "input_schema": {"type": "object", "properties": {}}},
]
while turn < max_turns:
turn += 1
# WINDOWING at turn 5: drop history, keep CASE_FACTS
if turn == 5:
case_facts["prior_work"] = "Customer verified, order found."
messages = []
# CASE-FACTS IMMUTABILITY: rewrite (not append)
block = f"""CASE_FACTS:
- Customer ID: {case_facts.get('customer_id', 'N/A')}
- Order ID: {case_facts.get('order_id', 'N/A')}
- Refund Amount: ${case_facts.get('amount', 0)}
- Prior Work: {case_facts.get('prior_work', 'None')}
"""
user_message = f"{block}\nQuestion: {case_facts.get('question', 'Help')}" if turn == 1 else f"{block}\nContinue."
messages.append({"role": "user", "content": user_message})
# PRE-CHECK token count
token_count = client.messages.count_tokens(model="claude-opus-4-5", system=system_prompt, tools=tools, messages=messages)
if token_count.input_tokens > 190000:
print(f"Warning: {token_count.input_tokens} tokens; near limit.")
resp = client.messages.create(
model="claude-opus-4-5", max_tokens=1024,
system=[{"type": "text", "text": system_prompt, "cache_control": {"type": "ephemeral"}}],
tools=tools, messages=messages,
)
if resp.stop_reason == "end_turn":
return resp.content[0].text if resp.content else "Done"
messages.append({"role": "assistant", "content": resp.content})
return "Max turns exceeded."Looks right, isn't
Each row pairs a plausible-looking pattern with the failure it actually creates. These are the shapes exam distractors are built from.
The context window resets after each turn.
Cumulative across all turns.
Messages accumulate; budget shrinks. Once the conversation no longer fits the model's window, new requests fail.
Streaming reduces context window cost.
Streaming is UX, not cost.
You pay for every token, streamed or not.
Windowing loses information; only for cost reduction.
Windowing trades verbose intermediate details for critical facts.
Information not lost; summarized. Also improves accuracy via attention engineering (facts at top).
Prompt caching is free; no trade-off.
Caching requires 1024-token minimum to be worthwhile.
Short requests: caching overhead exceeds savings. Use for system + tools in loops, not one-off requests.
If you hit the context limit, increase max_tokens.
The window limit is on input, not output.
Increasing max_tokens (output budget) doesn't help. Window the input.
In Claude Code, run /clear to reclaim context - it wipes everything including your CLAUDE.md and memory.
/clear wipes the conversation but preserves CLAUDE.md and memory files.
It does not delete your project instructions. To shrink an ongoing thread without losing it, use /compact (summarize) instead of /clear (wipe).
Side-by-side
| Aspect | Large window | Smaller window | Streaming | Caching |
|---|---|---|---|---|
| Total budget | Set by the model (read the models overview) | Set by the model (read the models overview) | Same as non-streaming | Cheaper reads on a cached prefix |
| Effective usage | More turns before windowing | Fewer turns before windowing | No savings; UX only | Big if repeated |
| When to use | Default; most tasks | Cost-constrained | Chat UX, long responses | Loops with fixed system/tools |
| Management | Window earlier than you must | Window sooner | Stream events; buffer | Mark ephemeral; monitor TTL |
| Cost impact | Baseline | Lower per request | Neutral; UX benefit | Reads cost a fraction of base input |
| Failure mode | Hit the limit later | Hit the limit sooner | Network drops | Cache miss on content change |
Decision tree
Single turn or a loop?
Loop likely to run >5 turns?
Repeatedly sending the same system prompt + tools?
cache_control: ephemeral. Save 90% per turn.Response is long (>5 sec wait) and user-facing?
After turn N, approaching the model's window limit?
The exam trap
Treating context as storage. Estimating the budget from character counts, summarizing without checking that open obligations survive, and counting prompt caching as extra capacity all fail. Measure tokens with the model you will call, and check each summary against a checklist taken from the source.

Question patterns
CCA-P practice questions
2 approved CCA-P questions for this topic. Tap an answer to check it, then read the rationale for every option.
An agent that browses internal documentation across a long session accumulates full tool-call outputs (entire fetched pages) in its context, and by turn 20 the agent starts giving inconsistent answers and occasionally references stale information from turn 3. What is the most direct architectural fix?
CCA-F practice questions
2 approved CCA-F questions for this topic. Tap an answer to check it, then read the rationale for every option.
Long-document extraction stalls at chunk 18 every single time, regardless of which model you use. What is happening?
CCA-A practice questions
No approved public CCA-A sample question is published for this topic yet. The worked example above is an authored teaching example.
CCD-F practice questions
2 approved CCD-F questions for this topic. Tap an answer to check it, then read the rationale for every option.
A coding agent is midway through a multi-day repository migration, tracking dozens of completed and pending steps across many turns. Per Anthropic's context-engineering guidance, which of the three context-window management techniques is best suited to this specific scenario, and why?
Frequently asked
Showing 16 of 16 questions
count_tokens() before each turn. Set a threshold as a share of the model's window; window when crossed./context for a per-category token breakdown (system prompt, tools, messages, memory) plus optimization suggestions. It shows where the budget is going so you can decide whether to /compact, trim, or start fresh./compact summarizes the current conversation to reclaim room while keeping the thread going (Claude Code also auto-compacts as you approach the limit); /clear wipes the conversation entirely. Neither deletes your CLAUDE.md or memory files - those persist across both.Sources and next steps
- Claude Certified Architect - Professional Exam Guide v1.0 (July 2026), PDF page 4, section: Domains 1 and 2, detailed objectives. Checked 2026-10-16.
- Claude Certified Developer - Foundations Exam Guide v1.0 (July 2026), PDF page 7, section: Domain 4: Debugging and Error Handling; Domain 6: Context Engineering. Checked 2026-10-16.
- Claude Certified Associate - Foundations Exam Guide v1.0 (July 2026), PDF page 5, section: Domains 3 to 7, detailed objectives. Checked 2026-10-16.
- Effective context engineering for AI agents (Anthropic engineering), section: Context as a finite resource; Compaction; Structured note-taking; Sub-agent architectures; Tool-set bloat. Checked 2026-10-16.
- Token counting (Claude API docs), section: How to count message tokens; Token counts on newer models. Checked 2026-10-16.
- Prompt caching (Claude API docs), section: Tracking cache performance: usage fields. Checked 2026-10-16.
- How can I create and manage projects? (Claude Help Center), section: Project knowledge; Project instructions. Checked 2026-10-16.
CCA-P exam guide: Domain 2, Claude Models, Prompting & Context Engineering
