Context Compaction
Learn how Claude Code manages context window limits with a 3-layer compression strategy — keeping conversations productive even on long sessions.
What You’ll Learn
Context windows are finite. Even with very large context windows, a long coding session with many file reads and tool calls will eventually hit the limit. When it does, Claude Code doesn’t just stop — it compacts.
By the end, you’ll understand:
- Why context limits matter in practice
- The 3-layer compression strategy
- What information survives compaction
- How to structure work for better context efficiency
The Problem
A typical coding session might look like:
System prompt: ~3,000 tokens
CLAUDE.md: ~1,000 tokens
Skill definitions: ~2,000 tokens
File reads (10 files): ~15,000 tokens
Tool outputs: ~5,000 tokens
Conversation: ~10,000 tokens
─────────────────────────────────────
Total: ~36,000 tokens
Now imagine a longer session with 50 file reads, multiple searches, and several rounds of edits. You can easily hit 100K+ tokens. At some point, the context window needs to be trimmed.
How It Works
The 3-Layer Strategy
Claude Code manages context progressively: it clears older tool outputs first, summarizes the conversation if that isn’t enough, and then restores the context that lives on disk:
┌──────────────────────────────────────────────┐
│ Context Compaction │
│ │
│ Layer 1: Clear Older Tool Outputs │
│ ┌───────────────────────────────────────┐ │
│ │ Old tool results are cleared first │ │
│ │ "Read src/db.ts (900 lines)" from │ │
│ │ an hour ago → output cleared │ │
│ └───────────────────────────────────────┘ │
│ │
│ Layer 2: Summarize the Conversation │
│ ┌───────────────────────────────────────┐ │
│ │ Earlier turns → structured summary │ │
│ │ │ │
│ │ Turn 1-15: "User asked to fix auth │ │
│ │ bug. Found issue in middleware. │ │
│ │ Fixed JWT validation. Tests pass." │ │
│ └───────────────────────────────────────┘ │
│ │
│ Layer 3: Restore What Lives on Disk │
│ ┌───────────────────────────────────────┐ │
│ │ Recent exchanges kept intact │ │
│ │ System prompt still applies │ │
│ │ CLAUDE.md + rules re-read from disk │ │
│ │ Up to 5 recent files re-read │ │
│ └───────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────┘
What Survives Compaction
| Kept or re-injected | Summarized | Reloaded on demand |
|---|---|---|
| System prompt and output style | Older conversation turns | Nested CLAUDE.md files in subdirectories |
| Project-root CLAUDE.md, unscoped rules, and auto memory (re-read from disk) | Earlier file reads and tool outputs | Rules with paths: frontmatter |
| The plan from plan mode; up to five recently read or edited files | Context that hooks added earlier | — |
| Invoked skills (first 5,000 tokens each, 25,000 total); the task list, when the session has the Task tools | Instructions you gave only in chat | — |
The Compaction Trigger
Compaction happens automatically as the conversation approaches the limit. By default, Claude Code compacts when the conversation reaches the model’s context limit; models with a native 1M-token window, including the current Fable, Opus, Sonnet, and Haiku models, compact a little earlier, at about 967K tokens. Sonnet 4.6 and Opus 4.6 without extended context compact at the 200K boundary.
To compact earlier, set a smaller auto-compact window, from 100K to 1M tokens:
/autocompact 500k # current model; saved to your user settings
claude --autocompact 300k # one launch only
CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000 claude # takes precedence over both
/autocompact auto returns to the window tuned for your model, and "autoCompactWindow": 500000 in a settings file sets one window for every model.
Since v2.1.299, Claude Code also compacts an idle conversation: in an interactive terminal session on the one-hour prompt cache, a conversation of 200K+ tokens left idle for about 54 minutes is compacted just before that cache expires, so your next message doesn’t reprocess the whole history. Turn this off with "idleCompaction": false or the Idle compaction row in /config.
Preserving Critical Information
The system is smart about what to preserve:
- System instructions — The system prompt and output style still apply
- Your requests — Kept in the summary, along with key code snippets
- Current state — What files have been modified, what’s pending
- Recent turns — The most recent exchanges stay intact
- Summary of earlier work — Compressed rather than lost, although detailed instructions given early in the conversation may not survive
To steer what the summary keeps, add a “Compact Instructions” section to CLAUDE.md, or run /compact with a focus.
Key Insight
Compaction is not deletion — it’s summarization. The AI doesn’t lose awareness of what happened earlier; it loses the verbatim details but keeps the essence.
This has practical implications for how you work:
- Long sessions are fine — compaction keeps them productive
- Critical context should be in CLAUDE.md — the project-root CLAUDE.md is re-read from disk after every compaction
- Break large tasks into phases — each phase can start with a fresh context
- Use subagents for research — their context is separate and discarded after
The biggest mistake users make is worrying about context limits. In practice, compaction handles it automatically. The system degrades gracefully — you’ll notice slightly less detailed recall of earlier conversation, but the work continues.
Hands-On Example
Optimizing for Context Efficiency
Structure your work to minimize context waste:
# Inefficient: loading everything then working
"Read all files in src/, then fix the bug in auth.ts"
→ Loads 50 files, only 1 is relevant
# Efficient: targeted exploration
"The bug is in authentication. Check src/auth/ first."
→ Loads 3-5 files, context stays lean
# Even better: use subagents for exploration
"Use an Explore agent to find where authentication
is handled, then fix the bug."
→ Exploration context is isolated in subagent
Monitoring Context Usage
Run /context at any point for a live breakdown of what fills the window, including which CLAUDE.md and memory files loaded:
/context # live breakdown by category
/compact focus on the auth bug fix # compact now, keeping what you choose
/clear # start fresh for unrelated work
When you see high context usage:
- Run
/clearbefore switching to an unrelated task - Use
/compactwith a focus to trigger compaction yourself - Use
/rewind, select a message, and choose Summarize from here or Summarize up to here to compact only part of the conversation - Delegate research to subagents
What Makes a Good Summary
When compaction summarizes your earlier work, it captures:
Summary of turns 1-25:
- User asked to implement user authentication for Express app
- Explored codebase: Express 4.x, PostgreSQL, no existing auth
- Decided on JWT + bcrypt approach
- Created: src/middleware/auth.ts, src/routes/auth.ts
- Modified: src/app.ts (added auth middleware)
- Added: user table migration
- Tests written and passing (4 tests)
- Current task: Adding password reset flow
This summary preserves the key decisions and state without the 25 turns of back-and-forth.
What Changed
| No Compaction | With 3-Layer Compaction |
|---|---|
| Session ends when context fills | Sessions can continue indefinitely |
| All history at full detail | Progressive compression |
| Context crisis is abrupt | Gradual, graceful degradation |
| Must restart for long tasks | Automatic management |
| Critical info can be lost | System prompt kept; CLAUDE.md re-read from disk |
Next Session
This completes Module 1: Core Agent! You now understand the fundamental building blocks: the agent loop, tools, planning, subagents, knowledge loading, and context management.
In Module 2, we scale up to multi-agent systems. Session 7 starts with Task Graph & Dependencies — how Claude Code coordinates multiple tasks with dependency edges, enabling complex workflows.