CLAUDE LABJP
TEACHERS — Anthropic launches Claude for Teachers, giving verified US K-12 educators free premium access, teaching skills, and curriculum links aligned to standards in all 50 statesADMIN — The Admin API is now in beta for every Claude Enterprise organization: member and invite calls need no beta header, while group and custom-role calls doM365 — The Microsoft 365 connector gains write tools — draft, send, and organize email, manage calendar events and mailbox settings, and create or update files in OneDrive and SharePointMCP — Fixed servers from --mcp-config or .mcp.json ignoring a per-server request_timeout_ms, which left long-running tool calls timing out at the 60s default in fresh sessionsSUBAGENT — A new --forward-subagent-text flag and CLAUDE_CODE_FORWARD_SUBAGENT_TEXT variable include subagent text and thinking in stream-json outputDEADLINE — Opus 4.7 fast mode is removed on July 24, seven days out. speed: "fast" will error, so confirm your move to Opus 4.8TEACHERS — Anthropic launches Claude for Teachers, giving verified US K-12 educators free premium access, teaching skills, and curriculum links aligned to standards in all 50 statesADMIN — The Admin API is now in beta for every Claude Enterprise organization: member and invite calls need no beta header, while group and custom-role calls doM365 — The Microsoft 365 connector gains write tools — draft, send, and organize email, manage calendar events and mailbox settings, and create or update files in OneDrive and SharePointMCP — Fixed servers from --mcp-config or .mcp.json ignoring a per-server request_timeout_ms, which left long-running tool calls timing out at the 60s default in fresh sessionsSUBAGENT — A new --forward-subagent-text flag and CLAUDE_CODE_FORWARD_SUBAGENT_TEXT variable include subagent text and thinking in stream-json outputDEADLINE — Opus 4.7 fast mode is removed on July 24, seven days out. speed: "fast" will error, so confirm your move to Opus 4.8
Articles/Claude Code
Claude Code/2026-05-31Intermediate

What to Do When Claude Code Hits the Context Window Limit

Long Claude Code sessions eventually hit the 200k token limit and stall. Here's how to use /compact, --continue, and session design patterns to keep development moving without losing context.

Claude Code196context window2error handling3troubleshooting87compact

One of the most disruptive issues in long Claude Code sessions is hitting the context window limit mid-task. You're deep into a refactor, files are being read, edits are piling up — then everything stops.

As an indie developer, I use Claude Code daily — running the automated content pipelines for Dolice Labs, building AdMob reporting scripts, and maintaining four production sites in parallel. Context exhaustion is the error I hit most consistently in long sessions. Once you understand the mechanics, it becomes straightforward to work around.

What the Error Looks Like

As Claude Code approaches the context limit, it surfaces in a few forms depending on how far over you are.

Warning phase (around 80% capacity):

Claude's context window is getting full.
Use /compact to compress the conversation.

Hard stop (limit exceeded):

This conversation is too long to continue.
Please start a new conversation or use /compact.

If the limit is exceeded at the API level before Claude Code can intercept it, you'll see a raw error in the terminal:

{
  "error": {
    "type": "invalid_request_error",
    "message": "prompt is too long: 210741 tokens > 200000 maximum"
  }
}

Why It Happens

Claude Sonnet 4's context window is 200,000 tokens. Every Claude Code session accumulates the following in that space:

  • Conversation history: your messages and Claude's responses, in full
  • Tool results: file contents from Read calls, bash command output
  • CLAUDE.md: your project instructions, loaded at session start
  • Edit history: before/after content for each file modification

The first time this became a real problem for me was when I tried to audit and fix a series of issues across multiple source files in one session. Ten sequential Read calls into a moderately sized TypeScript project and I was already past 150,000 tokens before any edits had even started.

Fix 1: Use /compact to Compress In-Place

When you want to keep the current session alive, /compact is the right first move.

/compact

This prompts Claude to summarize the conversation history, replacing detailed tool results and back-and-forth exchanges with a condensed summary. Token count drops significantly, and the session can continue.

