Skip to content

Why Claude Loses Context After Compaction (And How to Prevent It)

I spent 2 hours building a feature with Claude Code. Everything worked perfectly - tests passing, code clean, committed to git. Then I came back after lunch to add one small enhancement. Claude proceeded to rewrite the entire module using a completely different pattern, contradicting everything we’d built that morning.

I didn’t realize it immediately, but Claude had lost context. The first task after compaction went fine, but the next one revealed it had “forgotten” everything from thirty minutes ago.

Duplicated code. Contradictory patterns. Wasted time.

What’s Actually Happening

Claude Code loses context sharply after compaction - an automatic process that summarizes your conversation when you approach the context window limit. The first task after compaction works fine because the summary was adequate for that specific request. But when you reference something from earlier - a design decision, a pattern we established, a file we modified - that’s when it becomes clear the context is gone.

In production development, this leads to:

  • Duplicated code (Claude recreates what already exists)
  • Contradictory patterns (different approaches in same codebase)
  • Wasted time (undoing conflicting changes)
  • Hard-to-catch bugs (inconsistencies only spotted during review)

Why Context Compaction Hurts

Claude Code has a limited context window (200,000 tokens for Claude 3.5 Sonnet). As your conversation grows, you approach this limit. Claude Code automatically “compacts” older messages into summaries. These summaries are less detailed than original context. Critical details get lost in summarization.

You don’t always notice right away. The first task after compaction goes fine because the summary was adequate for that specific request. But when you reference something from earlier in the conversation - a design decision, a pattern we established, a file we modified - that’s when it becomes clear the context is gone.

After 15 years of traditional development, I spent 3 months using Claude Code daily. The context loss after compaction was a recurring problem. I’d build a feature, test it, commit it. Then start a related feature and Claude would suggest a completely different approach - because it had “forgotten” the earlier decisions.

Solution 1: Strategic Compaction Points

Before you hit compaction, organize your work into self-contained units:

  1. Complete self-contained work units
  2. Commit frequently with descriptive messages
  3. Document decisions in code comments
  4. Create checkpoints in your workflow

Compaction happens automatically. By organizing work into self-contained units, you ensure critical context is either:

  • In git history (commit messages)
  • In the code itself (comments)
  • Not needed across compaction boundaries

Instead of building a multi-file feature in one long session:

Terminal window
# Session 1: Build core model
git commit -m "feat: add User model with validation"
# Session 2: Build repository layer
git commit -m "feat: add UserRepository with CRUD operations"
# Session 3: Build API endpoints
git commit -m "feat: add user REST endpoints"

Each session is self-contained. Context loss between sessions doesn’t matter.

Solution 2: Re-establish Context After Compaction

When you detect context loss:

  1. Check git log for recent decisions
  2. Review modified files for patterns
  3. Summarize current approach to Claude
  4. Ask Claude to confirm understanding

Example prompt:

“We’re working on a user authentication system. We’ve already built:

  • User model (src/models/User.ts)
  • UserRepository using TypeORM (src/repositories/UserRepository.ts)
  • JWT-based auth service (src/services/AuthService.ts)

Current approach: Repository pattern with dependency injection. Please review these files to understand the established patterns before suggesting changes.”

Solution 3: Use Project Documentation

Create ARCHITECTURE.md documenting:

  • Design patterns in use
  • Key architectural decisions
  • Code organization principles
  • Stylistic conventions

When Claude loses context, you can quickly reference the documentation:

“See ARCHITECTURE.md section 2.3 for our data layer patterns”

Solution 4: Monitor Context Usage

Check token usage periodically (Claude Code shows this in the CLI).

When approaching 80% of context window:

  • Consider ending the session
  • Commit current work
  • Start fresh session

Solution 5: Verbalize Implicit Context

Bad assumption: “Claude knows we’re using the Repository pattern”

Better: “We’re using the Repository pattern for data access. All database interactions go through repository classes.”

Explicitly stating context makes it more likely to survive compaction, as it’s more likely to be captured in summaries.

The Context Handoff Technique

When ending a session near compaction, create a CONTEXT.md file:

Session Summary for Next Session:
==================================
Feature: User authentication system
Decisions Made:
1. Using Repository pattern for data layer
2. JWT for authentication, stored in HTTP-only cookies
3. Password hashing with bcrypt (10 rounds)
4. Input validation with Zod schemas
Files Modified:
- src/models/User.ts (user entity)
- src/repositories/UserRepository.ts (data access)
- src/services/AuthService.ts (auth logic)
- src/middleware/auth.ts (route protection)
Next Steps:
- Add refresh token rotation
- Implement rate limiting
- Add password reset flow
IMPORTANT: Maintain Repository pattern throughout.
All new database code should follow existing UserRepository structure.

Save this as CONTEXT.md in your project root. At start of next session:

“Read CONTEXT.md to understand our current work and decisions.”

Spotting Context Loss

How do you know when Claude has lost context?

  • Suggests code that already exists
  • Contradicts previous decisions
  • Asks about files we just created
  • Uses different patterns than established

Example of context loss symptoms:

// Context intact: Claude extends existing pattern
class OrderRepository {
async findById(id: string): Promise<Order | null> {
// Follows established Repository pattern
}
}
// Context lost: Claude creates duplicate
class OrderService {
async findOrder(id: string): Promise<Order | null> {
// Direct database access - contradicts Repository pattern!
}
}

When Context Loss is Actually OK

Not all context loss is bad:

  • Fresh perspective can reveal better approaches
  • Prevents accumulated context baggage
  • Forces explicit documentation of decisions

The key: Make context loss intentional, not accidental. Choose when to reset, don’t let it surprise you mid-feature.

FAQ

Can I disable context compaction?

No, it’s automatic in Claude Code. But you can manage when it happens using the strategies above.

How much context does Claude retain after compaction?

Roughly 20-30% of original detail. Summaries focus on “what happened” and lose “why” and subtle details.

Is this a Claude-specific problem?

All LLMs have context windows and face compaction challenges. Claude Code’s compaction is particularly aggressive.

How do I know when compaction happened?

Claude Code shows a notification in the CLI when compaction occurs. You can also monitor token usage in the interface.

The Bottom Line

Context compaction isn’t a bug - it’s a fundamental constraint of how LLMs work. The key is to work with it, not against it. By organizing your work into self-contained units, documenting decisions explicitly, and re-establishing context when needed, you can maintain productivity even with compaction.

The strategies I’ve shared come from real production use - not theory. They’ve saved me countless hours of duplicated work and contradictory code. Use them, and you’ll spend less time fighting context loss and more time shipping features.

Final Words + More Resources

My intention with this article was to help others share my knowledge and experience. If you want to contact me, you can contact by email: Email me

Here are also the most important links from this article along with some further resources that will help you in this scope:

Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!

Comments