Claude Code Advanced: Token Optimization & Mastering Large-Codebase Context (2026)
To optimize token usage in Claude Code on a large codebase, measure first with /context and /usage, then pull the six biggest levers: (1) proactively /clear and /compact between tasks; (2) pick the right model (Sonnet for most work, save Opus); (3) trim MCP overhead and prefer CLIs; (4) offload heavy work to hooks and skills; (5) use subagents plus just-in-time retrieval; (6) manage sessions and caching. If you do not measure, you will not know which technique is worth doing first.
- The commands and numbers in this article come from Anthropic's official docs (fetched 08/2026). Claude Code updates very often, so check claude --version and re-run /usage on your own machine to compare.
Why does Claude Code burn tokens on a large codebase?
A lot of devs get frustrated that "one small question and my usage climbs all day." The cause is not that question - it is how language models work: every request resends the entire conversation (system prompt, CLAUDE.md, history, files read, tool results) as input. The longer the session, the more each exchange costs, because that trailing context keeps growing.
Three mechanisms compound to drive the cost up:
- Long context pile-up: the more files you pull into context, the heavier every subsequent turn gets - even when you never touch those files again.
- Context rot: per Anthropic's article Effective context engineering for AI agents (2025-09-29), as the number of tokens in the window grows, the model's ability to recall important information actually drops. So a bloated context is not just more expensive, it also makes Claude less accurate.
- Cache misses: Claude Code caches the front of the prompt so you are not billed for it again. But the cache expires; step away too long and come back, and the whole context block gets billed at full price all over again.
On baseline cost, Anthropic's "Manage costs effectively" documentation (docs, fetched 08/2026) reports an average of roughly ~$13/dev per active day, with most usage landing around $150-250/month, and 90% of users staying under ~$30/day. If you are running well past that on a large codebase, there is almost certainly wasted token spend in a few predictable spots. To understand the plans and how billing works, see our guide to Claude Code pricing and plans. And if you are just starting out, read what Claude Code is first to get the fundamentals.
Measure first, optimize later - /context, /usage, statusline
Do not optimize blind. Before you touch any technique, take a snapshot of the current state so you know where your tokens are going. These two commands are the starting point:
/usage # token & cost overview: input, output, cache read/write, cost
/context # breaks down what is taking up your CURRENT context right now
/usage gives you the money picture: how many input tokens, output tokens, how much was read from cache (cheap) versus written to a new cache (expensive). A high cache-read ratio is a good sign. /context is the more valuable of the two when you are optimizing: it separates out the system prompt, CLAUDE.md, the MCP tools you have declared, and the files you have pulled in - showing you exactly what is hogging space.
You should also enable a context readout in your statusline so you can watch it continuously without typing a command - details in our guide to customizing the Claude Code statusline. The rule: only before/after numbers tell you which technique was actually worth the effort. Run /context right before and after each change below to measure the real delta.
Group 1 - Proactive context management (/clear, /compact, resume)
This is the cheapest, highest-impact lever there is. Most wasted tokens come from dragging stale, unrelated context into a new task.
/clear between unrelated tasks. Just finished fixing a bug in the auth module and now switching to writing tests for the payment module? Type /clear. It resets context to the start - the "conversation tail" cost drops back to near $0 for the new task. This is the single most important token-saving habit that most people skip.
/compact when you need to keep the thread going. When you want to continue the same line of work but context has ballooned, /compact squeezes the conversation into a summary. Important: use a directed compact so you do not lose exactly what you need:
/compact Keep the database schema decisions and the files changed in the payment module; drop the long debug logs
You can preset "Compact instructions" in CLAUDE.md so every compact keeps the same priorities. Claude Code also has auto-compact: when context gets near full, it compacts on its own so the session does not break. Convenient, but an honest warning - auto-compact can drop details, so for sensitive tasks, run a directed manual compact instead of leaving it to chance.
Resume from summary. When reopening a large session, choose to resume from the summary rather than reloading the full history - you start with a few thousand tokens instead of tens of thousands. To dig into this mechanism, read our guide to managing context and memory in Claude Code.
Group 2 - Pick the right model & tune extended thinking
Not every task needs the strongest model. Here is how to allocate by cost (reference API pricing: Opus 5 $5/$25 per 1M tokens in/out; Sonnet 5 $2/$10; Haiku 4.5 $1/$5):
- Sonnet for most coding. Sonnet 5 handles the vast majority of writing and editing code at a fraction of Opus's cost.
- Save Opus for architecture & hard problems. Switch with
/modelmid-session when you hit something that needs deep reasoning, then switch back to Sonnet. - Haiku for simple subagents. For a subagent doing purely mechanical work (grep, summarize, format), set
model: haikuin its definition.
Extended thinking is a double-edged sword for tokens. The "thinking" is billed as output tokens - and output costs several times more than input. On simple, repetitive tasks, heavy thinking is just burning money. How to control it:
/effort # tune the reasoning effort to fit the task
MAX_THINKING_TOKENS=8000 # cap thinking tokens (environment variable)
You can also turn extended thinking off in /config. An honest caveat: turning thinking off hurts deep-reasoning tasks (algorithm design, multi-layer debugging) - this is a trade-off, not an "always off to save money" rule. Only dial it down or off when the task genuinely does not need much reasoning.
Group 3 - Trim MCP & tool overhead
Every MCP server you enable pays a context "tax": its tool list (names, descriptions, parameter schemas) is loaded into every request. A few servers with many tools can eat thousands of tokens before you type a single character. Use /context to inspect this.
- Disable servers you are not using:
/mcpto view and manage connected servers; turn off whatever you do not need for the current session. - Prefer CLIs over MCP when you can. For tasks that already have a command-line tool -
gh(GitHub),aws,gcloud- let Claude call the CLI directly through Bash instead of wiring up an equivalent MCP server. A CLI does not carry the standing "tool listing" cost in context. - Code intelligence for typed languages. For TypeScript/Java/Go, a "go to definition" plugin lets Claude jump straight to a definition instead of grepping and reading a pile of files - cutting file-read tokens meaningfully on a large codebase.
To understand MCP and when to use it or not, see the piece on hooks in Claude Code in the next group - these two mechanisms often work together to reduce context.
Group 4 - Offload heavy work to hooks & skills
This is the group with the biggest payoff that the fewest people exploit. The idea: do not let bulky output flow straight into Claude's context - filter or summarize it at the script layer first.
A hook to filter test output. One run of a big test suite can print tens of thousands of lines - but Claude only needs to know what FAILED. A PreToolUse/post-processing hook that keeps only FAIL/ERROR lines can pull the token count from tens of thousands down to hundreds (per the "Manage costs effectively" docs). Example skeleton of a filter script:
#!/usr/bin/env bash
# filter-test-output.sh - keep only failing lines, cut the noisy log
npm test 2>&1 | grep -E "(FAIL|ERROR|✕|Error:|Expected|Received)" | head -n 100
A "codebase-overview" skill. Instead of having Claude read 20 files to understand the project structure every time, package a skill that describes the architecture, conventions, and where the main modules live. A skill loads on demand, so it does not sit permanently in context - but when needed, it gives instant context instead of a barrage of file reads.
Keep CLAUDE.md lean. Anthropic's docs recommend keeping CLAUDE.md under ~200 lines. Everything in this file loads into every request, so cramming it full is a permanent token tax. Move specialized instructions (a deploy procedure, one module's conventions) into an on-demand skill, and keep only what you truly use in every session in CLAUDE.md.
Group 5 - Subagents & just-in-time retrieval for large codebases
On a monorepo, the number-one enemy is letting a single context "scan" the whole repo. The fix is to isolate the heavy reading away from the main context.
Delegate research to a subagent. When you need to survey "where is feature X implemented," hand it to a subagent. It reads a batch of files in its own context and returns only a summary - per Anthropic's engineering article, typically just ~1,000-2,000 tokens instead of dumping full file contents into the main context. See the detailed walkthrough in our guide to subagents in Claude Code.
Just-in-time retrieval with @ references. Do not let Claude guess and grep around blindly. Point it straight to what it needs, when it needs it:
@src/payment/checkout.ts # load exactly one file when needed
@src/payment/ # load exactly one directory
Plan mode to avoid expensive re-work. Press Shift+Tab to enter plan mode: Claude plans before it edits. Reviewing a plan is far cheaper than letting it mis-edit a batch of files and then having to redo the work - and every redo loop costs tokens. If it heads the wrong way, use /rewind (or press Esc twice) to return to a previous checkpoint instead of re-describing everything from scratch.
The principle that ties this whole group together, borrowed from Anthropic: aim for minimal high-signal tokens - put as little into context as possible, but exactly the most valuable pieces. This is also the cure for the context rot mentioned at the top of the article.
Token traps: agent teams & all-day sessions
These two quietly inflate your usage in ways that are hard to notice.
Agent teams ~7x tokens. Running a "team" of many agents in parallel sounds powerful, but the "Manage costs effectively" docs warn that it uses roughly ~7x the tokens of a normal session (using plan mode). The reason: each teammate has its own context. When not to use it: sequential tasks, small scope, or when your token budget is tight. If you must, run the teammates on Sonnet and shut the team down as soon as you are done.
All-day sessions. Leaving a single session running from morning to evening is a recipe for burning tokens: long context bloats, and the cache keeps missing every time you step away. On caching, the docs note the lifetime is 1 hour on subscription plans versus 5 minutes with usage credits/API; you can enable the 1-hour cache with an environment variable:
ENABLE_PROMPT_CACHING_1H=1
Good habits: /clear when switching work, close the session for long breaks, resume from summary when you come back. (A small note for peace of mind: the background tokens for Claude Code's automatic tasks are very cheap - the docs cite < $0.04/session, so do not worry about that part.)
Summary table - technique to token savings
Sorted by token ROI (high leverage / low effort at the top). Where the "savings" column has an Anthropic source, we cite the verified number; the parts measured on a real codebase are for Jasmine to fill in from her test session.
| Technique | Effort | Savings | When to use |
|---|---|---|---|
/clear between unrelated tasks | Very low | Resets the context "tail" to ~0 for the new task | Every time you switch to unrelated work |
Directed /compact | Low | When you need to keep the thread but context has bloated | |
| Hook to filter test output | Medium | Tens of thousands → hundreds of tokens (Anthropic docs) | Codebase with a large test suite/logs |
| Keep CLAUDE.md < 200 lines | Low | Cuts the fixed token tax on every request | Always - clean up periodically |
| Choose Sonnet, save Opus | Low | Opus/Sonnet price gap ~2.5x (in), 2.5x (out) | Default for daily coding |
| Trim unused MCP / prefer CLI | Medium | Many MCP servers enabled | |
| Subagent returns a summary | Medium | Returns ~1-2k tokens instead of full file reads (Anthropic docs) | Surveying/research on a large codebase |
| Reduce/disable extended thinking | Low | Cuts output tokens on simple tasks | Repetitive tasks not needing deep reasoning |
| Avoid agent teams when unneeded | Low | Avoids ~7x token cost (Anthropic docs) | Sequential tasks / tight budget |
Speed it up with a prebuilt kit (AgentKit)
Many of the techniques above - the "codebase-overview" skill, specialized subagents, output-filtering hooks - are effective but take real effort to build and tune yourself. If you would rather have a ready-made set of context-optimized skills, subagents, and hooks for Claude Code, the AgentKit kit for Claude Code packages this toolset so you do not have to write it from scratch.
One note to avoid confusion: AgentKit here (agentkit.best, CLI ak) is a kit for Claude Code / Codex / Copilot - completely different from OpenAI's AgentKit. You can check out AgentKit (20% off via link) and judge for yourself; this is an optional suggestion, not a requirement - every technique in this article can be done by hand.
Frequently asked questions (FAQ)
When do I use /compact versus /clear?
Use /clear when you switch to an unrelated task - it resets context and cuts the "conversation tail" cost to near zero. Use /compact when you want to continue the same line of work but context has bloated; it squeezes the history into a summary while keeping your thread going.
Does Claude Code compact automatically?
Yes. When context gets near full, Claude Code auto-compacts so the session does not break. Convenient, but it can drop details, so for important tasks run a directed /compact yourself instead of leaving it to chance.
Is using Opus much more expensive?
Yes - per reference API pricing, Opus 5 ($5/$25 per 1M in/out) is about 2.5x more expensive than Sonnet 5 ($2/$10). Let Sonnet handle most of the coding and only switch /model to Opus for architecture or hard problems.
How do I see the tokens I am using?
Type /usage to see total input/output tokens, cache read/write, and cost; type /context to see which components are taking up your current context (CLAUDE.md, MCP tools, files read). Measure with these two before and after each change.
On a large codebase, where should I start optimizing?
Start by measuring with /context, then prioritize the two cheapest levers: /clear between tasks and trimming CLAUDE.md down under ~200 lines. After that, move to cutting excess MCP, using subagents for research, and a hook to filter test output.
Is turning off extended thinking harmful?
It can be. Disabling thinking saves output tokens but lowers quality on deep-reasoning tasks (algorithm design, multi-layer debugging). Only dial it down with /effort or MAX_THINKING_TOKENS=8000 for simple tasks, and keep thinking for work that needs reasoning.
Conclusion + next steps
The formula for optimizing Claude Code tokens fits in one chain: measure → cut context → choose model → offload to hooks/skills → subagents for large codebases. Do not do it all at once; measure with /context and /usage, pick the 2-3 highest-ROI levers from the table, apply them, and measure again. Remember that the savings depend on your codebase and habits - measure on your own machine.
Read next: managing context and memory to go deeper on compaction, and Claude Code pricing and plans to pick the plan that fits your usage. If you would rather use a prebuilt toolset than optimize by hand, check out our AgentKit review for Claude Code.
Want a stronger Claude Code right away? If you would rather not build context-optimized skills, subagents, and hooks yourself, AgentKit packages this toolset for Claude Code - worth a look to save setup time.