Managing Context in Claude Code
Claude Code context is the working memory of your session: every file it has read, every command it has run, every message you have exchanged, all held in a single window the model re-reads on every turn. Manage it badly and you get slow, expensive, and occasionally wrong answers as the session drags on. Manage it well and you can run a multi-hour refactor without the assistant losing the plot. This guide covers what fills up the context window, the built-in tools for controlling it (/compact, /clear, CLAUDE.md, subagents), and the habits that keep a long Claude Code session sharp.
What "context" actually means in Claude Code
Every request Claude Code sends to the model bundles the same things: your system prompt and CLAUDE.md files, the full conversation history (your messages, the assistant's replies, every tool call and its result), and any file contents that have been read into the conversation. None of this is free. It all counts against the model's context window, and the model has to re-process the entire bundle on every single turn, not just the new message.
This is the part people miss: reading a 2,000-line file into context does not cost you once. It costs you on every subsequent turn until that content leaves the window, because the model re-reads the whole conversation each time it responds. A session that opens ten large files early on is paying a tax on every message after that, whether or not those files are still relevant.
Two things eat context fastest in practice:
- Tool output.
grepacross a big repo, a build log with a wall of warnings, agit logwith hundreds of commits, or a file read with no line range. These often return far more text than the task needed. - Long-running back-and-forth. Debugging loops where the assistant tries something, sees an error, tries again, are the most context-hungry pattern in Claude Code, because each failed attempt and its output stays in history.
Current Claude models used in Claude Code offer very large context windows (up to 1M tokens on models like Claude Opus and Claude Sonnet), so short sessions rarely brush the limit. Long agentic sessions, especially ones with heavy tool use, still fill it. Context window size is generous, not infinite.
Why context running out breaks your session
When a Claude Code session approaches its context limit, two things can happen depending on your configuration: automatic compaction kicks in, or the request fails outright with a context-length error. Neither is a great time to discover you have not thought about context management.
The subtler failure mode is quality degradation before you hit the wall. As context fills with stale tool output, old file versions, and abandoned debugging attempts, the model has to work harder to find the signal in the noise. You will see this as the assistant re-reading a file it already read, forgetting an instruction from twenty turns ago, or making an edit that conflicts with a decision made earlier in the same session. This is not the model "getting dumber." It is the same model working with a messier, more diluted input.
The practical implication: treat context the same way you would treat memory in a long-running program. Not something to fill and forget, but something to actively manage as the session grows.
The /compact and /clear commands
Claude Code ships two commands for resetting context, and they solve different problems.
/compact asks Claude to summarize the current conversation into a condensed form, then continues the session with that summary in place of the full history. Use it when:
- You are deep into a task and want to keep working, but the conversation has accumulated a lot of resolved back-and-forth (fixed bugs, completed steps, dead-end attempts).
- You want to keep the thread of what you are doing without paying to re-read every tool call that got you there.
You can also add instructions to what gets kept: telling Claude to preserve specific details ("keep the exact error messages and the file paths we touched") makes the summary more useful for what comes next, since a generic summary can drop details that turn out to matter.
/clear wipes the conversation entirely and starts fresh. Use it when:
- You are switching to a genuinely unrelated task. There is no value in carrying forward context about a database migration when you are about to debug a CSS layout issue.
- The conversation has gone sideways (repeated failed attempts, contradictory instructions) and a clean slate is faster than untangling it.
- You are about to start something where stale context is actively risky, like a payments integration test where you do not want leftover assumptions from an earlier unrelated debugging session bleeding into the model's reasoning.
A rule of thumb: /compact when you are still on the same task and want continuity, /clear when you are changing tasks and want a clean start. Reaching for /compact reflexively on every task switch is a common habit that quietly keeps irrelevant context alive across unrelated work.
Claude Code also compacts automatically as a session approaches its context limit, so you do not strictly have to manage this by hand. But automatic compaction happens at a threshold the tool decides, not at a natural breakpoint in your work, so proactively running /compact or /clear at logical stopping points gives you more control over what survives.
CLAUDE.md: persistent context that does not cost a re-read
CLAUDE.md is the mechanism Claude Code gives you to put durable project knowledge in front of the model without re-explaining it every session. It is loaded automatically at the start of a session (and Claude Code supports nested CLAUDE.md files in subdirectories for folder-specific context), so anything that belongs there does not need to be typed into chat, and does not compete with your conversation history for space in the same wasteful way repeated instructions would.
What belongs in CLAUDE.md:
- Build, test, and lint commands, so Claude does not have to rediscover them by trial and error each session.
- Project conventions: naming, file layout, which patterns to follow and which to avoid.
- Hard constraints: things that must never happen (do not touch production data, do not flip this feature flag, do not add this dependency).
- Pointers to where real documentation lives, so Claude reads authoritative sources instead of guessing from training data, especially important for frameworks that change fast between versions.
What does not belong in CLAUDE.md:
- Anything that changes often. A CLAUDE.md that needs daily edits is really a task list, not project memory, and it bloats every session's starting context whether or not today's task needs it.
- Long prose explanations of "why" for things that are obvious from the code itself. CLAUDE.md is context budget spent before the conversation even starts; keep it dense.
- Duplicated information that already lives in a README or a docs folder Claude can read on demand. If it is only needed occasionally, let Claude fetch it when relevant instead of paying for it on every single turn.
Because CLAUDE.md content is injected at the start of every session, a bloated CLAUDE.md is a hidden context tax you pay before you have typed a single message. Audit it periodically the way you would audit any other thing that grows without anyone noticing: read it fresh, cut anything stale, and check whether recent instructions have made older ones redundant.
Subagents: context isolation, not just parallelism
The most underused context management tool in Claude Code is the subagent. When you delegate a task to a subagent (via the Agent tool, or a configured agent type), that subagent runs in its own context window. It does its own file reads, its own tool calls, its own back-and-forth, and none of that noise lands in your main conversation. Only the subagent's final report comes back.
This matters for context in a very concrete way: if you need to search a large codebase for every place a function is used, that search can involve dozens of grep calls and file reads. Do it directly in your main session and all of that tool output sits in your context for the rest of the session. Delegate it to a subagent and your main context gains one clean summary instead of dozens of raw tool results.
Good candidates for subagent delegation, specifically for context reasons:
- Broad, exploratory searches. "Find every place this API is called and how the response is handled" produces a lot of intermediate noise that you do not need to keep around after you have the answer.
- Independent verification. Running a test suite, checking a build, or reviewing a diff for problems, where you want the verdict, not the full transcript of how it got there.
- Research that feeds a decision. Reading through several files or a spec to answer one specific question. You want the answer, not the reading process.
Poor candidates: anything where you need to see the intermediate steps to course-correct, or where the task is small enough that the overhead of spinning up a subagent and reading its report costs more than just doing it inline.
The pattern that works well in longer Claude Code sessions is treating your main conversation as the orchestration layer and pushing anything context-heavy but self-contained out to subagents. Your main session stays lean and focused on decisions; the noisy work happens somewhere its cost does not accumulate against you.
Practical patterns for long sessions
A few habits make a measurable difference over a multi-hour Claude Code session.
Read narrow, not wide. When you know which lines you need, say so. An unscoped file read on a large file pulls the whole thing into context; a scoped read with a line range or offset pulls only what is relevant. This is the single cheapest context optimization available and the one most people skip because typing the full read is faster in the moment.
Prefer grep over cat for finding things. If you are looking for a symbol or a pattern, a targeted search returns a handful of matching lines. Reading whole files to eyeball them for the same thing returns everything, most of which is irrelevant to what you were looking for.
Close out debugging loops explicitly. After a bug is fixed, say so and move on rather than letting five failed attempts sit in history alongside the working fix. If you are about to /compact, this is exactly the kind of resolved thread that should not survive into the summary in full detail. A one-line "fixed by doing X" is worth more than the blow-by-blow of getting there.
Split large tasks into checkpoints. Instead of one enormous "build the whole feature" session, break it into stages with natural breakpoints: design, then implementation, then tests, then cleanup. /compact or /clear between stages when the earlier stage's detail is no longer load-bearing for what comes next.
Use files, not context, for anything that needs to persist across sessions. If you want Claude to remember a decision or a piece of state for next time, write it to a file (a plan doc, a CLAUDE.md update, a todo list) rather than relying on chat history surviving. Chat history is ephemeral relative to your project; files are not.
Batch independent tool calls. When you know you need to read three unrelated files, request them together rather than one exchange per file. This does not reduce the total context consumed, but it reduces the number of round trips, each of which re-sends the growing conversation history.
Watching your context usage
Claude Code surfaces context usage in the interface, and it is worth checking periodically in a long session rather than waiting for a warning or a failure. If you notice usage climbing faster than expected, it is usually one of a few culprits: an unscoped file read of something large, a verbose command whose full output you did not need (build logs are a classic offender), or a debugging loop that has run longer than it should have.
When you catch this early, a /compact with explicit instructions about what to keep is far more useful than doing it at the last minute. Compacting under pressure, right before hitting the limit, gives Claude less room to produce a good summary and more risk of losing something you actually needed.
If you are building on the Claude Agent SDK rather than using Claude Code directly, the same principles apply but with more explicit knobs: server-side compaction can be enabled to automatically summarize earlier turns as a conversation approaches the context window, and context editing can clear stale tool results or thinking blocks without a full summarization pass. Claude Code's /compact is the user-facing equivalent of the same idea, tuned for interactive use.
Common mistakes that burn context
Treating context like it is free until it suddenly is not. The cost is incurred continuously, not just at the moment you hit a wall. Every large tool output you leave sitting in history is being re-processed on every subsequent turn.
Putting everything in CLAUDE.md "just in case." A CLAUDE.md that reads like a full project wiki costs context on every session regardless of whether today's task touches any of it. Keep it to what is genuinely load-bearing, and let Claude read deeper docs on demand.
Never using `/clear` between unrelated tasks. Carrying forward an entire debugging session into an unrelated feature request means the model is reasoning with a pile of irrelevant history mixed into the relevant part. This is a common source of the "it's confusing two things" failure mode.
Doing broad research inline instead of delegating it. A wide codebase search run directly in your main session is one of the most expensive things you can do to your own context budget, and it is almost always better suited to a subagent that reports back a summary.
Reading whole files reflexively. If you already know roughly where in a file the relevant code lives, from a previous grep or from the file structure, request that range instead of the whole file. This habit alone accounts for a large share of avoidable context bloat in real sessions.
Letting failed attempts pile up without closure. If an approach did not work, say so plainly and move on. A conversation full of unlabeled dead ends is harder for the model to reason over than one where resolved threads are marked resolved.
FAQ
Does a bigger context window mean I do not need to manage context? No. A larger window raises the ceiling before you hit a hard limit, but the quality-degradation problem, where stale or irrelevant context dilutes the model's reasoning, shows up well before the window is technically full. Managing context is about keeping signal-to-noise high, not just avoiding an error message.
What is the difference between /compact and just starting a new session? /compact preserves continuity: the summarized version of your conversation stays in play, so Claude still knows what you were doing and why. Starting a new session (or /clear) drops everything, which is correct when the prior context is no longer relevant, but wrong when you are still mid-task and need the thread of decisions that got you there.
Should I put my entire coding style guide in CLAUDE.md? Only the parts that apply broadly and change rarely. A 50-line style guide that gets read on every single session is a reasonable trade if it prevents repeated corrections. A 500-line document covering every edge case is worth splitting: keep the high-frequency rules in CLAUDE.md and let Claude read a separate style doc on demand for the rest.
Do subagents share context with the main session? No, and that is the point. A subagent starts with its own context, does its own work, and returns a report to the main session. The main session's context grows by the size of that report, not by everything the subagent did to produce it. This is the primary reason to reach for a subagent on any task that involves a lot of exploratory reading or searching.
How do I know if a slow or wrong answer is a context problem? Signs to look for: the assistant re-reads a file it already read earlier in the session, repeats a mistake you already corrected, or seems to have "forgotten" an instruction from well earlier in the conversation. These are classic symptoms of a context window diluted with stale information. Running /compact with explicit instructions on what to preserve, or /clear and restating the essentials, usually resolves it faster than trying to re-correct within the same bloated context.
Is it worth manually compacting if Claude Code does it automatically near the limit? Yes, because automatic compaction happens at whatever threshold the tool has decided, not at a point that makes sense for your task. Proactively compacting or clearing at a natural breakpoint, like the end of a completed subtask, gives you control over what gets summarized and what gets dropped, which produces a better outcome than a reactive compaction triggered mid-thought.
AI CodingShip full-stack AI apps at conversation speed — specs, agents, deploys, all from the terminal.
Claude CodeGo from zero to confident with Claude Code, the terminal agent that reads, edits, runs, and verifies real code.
Related reading