Claude Code: Context Management

Last updated: 2026-08-31

Context is Claude Code's "working memory" — managing context well means managing Claude Code's understanding ability and your API bill.

💡 Tip: Claude Sonnet's context window is 200K tokens (~150K words). The larger the project, the more important context management becomes — not all files need to be in "working memory" simultaneously.

📋 Prerequisites: Chapter 9 - CLAUDE.md Usage Guide

1. What You'll Learn


2. Context Window Mechanism

(1) Context Composition

Component Typical Share Description
System prompt 2-3% Claude Code built-in instructions
CLAUDE.md 1-2% Project conventions
Project files 40-60% Read source code files
Conversation history 30-40% Previous Q&A records
Code output 5-10% Generated code

(2) Context Lifecycle

TEXT 📖 Display only
Session start → Load CLAUDE.md + system prompt
             → Read relevant files based on instructions
             → Each turn accumulates history
             → Early content truncated when approaching limit
             → Long sessions may degrade in quality

▶ Example 1: View Context Usage

TEXT 📖 Display only
> /cost

Token usage:
  System prompt:     4,230 tokens
  CLAUDE.md:         1,850 tokens
  Project files:    52,400 tokens (12 files)
  Conversation:     28,600 tokens (8 turns)
  Code output:       8,920 tokens
  ─────────────────────────────────
  Total:            96,000 / 200,000 tokens (48%)
  Estimated cost:    $1.82

3. Token Optimization Strategies

(1) Reduce Unnecessary File Reads

Strategy Effect How-To
Precise instructions Reduce 30-50% Specify exact files rather than "look at project"
Limit scope Reduce 20-40% Define working directory in CLAUDE.md
Clear timely Reduce 10-30% Use /clear in long sessions
Small steps Reduce 15-25% One thing at a time

(2) Instruction Precision Comparison

TEXT 📖 Display only
# High consumption (reads entire project)
> Help me refactor this project

# Medium consumption (limited scope)
> Refactor all services under src/services/

# Low consumption (precise files)
> Refactor src/services/user.service.ts, extract validation logic to separate file

▶ Example 2: Token Consumption Comparison

TEXT 📖 Display only
# Vague instruction: ~80K tokens, $1.60
> Add a user search endpoint to the project

# Precise instruction: ~25K tokens, $0.50 (70% savings)
> In src/routes/user.ts, add GET /api/users/search endpoint,
> using searchUsers method from src/services/user.service.ts,
> following the search endpoint format in src/routes/product.ts

4. Large Project Context Strategies

(1) Partition Working

MARKDOWN
<!-- Limit work scope in CLAUDE.md -->
## Current Work Scope
- Primary: src/api/ directory
- Models: src/models/ directory
- Current task: User permission module

## Not Currently Relevant
- src/frontend/ (independent frontend dev)
- src/migrations/ (DB migration complete)
- docs/ (docs maintained separately)

(2) On-Demand Loading

TEXT 📖 Display only
# Don't load all files at once
> ❌ "Read all route files and refactor"
> ✅ "Read src/routes/user.ts and add pagination support"

# Continue after completion
> "Now read src/routes/order.ts and add same pagination"

(3) Session Segmentation

TEXT 📖 Display only
# Split long tasks into short sessions

# Session 1: Model design
claude "Design user permission DB model, only read prisma/schema.prisma"
# Ctrl+D exit

# Session 2: Middleware
claude "Based on the permission model, implement RBAC middleware"

# Session 3: Route integration
claude "Integrate RBAC middleware into all routes needing permission checks"

5. Manual Context Control

(1) In-Session Commands

Command Purpose Scenario
/clear Clear conversation history Topic change
/compact Compress conversation history Long session optimization
/cost View Token usage Cost monitoring
/files View loaded files Check context

▶ Example 3: Before/After Optimization

TEXT 📖 Display only
# Before: Vague instruction — 156K tokens ($3.12)
> Fix all test failures

# After: Precise instruction — 32K tokens ($0.64)
> Run npm test, only fix 3 failing tests in auth module,
> don't read frontend files

Savings: 80%

❓ FAQ

Q What if 200K tokens isn't enough?
A Use /clear to reset conversation, or split into multiple short sessions. 200K is usually enough for single tasks; only long sessions may exceed.
Q Does /compact reduce quality?
A Slightly. Compression keeps key info but loses conversation details. Recommend /clear on topic change rather than /compact.
Q How to know which files Claude Code read?
A Claude Code displays file paths for each operation. Also use /files to view currently loaded files.
Q Can I prevent Claude Code from reading certain files?
A Write "don't read xxx directory" in CLAUDE.md, but compliance isn't 100%. Use .claudeignore for sensitive files.
Q What happens when context is nearly full?
A Claude Code may start forgetting earlier conversation content; answer quality degrades. Time to /clear or start a new session.
Q Is large Token consumption variation normal?
A Yes. Simple queries may use 5K tokens, complex refactoring 100K+. Instruction precision is the biggest factor.

📖 Summary


📝 Exercises

  1. Basic (⭐): Run /cost in a project, record Token consumption for a simple vs complex task.
  2. Intermediate (⭐⭐): Complete the same task with vague and precise instructions, compare Token consumption and quality.
  3. Advanced (⭐⭐⭐): Design context management strategy for a 50+ file project, achieving 50% Token reduction.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