Claude Code context: stop slow, costly sessions
Every turn re-sends your whole context, so a long session slows down and costs more. Read /context, cut the fixed tax, then clear and compact with intent.
How to stop a long Claude Code session getting slow and expensive
A long Claude Code session gets slow and expensive because every turn re-sends the whole context, and that context only grows. The fix is hygiene in a fixed order. Run /context to see what is filling the window, cut the items you pay for on every request, then use /clear between unrelated tasks and /compact with an instruction inside one long task. Work in continuous stints, because a cold prompt cache turns a cheap read into a full re-write of everything you have said.
Why the meter runs at all is answered in the token meter behind an agent session.
Read /context before you change anything
Do not guess what fills the window. Claude Code will tell you.
/context [all] draws current context usage as a colored grid, with optimization suggestions for context-heavy tools and memory bloat; all expands the per-item breakdown in fullscreen mode. Read the result as five buckets.
- The system prompt. Claude Code's own harness instructions. Fixed for the session.
- Tool definitions. The schema for every tool the agent can call, including every connected MCP (Model Context Protocol) server.
- Memory files.
CLAUDE.mdand auto memory, loaded at session start. - Files and tool results. Every file read, and everything your commands printed back.
- Message history. Your turns and its replies.
The first three are a fixed tax, paid on every request for the life of the session. The last two grow. Cut the fixed tax once, at the start; manage the growing part continuously.
Two strings tell you the window is full:
Context exceeds the 200k-token limit by 94k tokens — run /compact or /clear to continue.
Context is 94k tokens past the 200k-token compaction window — run /compact to reduce usage.The first is a hard limit, and the request is refused; the matching API (application programming interface) error reads Prompt is too long. The second is a compaction window, which can sit below the model's real context window on a 1 million token model. Requests still succeed past it, so that one is a warning rather than a refusal.
On a paid plan, /usage adds the other half, flagging behaviors such as long context or cache misses and attributing recent usage to individual skills, subagents and MCP servers.
CLAUDE.md is a permanent tax, so keep it lean
Your CLAUDE.md is loaded into context at session start and stays there. If it holds a detailed deployment procedure, those tokens are present while you fix a typo in a test file. Anthropic's guidance is to include only essentials and keep the file under 200 lines.
Move procedures into skills. A skill loads only when invoked, so a workflow you run twice a week costs nothing on the other days. Skills have their own budget after a compaction: bodies are re-injected, capped at 5,000 tokens per skill and 25,000 in total, oldest dropped first. Truncation keeps the start of the file, so put the most important instructions near the top of SKILL.md.
What survives a compaction decides where an instruction belongs.
- The system prompt and output style are unchanged, because they are not part of message history.
- The project-root
CLAUDE.md, unscoped rules, and auto memory are re-injected from disk. - A rule with
paths:frontmatter is lost until a matching file is read again. - A nested
CLAUDE.mdin a subdirectory is lost until a file in that subdirectory is read again. - Hooks are unaffected, because a hook runs as code and never enters context.
So a rule you depend on belongs in the project-root CLAUDE.md: Claude Code clears older tool outputs first and then summarizes, so instructions from early in the conversation may be lost. Edit memory with /memory. Claude Code holds the copy it loaded at session start, so a mid-session trim keeps the prompt cache and does not apply until the next /clear, /compact, or restart.
/clear between tasks, /compact inside one
These two look interchangeable and cost very different amounts.
/clear [name] starts a new conversation with empty context. It sends no request, so it costs nothing. Pass a name to label the previous conversation in the /resume picker; /reset and /new are aliases. Use it the moment you switch to an unrelated task, because the old task would otherwise be re-sent, and re-billed, on every message of the new one.
/compact [instructions] frees up context while continuing the same conversation: it summarizes the history so far and replaces it. Use it inside one long task, where you still need continuity.
Always give /compact an instruction. A bare /compact summarizes against a default prompt that does not know which part of the work you still need. An instructed one keeps it:
/compact focus on the auth bug fix
/compact keep only the plan and the diffIf you compact for the same reason every time, put a standing instruction in your project's CLAUDE.md under a # Compact instructions heading. In a new session /compact prints Not enough messages to compact., which only means there is no history yet.
Two costs get confused here. The summarization request shares your prefix, so it reads the existing cache rather than reprocessing the history, and most of its time goes to generating the summary. Compacting a large context is still a large request, because the conversation being summarized is the input. The turn after compaction is not the slow part: it rebuilds the cache for a much shorter prompt.
Two cheaper commands exist. /rewind [description] rolls back code and conversation to a checkpoint; for a path you want to abandon entirely it beats compacting, because it truncates back to a prefix that is already cached. /recap appends a summary as command output instead of replacing history, so the cached prefix stays intact.
Automatic compaction firing over and over prints this:
Autocompact is thrashing: the context refilled to the limit...Compaction succeeded, but a file or tool output refilled the window several times in a row, so Claude Code stopped retrying. Recover by reading the oversized file in line ranges, running /compact with a focus that drops the large output, moving that work to a subagent, or /clear if the earlier conversation is done.
MCP servers are fixed overhead
Every MCP server you connect adds to every request for the whole session. You pay whether or not you call it.
Claude Code softens this. MCP tool definitions are deferred by default, so only tool names enter context until Claude uses a specific tool. Run /context to see what your servers really cost, and /mcp disable <name> to drop one you will not use today. If you run your own MCP servers on a VPS, the same arithmetic limits how many tools one server should expose.
Do this at the start of a session. While definitions stay deferred, connecting or disconnecting a server only appends to the conversation, and the cache survives. Where definitions load into the prefix instead, because tool search is off or a server is exempt from deferral, the same change makes the next request re-read everything.
Filter verbose tool output before it enters context
A tool result is input, and input is re-sent on every later turn. A test run that dumps 20,000 tokens of output is not a one-time cost: you pay for it again on every turn until it leaves the window.
Filter at the source. A hook that reduces a test run to its failures before Claude sees it turns that wall of output into a few hundred tokens, on this turn and on every resend of it:
npm test 2>&1 | grep -E "FAIL|Error:" | head -40Hooks never enter context themselves, because they run as code. Do this for any tool whose output runs past a screen. The same logic covers a 3,000-line file: ask for the line range you need, because the whole file stays in the window once it arrives.
Scope what the agent reads, and delegate the noisy work
A prompt that names the file and the symptom reads that file. An open request to tidy the project reads whatever the agent decides is relevant, and every one of those reads stays in the window.
Delegate verbose work to a subagent. Test runs and log processing both consume real context; a subagent keeps that output in its own window and returns only a summary. The tradeoff: a subagent builds its own cache with no hits on the first call, and uses the five-minute cache lifetime even on a subscription. Delegation reliably protects your main context. It does not always lower total tokens.
The cache clock: work in stints
Prompt caching is what makes the resend affordable: 0.1x the base input rate to read the prefix, against 1.25x to write it, or 2x to write it on the one-hour lifetime. Each use refreshes the entry at no extra cost, so the clock runs from last use.
Which lifetime you get depends on how you authenticate, which is where a blanket "your cache expires after five minutes" goes wrong.
- On a Claude subscription, Claude Code requests the one-hour lifetime automatically.
- Once you are past your plan's limit and drawing on usage credits, you are billed for that usage, so it drops back to five minutes.
- On an API key or a cloud provider, it stays at five minutes.
ENABLE_PROMPT_CACHING_1H=1opts into the one-hour lifetime, andFORCE_PROMPT_CACHING_5M=1forces it back down.
The rhythm advice is the same either way: work in continuous stints, because an idle gap past the lifetime makes your next turn re-write the whole accumulated prefix. A detached Claude Code session in tmux costs nothing while idle, and the warm cache is what the idle time gives up.
Some actions throw the cache away while you are still working: switching models, changing effort level, turning on fast mode, connecting or disconnecting an MCP server, enabling or disabling a plugin, denying an entire tool, compacting, and upgrading Claude Code. /model is the usual surprise, because each model has its own cache, so the next request reads the entire history with no cache hits even though the content is identical.
Editing files, editing CLAUDE.md, invoking skills and commands, running /recap, rewinding, and spawning a subagent all keep the cache. It is scoped to one machine and one directory, so two sessions in different directories miss each other's cache.
To see whether caching works, read current_usage. cache_creation_input_tokens was written at the cache write rate; cache_read_input_tokens was served at roughly a tenth of the standard input rate. A high read-to-creation ratio is healthy. If creation stays high turn after turn, something in your prefix keeps changing.
Does a bigger context window fix this?
Partly. Several current models support a 1 million token context window, and compaction works the same way at the larger limit. The economics do not change, because the full prompt is still re-sent and still billed on every turn. A bigger window decides when you are forced to act; hygiene decides the cost. If the bill is the problem rather than the ceiling, which Claude plan fits the way you work decides whether you are spending dollars or plan allowance.
Context editing and compaction in the API are different things
If you are building your own agent on the Messages API, no slash commands exist and you implement this yourself. Two server-side features do the job, and they are not the same feature.
Context editing selectively clears specific content from conversation history as it grows, replacing each cleared result with placeholder text so Claude knows something was removed. It is a beta: send anthropic-beta: context-management-2025-06-27 and configure strategies under context_management.edits. clear_tool_uses_20250919 clears tool results, and clear_thinking_20251015 manages thinking blocks. Its trigger defaults to 100,000 input tokens, keep to the last 3 tool uses, and clear_tool_inputs to false, so inputs stay and only results go.
Compaction generates a summary and replaces the full conversation history with it. It is also a beta: send anthropic-beta: compact-2026-01-12 and use the edit type compact_20260112. The trigger defaults to {"type": "input_tokens", "value": 150000}, and the value must be at least 50,000.
Compaction has one handoff rule that quietly breaks agents. The response begins with a compaction content block holding the summary, followed by the normal text block. You must pass that block back on later requests, and the API then drops every content block before it. In practice: append the whole of response.content, not only the text.
Anthropic's documentation calls server-side compaction the primary strategy for managing context in long-running conversations, and context editing the option for finer control over what gets cleared. Check model support first. The current Opus, Sonnet and Fable models support compaction; claude-haiku-4-5 does not, and the compaction page carries the live list. Neither beta drives Claude Code's own /compact, which its documentation describes as a one-off summarization request the client sends.
FAQ
Why does my Claude Code session get slower and more expensive the longer it runs?
Because the whole conversation is sent again on every turn, so a one-line question in a session that has been open all day carries the entire day with it. Prompt caching keeps that cheap while the cache is warm, at 0.1x the base input rate for a read; once a turn misses the cache, the same prefix is re-written at 1.25x. Run /context to see what is filling the window, and read what a Claude Code session bills you for for the mechanism.
What is the difference between /clear and /compact in Claude Code?
/clear starts a new conversation with empty context. It sends no request, so it costs nothing, and it is the right choice between unrelated tasks. /compact keeps the same conversation and replaces the history with a summary, so it is the right choice inside one long task. Give it a focus, as in /compact keep only the plan and the diff, because the instruction decides what survives.
How do I see what is using up my Claude Code context window?
Run /context, or /context all for the full per-item breakdown. It shows the system prompt, tool definitions, MCP servers, memory files, and history as a colored grid, with suggestions for context-heavy tools and memory bloat. On a paid plan, /usage also attributes recent usage to individual skills, subagents and MCP servers.
Should I use a 1 million token context window instead of compacting?
A larger window delays the problem rather than solving it. Several current models run a 1 million token context window, Opus 4.8 and Sonnet 5 among them, and compaction behaves the same way there. Every turn still re-sends the full prompt and still bills for it, so a 400,000-token conversation is expensive whether or not it fits.
What is the difference between context editing and compaction in the Claude API?
Context editing selectively clears old content, mostly tool results, leaving placeholder text where each one was so Claude knows it was removed. Compaction generates a summary and replaces the full history with it. Anthropic's documentation calls compaction the primary strategy for long-running conversations, and positions context editing as the fine-grained option. Both are betas with their own headers, and both are separate from Claude Code's /compact.