What you will be able to do
- Choose between compaction on demand, compaction at a token threshold, and client-side SDK compaction
- Configure tool result clearing and thinking block clearing with triggers and keep rules
- Preview the effect of context editing with the token counting endpoint
- Weigh context saved against prompt cache hits lost, and place cache breakpoints so compaction doesn't re-cache the system prompt
1.Compaction: replacing old turns with a summary
A long agent session keeps growing until it either runs out of room or degrades well before that, as accuracy falls with length (Context limits and context rot). Compaction deals with both. It replaces the older turns with a summary Claude writes, so the task can keep going in a small active context. For conversations that regularly approach the limit, server-side compaction is the main strategy. It is in beta for Claude 4.6 and later models and Claude Mythos Preview.
| Aspect | Compaction on demand | Compaction at a token threshold | Your own summarizer (client) |
|---|---|---|---|
| Who decides when | You, by sending a request | The API, when input tokens reach the trigger you set | You |
| Code you write | A compaction loop that requests the summary and swaps it in | One parameter on your ordinary requests | The summarization call, its prompt, and the history rewrite |
| Runs in the background | Yes | No: it runs inside the request that reaches the threshold | Yes, in your own code |
| Choose it when | You must control timing, can't pause for a summary, or must keep recent turns and their thinking | You want the API to manage context inside ordinary requests | You already run a summarizer that replaces the whole history |
Use on-demand compaction wherever it's available. It is the only server option where kept turns keep their thinking on models that preserve thinking. With threshold compaction, any turns you re-insert on Fable 5.1, Opus 5.5, Sonnet 5.5 or Haiku 5.5 must have their thinking removed. Either way, compaction is an extra sampling step, and it counts toward rate limits and billing.
Client-side SDK compaction is the alternative. Server-side compaction is generally preferred over it. It runs in the TypeScript and Ruby SDKs through tool_runner with a compaction_control setting. After each response the SDK adds input_tokens + cache_creation_input_tokens + cache_read_input_tokens + output_tokens. Once that total passes context_token_threshold (100,000 by default), it injects a summary request and replaces the entire history with the summary. In the documented example, that takes the history from about 100k tokens to roughly 2–3k. A lower threshold means more frequent compactions and a smaller context. You can also set a cheaper model for writing summaries, or your own summary_prompt, as long as it wraps the summary in <summary></summary> tags.
That sum can go wrong with server-side tools. After a web search, cache_read_input_tokens can include reads from several internal calls the tool made. A real context of 63,000 tokens then shows up as 334,400, and compaction fires far too early. Check the true length with the token counting endpoint, or avoid SDK compaction in workflows that use server tools heavily. Compaction suits long multi-file tasks and research runs with measurable progress and artifacts saved outside the conversation. It's a poor fit when the task needs precise recall of early details or exact state across many variables.
Checkpoint 1 of 5· Match them up
Match each way to compact a long session with the situation it fits best
Tap a term, then the definition that fits it.
On-demand compaction is the server option that gives you control over timing and keeps recent turns with their thinking. With threshold compaction, the API decides when to compact inside a normal request. With a client summarizer, you write and run the summarization yourself, and SDK compaction automates that through tool_runner and compaction_control.
“Your application needs to control when compaction happens, can't pause while a summary is written, or must keep recent turns and their thinking”Source: platform.claude.com
Checkpoint 2 of 5· Check yourself
A TypeScript agent uses tool_runner with compaction_control at the default threshold and calls web search heavily. Compaction keeps firing after a few turns, even though the conversation itself is only about 60k tokens. What is the most likely cause?
With server-side tools, cache_read_input_tokens can include reads from several internal calls. That inflates the SDK's sum, so compaction fires too early. Cached tokens do count toward the window, so the problem is the inflated sum, not caching itself. Measure the real length with the token counting endpoint, or avoid SDK compaction in workflows that rely heavily on server tools.
“the cache_read_input_tokens value includes accumulated reads from multiple internal API calls made by the server-side tool, not your actual conversation context”Source: platform.claude.com
2.Context editing: clearing tool results and thinking by rule
Context editing works by removal, not summarization. You set rules, and once a threshold is crossed the API clears specific content before the prompt reaches Claude. There are two server-side strategies. You can configure each one on its own or combine them.
Tool result clearing (clear_tool_uses_20250919) is meant for agents that make heavy use of tools. A file Claude read twenty turns ago has usually done its job already. When the trigger fires, the API clears the oldest tool results first, in chronological order, and puts placeholder text in each one's place. Set clear_tool_inputs to true to also clear the tool call parameters.
context_management={
"edits": [
{
"type": "clear_tool_uses_20250919",
# Trigger clearing when threshold is exceeded
"trigger": {"type": "input_tokens", "value": 30000},
# Number of tool uses to keep after clearing
"keep": {"type": "tool_uses", "value": 3},
# Optional: Clear at least this many tokens
"clear_at_least": {"type": "input_tokens", "value": 5000},
# Exclude these tools from being cleared
"exclude_tools": ["web_search"],
}
]
},Thinking block clearing (clear_thinking_20251015) controls thinking from earlier assistant turns through keep. Use {type: "thinking_turns", value: N} to keep the last N turns, or "all" to keep everything. If you don't set it, the default follows the model: Opus 4.5+, Sonnet 4.6+, Haiku 5.5+ and the Fable and Mythos models keep all turns, while older Opus, Sonnet and Haiku models keep only the last turn.
Your stored history stays complete. On Fable 5.1, Opus 5.5, Sonnet 5.5 and Haiku 5.5, server-side context management never invalidates thinking blocks. Editing earlier turns yourself on the client can invalidate the thinking in every later assistant turn. Clearing also works with the memory tool: when context nears the clearing threshold, Claude gets an automatic warning and can write what matters to memory files before the results disappear. To see the effect before turning a rule on, pass the same context_management to the token counting endpoint. It returns the count after clearing next to the original.
{
"input_tokens": 25000,
"context_management": {
"original_input_tokens": 70000
}
}Checkpoint 3 of 5· Check yourself
Your Opus 5.5 coding agent reads dozens of large files, and those old file reads are crowding the window. The web search results it gathered must stay word for word, and you don't want any thinking blocks invalidated. Which setup fits?
Tool result clearing removes the oldest tool results on the server. exclude_tools protects the web_search results, and on Opus 5.5 server-side context management never invalidates thinking. Compaction would summarize the search results instead of keeping them word for word. Thinking clearing doesn't touch tool results. Editing earlier turns on the client can invalidate the thinking in every later assistant turn.
“Tool result clearing - Best for agentic workflows with heavy tool use where old tool results are no longer needed”Source: platform.claude.com
Sources3
3.Context management versus the prompt cache
Prompt caching reuses an identical prompt prefix (Prompt caching). Compaction and context editing both change the prompt partway through, and cache hits stop at the first change. Each clearing or compaction saves context and costs you a cache write. That trade only pays off when the edit is big enough to justify it.
| Action | Cache effect | How to tune it |
|---|---|---|
| Tool result clearing | Invalidates cached prefixes when content is cleared; cache write on each clear | Set clear_at_least so every invalidation removes enough tokens to justify it |
| Thinking block clearing | Kept blocks preserve the cache; clearing invalidates it at the clearing point | Set keep: "all" to favour cache hits, a small thinking_turns value to favour window space |
| Compaction | The summary is new content that must be written to the cache | Put a cache_control breakpoint at the end of the system prompt so it stays cached separately |
Compaction shows why breakpoint placement matters. Without a breakpoint of its own, the system prompt is invalidated along with everything else when compaction rewrites the conversation, and has to be re-cached alongside the summary. With a cache_control breakpoint on the last block of the system prompt, the system prompt is still read from cache after compaction, and only the summary is written as a new entry.
The same rule applies to any request with a large fixed preamble. Put static content first (tool definitions, system instructions, examples) and mark the end of it with cache_control. Take a support agent with a 6,000-token policy prompt and a user message that changes every time. The breakpoint goes on the final block of the policy text. A breakpoint on the user message would create a new cache entry that no later request matches. Putting one on every block doesn't help either, because the changing part can never be a shared prefix.
Checkpoint 4 of 5· Check yourself
After a teammate adds clear_thinking_20251015 with keep set to {type: "thinking_turns", value: 1} to a long Opus 5.5 session, the window stays smaller but cache hits drop and input costs go up. What explains this, and what is the trade-off?
Kept thinking blocks preserve the cache, and clearing them invalidates it from the clearing point onward. So the keep value is a choice between cache performance and window space. Clearing thinking is not free. Server-side context management never invalidates thinking on Opus 5.5, and the client is supposed to keep its full history.
“When thinking blocks are cleared, the cache is invalidated at the point where clearing occurs.”Source: platform.claude.com
Checkpoint 5 of 5· Exam question
A team is building a customer support agent that sends a 6,000-token static system prompt containing product policies and tone guidelines, followed by a short per-request user message that always differs. Both latency and cost matter, and the team wants to maximize the prompt cache hit rate across thousands of daily requests. Where should they place the cache_control breakpoint?
Correct answer: A — On the final block of the static system prompt, so the stable policy and tone text is cached and reused across every request
- A. Correct. Cache breakpoints should mark the last block of content that stays identical across requests. Placing the breakpoint at the end of the static system prompt caches that stable prefix and lets it be reused on every request regardless of the changing user message.
- B. Incorrect. Placing the breakpoint on content that changes every request means the cached prefix hash never matches a prior write, so no cache hit occurs and the write cost is paid repeatedly.
- C. Incorrect. Skipping the system prompt leaves the largest, most stable portion of the request uncached, forfeiting most of the available savings even if the tools array is cached.
- D. Incorrect. Adding a breakpoint on the changing user message does not create a cache hit for that block and only adds unnecessary cache-write overhead without improving the hit rate.
Practise it for real
Measure how much context a tool result clearing rule would save, before you turn it on in production
1.Take a long agent transcript and call the token counting endpoint on it with no context_management.
Why: This gives the baseline input size the agent sends now.
You should see: An input_tokens value for the full history.
2.Call client.beta.messages.count_tokens again with betas=["context-management-2025-06-27"] and a clear_tool_uses_20250919 edit with an input_tokens trigger and a tool_uses keep value.
Why: The endpoint previews the prompt after clearing without running a real request.
You should see: A response with input_tokens after clearing and context_management.original_input_tokens before it.
3.Subtract the two values, and compare the savings with the clear_at_least you plan to set.
Why: Each clear invalidates the cached prefix, so a clear should remove enough tokens to be worth a cache write.
You should see: A savings figure that tells you whether to raise the trigger or the minimum clear size.
Stuck? Get a nudge
If the savings are small compared with your cached prefix, raise clear_at_least so the API clears less often and in bigger chunks.
Sources
(4)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Compaction replaces the older turns of a conversation with a summary that Claude writes on the server”
↩︎ Compaction: replacing old turns with a summary“Use on-demand compaction wherever it is available.”
↩︎ Compaction: replacing old turns with a summary“The API, when input tokens reach the trigger you set”
↩︎ Compaction: replacing old turns with a summary“Your application needs to control when compaction happens, can't pause while a summary is written, or must keep recent turns and their thinking”
↩︎ Checkpoint - 2.
“Compaction requires an additional sampling step, which contributes to rate limits and billing.”
↩︎ Compaction: replacing old turns with a summary“When compaction occurs, the summary becomes new content that needs to be written to the cache.”
↩︎ Context management versus the prompt cache“To maximize cache hit rates, add a cache_control breakpoint at the end of your system prompt.”
↩︎ Context management versus the prompt cache - 3.
“Client-side SDK compaction - An SDK-based alternative for summary-based context management (server-side compaction is generally preferred)”
↩︎ Compaction: replacing old turns with a summary“Available in TypeScript and Ruby SDKs when using tool_runner.”
↩︎ Compaction: replacing old turns with a summary“A lower threshold means more frequent compactions with smaller context windows.”
↩︎ Compaction: replacing old turns with a summary“Use the token counting endpoint to get accurate context length”
↩︎ Compaction: replacing old turns with a summary“Tasks requiring precise recall of early conversation details”
↩︎ Compaction: replacing old turns with a summary“When activated, the API automatically clears the oldest tool results in chronological order.”
↩︎ Context editing: clearing tool results and thinking by rule“Your client application maintains the full, unmodified conversation history.”
↩︎ Context editing: clearing tool results and thinking by rule“server-side context management never invalidates thinking blocks”
↩︎ Context editing: clearing tool results and thinking by rule“Claude receives an automatic warning to preserve important information”
↩︎ Context editing: clearing tool results and thinking by rule“The token counting endpoint supports context management, allowing you to preview how many tokens your prompt will use after context editing is applied.”
↩︎ Context editing: clearing tool results and thinking by rule“Invalidates cached prompt prefixes when content is cleared.”
↩︎ Context management versus the prompt cache“Use the clear_at_least parameter to ensure a minimum number of tokens is cleared each time.”
↩︎ Context management versus the prompt cache“Configure the keep parameter based on whether you want to prioritize cache performance or context window availability.”
↩︎ Context management versus the prompt cache“When thinking blocks are cleared, the cache is invalidated at the point where clearing occurs.”
↩︎ Exam trap 1“the cache_read_input_tokens value includes accumulated reads from multiple internal API calls made by the server-side tool”
↩︎ Exam trap 2“the cache_read_input_tokens value includes accumulated reads from multiple internal API calls made by the server-side tool, not your actual conversation context”
↩︎ Checkpoint“Tool result clearing - Best for agentic workflows with heavy tool use where old tool results are no longer needed”
↩︎ Checkpoint“When thinking blocks are cleared, the cache is invalidated at the point where clearing occurs.”
↩︎ Checkpoint - 4.
“Place static content (tool definitions, system instructions, context, examples) at the beginning of your prompt.”
↩︎ Context management versus the prompt cache“Mark the end of the reusable content for caching using the cache_control parameter.”
↩︎ Context management versus the prompt cache