Claude Code — context window exhausted mid-task
Agentic coding sessions burn through context faster than any other Claude workflow. Files read into context, tool outputs, and long chains of edits saturate the 200K window quickly. Managing it is a skill.
Quick fix (TL;DR)
/compact preemptively at natural breakpoints, (b) using /clear between unrelated subtasks, (c) reading large files with line ranges instead of full contents, and (d) splitting genuinely-long tasks across sessions with checkpointed state.Real error messages you'll see
These are the exact strings returned by the Claude API service and its SDKs when this error occurs. Copy-paste-searching any of them should land on this page.
⚠ Context window at 92% (183,254 / 200,000 tokens) Run /compact to summarise older messages, or /clear to reset the session.
Error: Context window exhausted (204,832 tokens > 200,000 limit). Auto-compact could not free enough space. Run /clear or start a new session.
anthropic.BadRequestError: Error code: 400 - prompt is too long: 208912 tokens > 200000 maximum
Reference
What consumes context in a Claude Code session
| Source | Typical footprint | Reduction technique |
|---|---|---|
Full-file Read | Whole file tokenized | Use line ranges |
| Bash output | Entire stdout/stderr | Redirect to a file, read summary |
| Tool calls (MCP) | Result payload | Return trimmed data server-side |
| System prompt + tools | ~10-20K tokens | Fixed cost |
| Prior turns | Accumulates | /compact or /clear |
| SKILL.md files loaded | 2-8K each | Load only what is needed |
| Screenshot / image | 1-2.5K each | Downscale before send |
Session-management commands (Claude Code)
| Command | Effect |
|---|---|
/compact | Summarise older turns, keeping recent context |
/compact <instructions> | Compact with focus (e.g. "keep all bash commands used") |
/clear | Full reset — new session, no history |
/context | Show token counts by source |
/resume | Resume a previous session by ID |
Root causes, ranked by frequency
Based on developer reports across Claude API forums, GitHub issues, and Anthropic community during 2025–2026.
- 24%Full-file reads of large sources.
Read(./src/main.py)on a 3K-line file adds ~15K tokens. Multiple such reads exhaust context before the task begins. - 18%Verbose bash output cached in context. Running
npm testor a large build dumps 20-50K tokens of logs. All retained in context. - 14%Long-running task without
/compact. 50-turn coding session with no compaction; context creeps toward the limit. - 10%Multiple MCP tools returning large payloads. Database queries returning full rows; Github API returning entire diff.
- 8%Screenshots in Computer Use mode. Every screenshot is 1.5-2.5K tokens; 20-iteration session accumulates 30-50K.
- 7%SKILL.md over-loading. Many skills loaded proactively even when the task uses one.
- 8%Repeated file re-reads. Agent forgets it read a file already and reads it again — every duplicate wastes tokens.
- 11%Deep tool-use chains preserved verbatim. Long tool_use → tool_result → tool_use sequences; each result adds context that stays for later turns.
Fixes — copy-paste solutions
Compact preemptively at natural task boundaries
Run /compact after completing a distinct subtask. This summarises older messages so the current context has room for the next subtask. Optional instructions preserve details you know you will need.
# Session flow that keeps context healthy # --- Phase 1: implement feature A --- > Read the existing auth module and add a new SSO provider. [Claude reads files, edits code, runs tests] > Great. Now /compact "keep the file paths I edited and the new provider name for future reference" # Claude summarises phase 1 in a few hundred tokens # --- Phase 2: implement feature B --- > Add a settings page for the new SSO provider. [Claude works on phase 2 with room to spare] > Ok. /compact "keep the file paths and route names" # --- Phase 3: run the full test suite and fix regressions --- > Run npm test and fix anything that broke. [Long output, many edits — but we have context because we compacted] # --- If a truly unrelated task --- > /clear # full reset, start fresh > Now, unrelated: refactor the analytics module.
/compact are gold. "Keep the file paths and function signatures I introduced" is much better than a bare /compact, which uses a generic summarisation.Read files with line ranges instead of full contents
Ask Claude to use the Read tool's offset and limit parameters when navigating large files. Also encourage grep-first workflows — find the range first, then read only that range.
# Guide the agent toward line-scoped reads # --- BAD: whole-file read --- > Read src/big_module.py # → 15K tokens # --- GOOD: grep, then range-read --- > Find the definition of process_batch in src/big_module.py, then read a > 40-line window around it. [Claude runs: rg -n "def process_batch" src/big_module.py → line 847 Reads src/big_module.py, offset=827, limit=40 → ~1K tokens] # --- Codify in .claude/CLAUDE.md --- # CLAUDE.md is auto-loaded per project. Add: ``` When reading files larger than 500 lines, first use grep or ripgrep to locate the relevant symbol, then Read with offset/limit for a 30-50 line window. Do NOT read whole large files. ``` # Now every session in this project follows the pattern automatically
Split truly-long tasks across sessions with checkpointed state
For migrations, large refactors, or long bulk operations, checkpoint state to disk. End the session with a written summary that a fresh session can pick up from.
# Pattern for multi-session tasks # End of session 1: > We're at 85% context. Before we hit the limit, write a handoff file > ./HANDOFF.md that documents: > 1. What we've done (files edited, tests written) > 2. What remains (with specific file paths and line refs) > 3. Any decisions we made and why > 4. Commands to re-establish the working state (branch name, npm version) [Claude writes HANDOFF.md] > /exit # Start of session 2 (fresh /clear): > Read HANDOFF.md and continue the task from where we left off. [Claude reads a few KB of structured handoff, starts fresh with full context budget] # For very long tasks, do this every 2-3 hours: > Update HANDOFF.md with today's progress. Then /compact.
Prevention checklist
Ship these seven safeguards once and this error stops appearing in your logs.
- Run
/compactat every natural task boundary — before you need it. - For files > 500 lines, always grep first and Read with
offset/limit. - Redirect large bash output to a file (
> /tmp/build.log) and only Read the tail. - Add a project
CLAUDE.mdencoding your team's context-hygiene rules. - For multi-session work, checkpoint state to a HANDOFF.md file explicitly.
- Watch the token counter —
/contexttells you where the tokens went. - Split unrelated subtasks across separate sessions with
/clear; do not mix them in one long session.
Frequently asked questions
/compact summarises older turns and keeps the compacted history plus recent turns — Claude "remembers" the task. /clear is a full reset — Claude has no prior context. Use /clear when switching to a truly unrelated task./compact) and split tasks across sessions. Extended-context model variants may be available at higher cost tiers.Related errors & hubs
Get the weekly AI-error digest
New fixes, provider status recaps, and one deep tutorial — every Tuesday. 8,400+ engineers.