Confirm the summary before proceeding: Claude sometimes presents the compressed summary for review before finalizing. Check that your current working state — which files are being modified, what decisions have been made — is captured accurately.

Important: /compact is irreversible. Once compressed, the detailed conversation history is gone. If you need to trace back through earlier reasoning, do that before compressing.

Fix 2: Start a New Session with --continue

If you've reached a natural stopping point, starting a fresh session is often cleaner than compressing a long history.

# Resume the most recent session
claude --continue
 
# Resume a specific session by ID
claude --resume <session-id>
 
# List available sessions
claude --list-sessions

--continue carries forward a summary of the previous session, not the full history. This means file contents, earlier tool outputs, and intermediate reasoning are not directly available. At the start of the new session, re-state the important context explicitly: which file you were working in, where you left off, and what the next step is.

Fix 3: Design Sessions to Stay Small

The most reliable long-term solution is scoping each session tightly enough that context exhaustion rarely happens.

One session = one commit's worth of change

Rather than opening a session with "improve the overall quality of this repo," start with "add error handling to the fetchArticle function in src/lib/content.ts." Narrow scope means fewer files get read, fewer decisions get made, and the session ends before the limit is approached.

Read only what you need

# Costly: asks Claude to load everything
# "Look at the whole src/ directory and find the problem"
 
# Efficient: direct targeting
# "Read src/lib/content.ts and check the return type of getArticle"

Commit often

Frequent commits create natural restart points. When a new session begins, git log --oneline -5 gives Claude the full context of what was completed in a few dozen tokens — far cheaper than re-reading files.

Prevention Habits Worth Building

Keep CLAUDE.md lean

Project instruction files get loaded at session start on every run. If yours has grown to cover every edge case and historical decision, it may be consuming tens of thousands of tokens before any work begins. Move stable reference material into separate documents and link to them rather than inlining everything.

Trim command output

# Token-heavy
git log --stat       # includes full file diff stats per commit
 
# Token-efficient
git log --oneline -10   # just the last ten commit summaries

Use offset/limit when reading large files

Claude Code's Read tool accepts offset and limit parameters. Instead of reading an entire 800-line file, read only the relevant section. This alone can reduce per-task token usage substantially on large codebases.

/compact vs. /clear: Knowing the Difference

These two commands look similar but behave very differently:

  • /compact — replaces conversation history with a summary, preserving context while reducing tokens
  • /clearcompletely resets the conversation, as if starting fresh

Use /compact when you're mid-task and want to continue with the same thread. Use /clear when you're switching to an entirely different task and the current history is no longer relevant.

Summary

When you hit the context limit, the decision tree is straightforward:

Still mid-task → /compact to compress and continue in place.
At a stopping point → claude --continue or --resume to start a clean session.
Long-term fix → keep sessions scoped to single commits and commit frequently.

The "one session = one commit" approach has made the biggest difference in practice. Context issues drop, work is easier to track, and sessions end in a clean state rather than getting compressed under pressure.

Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

Claude Code2026-07-01
My Claude Code Hooks Stopped Firing After an Update — the Hyphenated Matcher Exact-Match Change in v2.1.195
In Claude Code v2.1.195, hook matchers containing a hyphen switched from partial match to exact match, silently disabling an existing PreToolUse hook. Here is how I isolated the cause and how to write matchers that won't break.
Claude Code2026-05-30
Why git Says detected dubious ownership in repository — and How to Get Past It
An automation that ran fine yesterday suddenly dies on detected dubious ownership in repository. Here is what actually triggers it, the safe.directory fix, and how it differs from a real Permission denied.
Claude Code2026-05-27
When Claude Code's Bash Tool Hits Permission Denied on /tmp — A $HOME/repos Fallback Pattern
A practical look at why git clone inside Claude Code's sandboxed Bash sometimes fails with Permission denied on /tmp, and how a tiny $HOME/repos fallback keeps unattended schedules alive across four indie sites.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →