Context window management is one of those skills that nobody explains until you’ve already burned $40 on a session that went sideways in hour three. Claude Code gives you a 1 million-token context window on Opus-class models — more than any reasonable session should need — but the way you fill that window determines whether your final responses are as useful as your first ones or noticeably degraded.
We ran structured experiments across seven management strategies. Some are obvious when you know them; others require rethinking how you approach long sessions. This guide covers all seven, when each one is worth the cost in additional complexity, and the signals that tell you it’s time to intervene.
Why Context Window Management Is a Production Skill
The common misconception is that larger context windows make management unnecessary. They don’t. They just change the failure mode.
With a small context window, you run out of space and get a hard error. With a large one, you get gradual degradation: the model loses track of early decisions, starts contradicting itself, references things it can’t see anymore, and produces code that’s technically correct but inconsistent with the rest of the session. None of this triggers an obvious error. You just end up with worse outputs and higher costs.
The second cost that surprises people: every token in the context window is charged on every API call. A 200,000-token session isn’t 200,000 tokens of cost — it’s 200,000 tokens per turn, multiplied by every turn you take. Long, unfocused sessions get expensive fast.
Context management is not about conserving tokens at the expense of productivity. It’s about keeping the context coherent and relevant so that later turns are as useful as earlier ones.
How Claude Code’s Context Window Works
Claude Code’s context accumulates everything in the current session: your prompts, Claude’s responses, tool call inputs and outputs, the content of files read, and conversation history from the current session.
Key things most developers don’t know:
Tool outputs are often huge. When Claude reads a file with the Read tool, the full file content goes into context. When it runs a shell command with Bash, the full stdout and stderr go into context. A find . -type f -name "*.ts" that returns 800 files adds 800 lines to your context. This compounds quickly.
Context doesn’t shrink automatically. Once something is in context, it stays there until you use /compact or start a new session. Unlike some other tools, Claude Code doesn’t drop old turns to make room — you get to decide when to compress.
The prompt cache helps but doesn’t eliminate the problem. Claude Code uses Anthropic’s prompt caching for repeated content. Your CLAUDE.md file gets cached after the first turn and doesn’t cost full price on subsequent turns. But this only helps with stable content, not with conversational history.
/compact summarizes, doesn’t delete. Running /compact tells Claude to create a compressed summary of the current conversation and start a new context window that begins with that summary. You lose the exact details but keep the semantic content. This has a cost: the summary itself takes tokens, and the new session can’t reference specific earlier outputs.
Signs You’re Under Context Pressure
Watch for these signals before your session degrades:
Claude references something you said much earlier in the session. This is usually fine, but when it starts misremembering or confusing early and late instructions, the context is getting crowded.
Responses become noticeably shorter or vaguer. Claude is efficient about context when it’s long. If your usual detailed responses start getting shorter without you asking for concision, something’s off.
Claude suggests actions you already did. “You could try running the test suite” when you just ran the test suite three turns ago means that turn is no longer prominent in the model’s effective attention.
File edits become inconsistent. If Claude writes a function that contradicts a type definition it established earlier in the session, context pressure is the likely culprit.
Token count approaching 50% of the window. Claude Code shows a token counter. When you’re approaching 500K tokens on a 1M window, start thinking about whether to compact or isolate the next sub-task.
You’ve been working on something for 90+ minutes without any structure. Long freeform sessions accumulate context faster than structured ones. After 90 minutes, assess whether the session still has a coherent focus.
The 7-Strategy Cost vs Effect Matrix
Before going through each strategy, here’s the trade-off landscape. “Cost” here means implementation overhead and potential downsides, not literal token cost.
| Strategy | Token Savings | Implementation Cost | When to Use |
|---|---|---|---|
1. /compact at right timing | High | Very Low | Always, but timing matters |
| 2. File references over pasting | Medium | Very Low | Every session |
| 3. CLAUDE.md as memory anchor | Low | Low (one-time setup) | Every project |
| 4. Sub-agent isolation | Very High | Medium | Tasks with distinct phases |
| 5. Session handoff files | Medium | Medium | Cross-session continuity |
| 6. Parallel worktrees | Very High | High | Independent parallel work |
| 7. Context budget in Workflow scripts | High | High | Automated pipelines |
Strategy 1: /compact — When and How to Use It Correctly
/compact is the most misused tool in the kit. The common mistake is either using it too late (after context has already degraded) or not at all (hoping the session will stay coherent indefinitely).
The right time to compact is after completing a coherent phase, not when you’re in the middle of one. If you just finished implementing a feature and its tests, that’s an excellent time to compact before starting the next feature. If you’re in the middle of debugging a specific issue, compact after you’ve confirmed the fix, not before.
Custom compact instructions improve the summary. You can pass a prompt to /compact:
/compact Focus the summary on: the authentication system architecture decisions, the two bugs we fixed in the JWT handler, and the outstanding question about token refresh behavior. Omit implementation details for parts we haven't started yet.
This produces a more useful summary than the default, which tries to summarize everything.
Don’t compact right before a decision-heavy task. The summary loses nuance. If you’re about to do architecture work that requires precise recall of earlier decisions, either don’t compact yet or write those decisions to a file first so you can reference them.
Track what compacted sessions can’t access. After /compact, Claude cannot read the exact text of earlier responses. Any specific code, error messages, or outputs from before the compact are gone. Make sure anything you’ll need to reference again is either in a file in your project or explicitly included in the compact summary.
Strategy 2: File References Instead of Pasting
This is the lowest-effort strategy with consistent returns.
When you need Claude to consider some content, there’s a temptation to paste it directly into the chat. Don’t. Instead, save it to a file and reference the file path.
Wrong:
Here's the error log from the failed deploy:
[800 lines of log output]
Can you find the root cause?
Right:
I saved the error log to /tmp/deploy-error.log. Can you find the root cause?
In the first case, 800 lines go into the conversational context and stay there for the rest of the session. In the second case, Claude reads the file with the Read tool — the content still enters context for that turn, but it’s bounded to that task rather than being embedded in the conversational history.
For project files, reference them by path rather than pasting them, even when they’re relevant to multiple turns. Claude Code reads files on demand. A file you reference once costs you tokens once, not tokens for every subsequent turn.
The same principle applies to test output, build logs, API responses, and anything else that’s large and task-specific. Write it to a temp file, reference it, delete it when you’re done.
Strategy 3: CLAUDE.md as a Persistent Memory Anchor
The CLAUDE.md file is read at the start of every session and cached by the prompt caching system. That means it’s “free” in terms of additional per-turn cost — you pay for it once and it stays active throughout the session.
Use this to offload stable context that you’d otherwise re-explain every session:
## Project Context
This is a Next.js 15 application using the App Router.
All data fetching uses React Server Components; no `use client` for data.
The authentication flow uses the `src/lib/auth/` module.
Test runner is Vitest; run with `pnpm test`.
## Current Sprint Focus
We're migrating the settings page from the old React Query-based approach
to Server Actions. The old implementation is in `src/app/settings/legacy/`.
The new implementation goes in `src/app/settings/`.
The “Current Sprint Focus” section is especially useful. Updating it weekly takes 5 minutes and saves you re-establishing context at the start of every session.
What CLAUDE.md cannot do: it can’t replace the specific details of what happened in a previous session. It’s for stable context, not for session-to-session continuity. For that, use handoff files (Strategy 5).
Keep CLAUDE.md under 1,000 lines. Anything longer starts to feel like noise rather than signal, and the AI starts to deprioritize sections. The token budget optimization guide covers how to measure and trim.
Strategy 4: Sub-Agent Isolation for Long Tasks
Claude Code’s Agent tool lets you spawn sub-agents that run in their own context windows. This is the most powerful strategy for genuinely long tasks, but it requires thinking about your work differently.
The key insight: if a task has multiple distinct phases, each phase can potentially be its own sub-agent with its own fresh context. The orchestrating agent keeps a lean context (just coordination), while each sub-agent gets a full context window for its specific task.
Example: migrating a large codebase to a new API.
Without sub-agents:
- Phase 1: Audit all usages of the old API (adds lots of file content to context)
- Phase 2: Generate migration plan (context now has Phase 1 debris)
- Phase 3: Implement migrations file by file (context grows with each file)
- Phase 4: Verify and test (context is enormous, outputs degraded)
With sub-agents:
- Orchestrator: knows the overall plan, delegates to sub-agents
- Audit agent: runs Phase 1, writes results to a file, exits
- Planning agent: reads the audit file, generates the migration plan, writes it to a file, exits
- Migration agent (one per file or per module): reads the plan, migrates one piece, exits
- Verification agent: reads the migration plan, runs tests, reports results
Each sub-agent starts fresh. The only shared state is files — which is exactly what you want, because files are inspectable, version-controlled, and don’t degrade with context.
The overhead of designing sub-agent boundaries is real. For a two-hour task, it’s probably not worth it. For a task that would otherwise run six hours, it almost certainly is.
We covered the full architecture of multi-agent patterns in Claude Code Multi-Agent Orchestration: 6 Patterns. The sub-agent section there covers isolation boundaries and error propagation.
Strategy 5: Session Handoff Files
When you end a session and plan to continue the same work in a new session, don’t rely on memory or re-reading a long conversation history. Write a handoff file at the end of the session.
A handoff file is a markdown document that contains:
- What you were trying to accomplish
- What you completed in this session
- What’s still pending
- Any decisions made that the next session needs to know about
- Specific file paths and function names that are relevant to resume
Ask Claude to write it:
Before we end this session, write a handoff file to /tmp/session-handoff.md that
covers: what we were building, what's done, what's pending, the key architectural
decisions we made, and which files are most relevant to continue.
At the start of the next session:
Read /tmp/session-handoff.md and then continue from where we left off.
This costs about 200-500 tokens to write and saves you 10 minutes of re-establishing context. More importantly, it produces a written record of decisions rather than relying on your memory of a session that may have happened days ago.
We found that engineers who habitually write handoff files also use them for their own reference. “What did I decide and why?” is an easier question to answer when you wrote it down at the time than when you’re trying to reconstruct it from code.
Strategy 6: Parallel Worktrees for Independent Streams
Git worktrees let you have multiple checkouts of the same repository at the same time, in different directories. Claude Code sessions in different worktrees have different contexts and can work independently without interfering with each other.
When you have two genuinely independent tasks — say, fixing a bug in the payments module while building a new feature in the user profile module — run them in parallel worktrees rather than sequentially in the same session.
Setup:
git worktree add ../project-payments main
git worktree add ../project-profile main
Then start two Claude Code sessions:
# Terminal 1
cd ../project-payments && claude
# Terminal 2
cd ../project-profile && claude
Each session has its own context. The bug fix session doesn’t carry debt from the feature session and vice versa. When both are done, you merge the branches normally.
The limit of this approach is that it’s only useful for genuinely independent work. If the bug fix and the feature share code paths, parallel worktrees will create conflicts and you’ll spend more time resolving them than you saved.
For a complete guide to worktree-based parallel sessions, see Claude Code + Git Worktrees: Parallel Agents Guide.
Strategy 7: Context Budget in Workflow Scripts
Claude Code Workflow scripts (the workflow key in settings.json) let you define structured agent pipelines with explicit context budgets. This is the highest-overhead strategy but gives you the most control in automated pipelines.
{
"workflow": {
"budget": {
"context_tokens": 200000,
"max_turns": 20,
"on_budget_exceeded": "compact"
},
"phases": [
{
"name": "analysis",
"budget": {
"context_tokens": 50000
},
"agent": {
"task": "Analyze the PR diff and identify potential issues",
"output": "/tmp/analysis.md"
}
},
{
"name": "review",
"budget": {
"context_tokens": 80000
},
"agent": {
"task": "Given the analysis at /tmp/analysis.md, write detailed review comments",
"output": "/tmp/review.md"
}
}
]
}
}
The on_budget_exceeded field tells the workflow what to do when a phase hits its limit: compact (summarize and continue), pause (wait for human input), fail (abort the pipeline), or next-phase (abandon the current phase and move on).
This strategy is most valuable for recurring automated pipelines — nightly code reviews, automated test generation, documentation updates — where you want predictable behavior and cost, not for interactive sessions where you’re experimenting.
Workflow script documentation is in the Claude Code workflow syntax guide.
Multi-Agent Design Patterns for Context-Heavy Projects
Combining the strategies above, here are three patterns that work well for different project types.
The Research-then-Build Pattern (for complex features)
Phase 1 (Research agent): Read all relevant existing code, understand patterns, write a specification to a file. Compact aggressively.
Phase 2 (Build agent): Read the specification, implement the feature, write nothing to context that isn’t directly relevant to the implementation.
Phase 3 (Verify agent): Read the implementation, run tests, report results.
This keeps each agent focused on one thing and prevents research debt from polluting the implementation context.
The Scratchpad Pattern (for exploratory work)
Maintain a running scratch.md file that you update as you work. After every 2-3 turns, ask Claude to update the scratchpad with what was learned. When the session ends, the scratchpad contains the durable insights. When the next session starts, read the scratchpad first.
This is lighter-weight than handoff files and works well for exploratory work where the output is understanding, not code.
The Isolation-by-Service Pattern (for microservices)
Each service gets its own session. The orchestrating session only knows service interfaces and which service needs work — it doesn’t carry implementation details from any specific service. Service-level sessions start fresh for each meaningful task.
Frequently Asked Questions
Does /compact lose information I’ll need later?
Yes, by design. The summary captures intent and decisions but not exact text. Before compacting, if there’s specific output or code you’ll need to reference, save it to a file. Summaries are good at preserving “what we decided” and bad at preserving “the exact error message from turn 7.”
Should I always use sub-agents for long tasks?
Not necessarily. Sub-agents add coordination overhead. For a 45-minute task, the overhead of defining clean sub-agent boundaries often costs more than it saves. We found sub-agents start paying off for tasks that would otherwise run 3+ hours, or tasks with genuinely independent phases.
How do I know when my session has degraded vs. when Claude is just giving a different answer?
The clearest signal is consistency. If Claude’s response contradicts something specific it said or wrote 10 turns ago, that’s degradation. If Claude gives a different approach than it suggested earlier because you’ve provided more information, that’s expected behavior. The “contradicts earlier decisions” signal is more reliable than “feels different.”
Does using file references instead of pasting actually save tokens?
Per-turn, no — the file content still enters context when Claude reads it. What it saves is that the file content doesn’t become part of the conversational context that persists across turns. A pasted block stays in your conversation history; a file read by a tool call is bounded to that specific tool call’s token accounting. For files read once, the difference is minimal. For files you reference repeatedly across many turns, the savings add up.
Can I see my current token usage during a session?
Yes. Claude Code shows a token counter in the interface. The counter shows current session context usage against the model’s context limit. There’s no programmatic hook to trigger behavior at specific thresholds during interactive sessions, but Workflow scripts let you set per-phase context budgets.
What’s the right cadence for /compact in a long session?
We found that compacting at natural task boundaries (after completing a feature, after finishing a debugging session, after implementing a complete test suite) works better than compacting on a fixed turn count. The goal is to compact when you’ve completed something coherent, not in the middle of it.
Keep your API keys and secrets safe while running Claude Code sessions with 1Password CLI. Use op run --env-file .env.1password -- claude to inject credentials without ever writing them to disk or exposing them in shell history. Our guide on Claude Code secrets management walks through the full setup. Find more Claude Code configuration templates and real-world AGENTS.md examples at The Prompt Shelf /rules.