Claude Code operates within a context window whose size depends on your model and plan. Opus 4.8 supports a 1M token context window by default on Max, Team, and Enterprise plans. Sonnet and Haiku have smaller windows. How you manage that window directly affects response quality, speed, and cost. This guide covers strategies for keeping context focused and knowing when to start fresh.
How Context Works
Every message you send, every file Claude reads, and every tool result occupies tokens in the context window. With the 1M token limit, you can sustain much longer sessions than before -- reading dozens of files, making multi-file changes, and iterating extensively without hitting the ceiling. However, as the conversation grows, older messages get compressed automatically. Understanding this lifecycle helps you work more effectively:
- Fresh context — Early in a conversation, Claude has full access to everything discussed.
- Active window — With Opus 4.8 on Max/Team/Enterprise, the 1M token window lets you work through large features, multi-file refactors, and extended debugging sessions in a single conversation. Smaller models hit compression sooner.
- Compression — As the window fills, the system summarizes older messages to make room.
- Degradation — After heavy compression, nuance from earlier exchanges may be lost.
The /compact Command
Use /compact to manually trigger context compression. With the 1M token window, you no longer need to compact aggressively -- but it remains valuable for cost control and keeping Claude focused. Compact when:
- You have finished one subtask and are moving to another (reduces cost of subsequent messages)
- The conversation has accumulated a lot of tool output you no longer need
- You notice responses slowing down or becoming less accurate
- You want to reduce token spend even though you have not hit the limit
You can also pass a prompt to /compact to guide what gets preserved:
/compact focus on the database migration work
This tells the compressor to prioritize retaining information about database migrations while aggressively summarizing everything else.
Scoping Tasks Narrowly
The single most effective context management strategy is keeping tasks small. Instead of asking Claude to "refactor the entire authentication system," break it into focused requests:
- "Refactor the password hashing in
auth/hash.ts" - "Update the session middleware to use the new token format"
- "Add tests for the refreshToken endpoint"
Each focused task uses less context, produces better results, and is easier to review.
Using Subagents to Protect Context
When you need to explore the codebase or research a question, subagents run in their own context window. The main conversation only receives a summary of their findings. This is valuable when:
- Exploring unfamiliar code — A subagent can read dozens of files without polluting your main context.
- Running broad searches — Grep and glob results from a subagent stay contained.
- Parallel investigation — Multiple subagents can research different aspects simultaneously.
Claude Code automatically uses subagents for deep exploration tasks. You can encourage this by framing requests as research:
Find all the places where we handle authentication errors
and summarize the patterns used.
What 1M Tokens Gets You (Opus 4.8 on Max/Team/Enterprise)
To put the Opus 4.8 context limit in perspective:
| Content | Approximate tokens |
|---|---|
| One source file (~200 lines) | ~2,000 |
| 10 source files | ~20,000 |
| A 50-message conversation with tool use | ~100,000-200,000 |
| A full-day pair programming session | ~400,000-600,000 |
| Reading an entire medium codebase (500 files) | ~1,000,000 |
With Opus on Max/Team/Enterprise, most development sessions -- even long ones -- will stay well within the 1M limit. You can comfortably read entire modules, iterate on complex features, and run multiple test-fix cycles without running out of room. On Sonnet or Haiku, context management remains important since these models have smaller windows.
When to Start Fresh
Start a new conversation when:
- You are switching to a completely unrelated task
- The conversation has gone through multiple rounds of compression
- Claude starts "forgetting" decisions made earlier in the conversation
- You want to reset cost accumulation (each message in a long session sends the full context)
There is no penalty for starting fresh. Claude reads your CLAUDE.md and project files at the start of every conversation, so project context is always available.
Practical Tips
- Front-load important information. Put critical constraints and requirements in your first message or in
CLAUDE.mdso they survive compression. - Use CLAUDE.md for durable context. Anything Claude needs to remember across conversations belongs in
CLAUDE.md, not in chat. - Avoid pasting large files into chat. Let Claude read files with tools instead — the content can be compressed more effectively than inline text.
- Review what Claude remembers. If you suspect context loss, ask "What do you remember about X?" to check before continuing.
- One concern per conversation. Mixing bug fixes, feature work, and refactoring in one session wastes context on task-switching overhead.
How Context Compression Works
When the context window approaches its limit, the system automatically:
- Identifies older message pairs (your message + Claude's response)
- Summarizes them into compact representations
- Replaces the originals with summaries
- Preserves the most recent messages in full
The compression is lossy — specific code snippets, exact line numbers, and nuanced decisions may be simplified. This is why keeping tasks focused matters: less to compress means less information lost.
Cost Management
Claude Code consumes tokens with every interaction. Understanding how token usage works and applying a few habits can significantly reduce your spend without sacrificing productivity.
Understanding Token Usage
Every message you send and every response Claude generates costs tokens. But the biggest driver of cost is context size — the accumulated conversation history that gets sent with each new message. As your conversation grows, each exchange becomes more expensive.
Opus 4.8 supports a 1M token context window by default on Max, Team, and Enterprise plans. This lets you sustain much longer sessions when using Opus, which is great for productivity but means a single extended session can accumulate significant cost if you are not mindful. Sonnet and Haiku have smaller context windows, so context management is even more important with those models.
Key cost factors:
- Conversation length — longer sessions mean more tokens per message (a 500K-token Opus session sends 500K tokens with every new exchange)
- File reads — every file Claude reads adds to the context
- Tool output — command results, search results, and file contents all count
- Model choice — Opus costs more than Sonnet, which costs more than Haiku
Track Your Actual Spend
Before optimizing, know what you are spending. Use these methods to get real numbers:
Session-Level Tracking
Use /cost during a session to see how many tokens you have used and what it costs. Check this periodically to build intuition about which tasks are expensive.
Dashboard Monitoring
Check the Anthropic Console for daily and monthly usage breakdowns. Look at:
- Daily spend trend — is it climbing or stable?
- Per-model breakdown — how much goes to Opus vs Sonnet vs Haiku?
- Peak usage days — what tasks drove the spikes?
Setting Budget Alerts
Set spending limits in the Anthropic Console to avoid surprises. Start with a daily cap that matches your expected usage, then adjust after a week of real data.
The Model Selection Rule of Thumb
Pick the cheapest model that gets the job done:
| Task Type | Recommended Model | Why |
|---|---|---|
| Quick questions, boilerplate, renames | Haiku | Fast, cheap, good enough |
| Feature implementation, code review, tests | Sonnet | Best balance of quality and cost |
| Complex multi-file refactors, subtle bugs, architecture | Opus | Worth the premium for hard problems |
Switch models mid-session with /model:
/model claude-haiku-4-5-20251001 # Drop to Haiku for simple tasks
/model claude-sonnet-4-6 # Back to Sonnet for real work
/model claude-opus-4-7 # Upgrade for the hard part
Most developers find that 80% of their work is Sonnet-appropriate. Reserve Opus for the 10-20% that actually needs it.
Use /compact — Your Biggest Cost Lever
The /compact command summarizes your conversation history, dramatically reducing context size. This is the single most effective cost-saving habit.
# Compact with default summary
/compact
# Compact with a specific focus
/compact focus on the authentication refactor
When to compact:
- After completing a sub-task before moving to the next one
- When you notice responses slowing down
- When
/costshows context growing beyond 200K tokens and you are doing routine work - Before starting a new line of work in the same session
What it saves: A long Opus session can accumulate 300K-500K tokens of context. Compacting cuts this to 5-10K, meaning every subsequent message costs a fraction of what it would otherwise. With Opus 4.8's 1M token window on Max/Team/Enterprise, you will not need to compact to avoid hitting the ceiling -- but you should still compact to control costs. A message at 500K context costs 50x more than one at 10K context. On Sonnet and Haiku, compacting also helps avoid hitting their smaller context limits.
One Task Per Session
Start a new claude session for each distinct task. A session about "fix the login bug" should not continue into "now add the search feature." Each new topic inherits all the context from the previous one, inflating costs for no benefit.
# Task 1: fix the bug
claude "Fix the null check in auth.ts:42"
# Done. Exit.
# Task 2: new feature (fresh session, clean context)
claude "Add full-text search to the /products endpoint"
Use --resume only when you genuinely need to continue previous work.
Scope Your Tasks
Smaller, focused tasks cost less than broad, open-ended ones. Instead of asking Claude to "refactor the entire codebase," break it into specific pieces.
# Expensive — broad scope, lots of exploration
"Refactor all the API endpoints to use the new middleware"
# Cheaper — focused, specific
"Refactor the /users endpoint in src/routes/users.ts to use the new auth middleware"
Efficient Prompting Patterns
How you write prompts affects how many tokens Claude uses exploring and responding.
Be specific about what you want:
# Vague — Claude explores broadly
"Fix the bug in the login page"
# Specific — Claude goes straight to the issue
"Fix the null pointer error in src/auth/login.ts:42 where user.email is accessed before the null check"
Point Claude to the right files:
# Let Claude search (costs tokens for tool calls)
"Find and fix the rate limiter"
# Direct Claude (saves exploration tokens)
"Fix the rate limiter in src/middleware/rateLimit.ts"
Use CLAUDE.md to avoid repeating context — instructions in CLAUDE.md are loaded once rather than typed every session. See CLAUDE.md Guide.
Daily Spend Patterns
To get a feel for realistic usage, track your own spend for a week. Most developers fall into one of these patterns:
- Light usage (exploration, questions, small fixes): primarily Haiku/Sonnet, low context accumulation
- Moderate usage (feature development, code review): Sonnet with occasional Opus, regular compacting
- Heavy usage (full-day pair programming, large refactors): mixed models, aggressive compacting, multiple sessions
The key variable is not which model you use — it is how long your conversations get. A 50-message Sonnet session costs more than a 5-message Opus session.
Cost Reduction Checklist
| Strategy | Impact | Effort |
|---|---|---|
Use /compact every 15-20 messages | High | Low |
| Start fresh sessions per task | High | Low |
| Scope tasks narrowly | High | Low |
| Use Haiku for simple work | Medium | Low |
| Be specific in prompts (include file paths) | Medium | Low |
| Use CLAUDE.md for persistent context | Medium | One-time |
| Set budget alerts in the Console | Medium | One-time |
Check /cost periodically | Low | Low |
Common Mistakes
Anti-patterns that reduce Claude Code's effectiveness, waste tokens, or lead to frustrating results. Avoid these to get the most out of your workflow.
Vague Prompts
The most common mistake. Vague prompts force Claude to guess your intent, explore broadly, and often produce results that miss the mark.
# Bad — vague, no direction
"fix the bug"
"make it better"
"refactor this"
# Good — specific, actionable
"fix the null reference error in src/auth/login.ts:42"
"improve the error messages in the validation module to include the field name"
"extract the database query logic from UserController into a UserRepository class"
The more specific your prompt, the fewer tokens Claude spends exploring and the better the result.
Not Using CLAUDE.md
Without a CLAUDE.md file, Claude does not know your project's conventions. It will guess at coding style, test commands, linting rules, and architecture patterns — and often guess wrong.
What happens without CLAUDE.md:
- Claude uses generic conventions instead of your team's standards
- You repeat the same instructions every session
- Code style is inconsistent with the rest of your codebase
Fix: Create a CLAUDE.md at your project root. Even a minimal one helps enormously. See CLAUDE.md Setup and the minimal example.
Ignoring Plan Mode
For complex, multi-step tasks, jumping straight into implementation leads to wrong approaches and wasted effort. Plan mode lets Claude think through the approach before writing code.
# Risky for complex tasks — Claude may take a wrong turn
"refactor the authentication system to use JWT"
# Better — plan first, then execute
"plan how to refactor the authentication system to use JWT"
# Review the plan, then:
"looks good, go ahead and implement it"
Use plan mode for any task that touches more than 2-3 files or involves architectural decisions.
Not Scoping Tasks
Asking Claude to do too much at once leads to context bloat, confusion, and errors. Large tasks should be broken into focused steps.
# Too broad — likely to go off track
"build a complete user management system with CRUD, roles, permissions, and an admin dashboard"
# Better — one piece at a time
"create the User model with fields for email, name, and role"
# Then: "add CRUD API endpoints for the User model"
# Then: "add role-based permission middleware"
Each focused task gets better results and costs fewer tokens.
Running Without Context
Starting Claude Code and immediately asking about code without letting it understand your project first.
Fix: Let Claude read relevant files before asking it to modify them:
# Bad — Claude has no context
"fix the UserService"
# Good — provides context
"read src/services/UserService.ts and then fix the error handling in the create method"
Your CLAUDE.md file also provides automatic context. Use it.
Over-Permissioning
Running Claude Code with all permissions allowed and never reviewing what it does. While Claude is careful by default, you should still review changes, especially for:
- Destructive operations (deleting files, dropping tables)
- Actions that affect shared systems (pushing code, creating PRs)
- Security-sensitive changes (auth logic, permissions, secrets handling)
Fix: Use a restrictive permission mode for sensitive projects. Review diffs before committing. Do not auto-approve everything.
Not Using /compact
Letting conversations grow unbounded is one of the most expensive mistakes. Every message gets more expensive as context accumulates, and Claude's responses may degrade as context fills up.
Fix: Run /compact after completing each sub-task, or every 20-30 exchanges. See Cost Management for details.
Trying to Do Everything in One Session
Marathon sessions of 100+ exchanges lead to context overflow, confusion, and high costs. Claude works best with focused sessions.
Fix:
- Start a new session for unrelated tasks
- Use
/compactor/clearbetween phases of work - Break large projects into multiple sessions with clear goals
Not Reviewing Generated Code
Accepting Claude's output without reading it. Claude is highly capable but not infallible — especially for:
- Edge cases in business logic
- Security-sensitive code paths
- Complex state management
- Integration with systems Claude cannot access
Fix: Always read the diff before committing. Run tests. Check edge cases.
Fighting the Tool Instead of Redirecting
When Claude takes a wrong approach, some users try to get it back on track with increasingly complex clarifications. It is often faster to interrupt and restart.
# If Claude is going down the wrong path:
[Press Escape]
"Stop. Use a different approach: instead of creating a new class, modify the existing UserService."
Or use /clear and start fresh with a better-scoped prompt.
Anti-Pattern Summary
| Mistake | Fix |
|---|---|
| Vague prompts | Be specific about file, function, and intent |
| No CLAUDE.md | Create one — even a minimal version helps |
| Skipping plan mode | Plan first for complex, multi-file tasks |
| Too-broad tasks | Break into focused, single-concern steps |
| No context | Let Claude read files before modifying them |
| Over-permissioning | Review changes, use restrictive mode when needed |
| Skipping /compact | Compact after each sub-task |
| Marathon sessions | Fresh sessions for unrelated work |
| Not reviewing output | Always read the diff |
See Also
- Getting Started — Initial setup and configuration basics
- CLAUDE.md Guide — Storing durable project context
- Multi-Agent — Using subagents for context isolation
- Prompt Tips — Writing effective prompts within context constraints
- Agent View — Spot the session whose context is bloating
Source and license
- Adapted from MuhammadUsmanGM/claude-code-best-practices / guides/context-management.md (Muhammad Usman and contributors, License MIT, 8e7d4bf)