Token Optimization When Using Claude Code: Best Practices for Long-Running Sessions
Use trigger-table lazy loading, strategic model selection, and the /compact command at logical milestones to cut token consumption by 50% or more while maintaining context quality.
Token optimization is critical for productive Claude Code sessions, as every file read, skill loaded, and conversation turn consumes your finite context window. The affaan-m/everything-claude-code repository provides a comprehensive playbook for token efficiency, combining architectural patterns from the Strategic-Compact skill with high-level economy strategies documented in the Longform Guide.
Architectural Foundations from the Strategic-Compact Skill
The skills/strategic-compact/SKILL.md file defines the core architecture for preventing context bloat. These patterns work by deferring load until necessary and eliminating redundant content.
Trigger-Table Lazy Loading
Instead of loading every skill at session startup, implement a trigger table that maps keywords to skill paths. According to lines 99-107 in SKILL.md, the system loads a skill only when you mention specific trigger words, saving 50% or more of baseline tokens.
Configure your trigger table in a custom skill file:
{
"triggers": {
"test": "skills/tdd-workflow",
"security": "skills/security-review",
"deploy": "skills/deployment-patterns",
"auth": "skills/security-review"
}
}
When you type "run tests," Claude Code loads tdd-workflow only at that moment rather than keeping it resident.
Context Composition Awareness
Monitor which artifacts consume tokens to make informed pruning decisions. As documented in lines 110-115 of skills/strategic-compact/SKILL.md, track these four sources:
- CLAUDE.md files — always loaded; keep them under 200 lines
- Loaded skills — each adds approximately 1,000-5,000 tokens
- Conversation history — grows with every exchange
- Tool results — file reads and searches append raw output to context
Duplicate Instruction Detection
Consolidate shared logic to a single source to eliminate redundant tokens. Lines 117-121 in SKILL.md warn against loading identical rules from multiple locations, such as both ~/.claude/rules/ and project-level .claude/rules/. Store global guidelines in one location and reference them rather than duplicating content.
Context Optimization Tools
Two built-in utilities provide aggressive compression:
token-optimizerMCP — deduplicates content automatically, achieving greater than 95% token reductioncontext-mode— virtualizes a 315 KB context down to approximately 5 KB (lines 124-126)
High-Level Token Economy Patterns
The the-longform-guide.md file (lines 105-141) outlines workflow-level strategies that reduce tokens across the entire session lifecycle.
Choose Models Strategically with Sub-Agent Architecture
Allocate the cheapest suitable model per task to minimize per-token costs while preserving quality. The model selection table in lines 16-23 specifies:
- Haiku — for exploration, file finding, and simple searches
- Sonnet — for multi-file implementation and refactoring
- Opus — for security audits and complex architectural decisions
Example usage:
/think Haiku find-files matching "auth"
/think Sonnet refactor-user-module
/think Opus security-audit-payment-flow
Replace grep with mgrep
Substitute standard grep with the specialized mgrep tool to achieve approximately 50% token reduction for file searching. Lines 36-39 document that mgrep returns compact result sets rather than raw terminal output, significantly reducing what Claude Code must parse.
# High token cost
grep -r "TODO" src/
# Optimized token usage
mgrep "TODO" src/
Keep Codebases Modular
Maintain core files in the hundreds rather than thousands of lines. As noted in lines 41-44, modular codebases improve both token usage and edit accuracy by allowing Claude to load only relevant files rather than entire monolithic modules.
Practical Implementation
Configuring Lazy Loading Hooks
Add the strategic-compact hook to your project and configure automatic skill loading:
// In your project configuration
{
"compact_triggers": [
"after planning",
"before implementation",
"after tests pass"
],
"lazy_load_skills": true,
"trigger_table_path": "./config/triggers.json"
}
Running /compact at Logical Milestones
Manually invoke compaction at context-heavy transition points:
/compact after planning -- clear research context
/compact before deploy -- remove test files from context
The suggest-compact.js utility (referenced in SKILL.md) automatically prompts for compaction after you save plan files such as plan.md, consuming only a handful of tokens while dropping thousands of research tokens.
Tool Substitution Workflows
Replace high-verbosity tools with token-efficient alternatives:
- Use
mgrepinstead ofgrepfor searches - Use
token-optimizerMCP before loading large documentation - Use
context-modewhen referencing external libraries over 300 KB
Summary
- Implement trigger-table lazy loading in
skills/strategic-compact/SKILL.mdto load skills only when trigger words appear, cutting baseline token usage by 50% - Monitor context composition from four sources: CLAUDE.md files, loaded skills, conversation history, and tool results
- Consolidate duplicate instructions to avoid loading identical rules from both global and project-level directories
- Use
/compactat milestones such as after planning or before deployment to prune obsolete context - Select models strategically: Haiku for exploration, Sonnet for coding, Opus for security
- Substitute
grepwithmgrepto halve token consumption during file searches
Frequently Asked Questions
How do I know when to run the /compact command?
Run /compact after completing distinct phases such as research, planning, or testing. According to the Strategic-Compact skill (lines 99-107), logical milestones include immediately after saving a plan.md file, before switching from exploration to implementation, or after a successful test suite run. The command removes prior conversational context while preserving your codebase state.
What is the difference between token-optimizer and context-mode?
The token-optimizer MCP tool actively deduplicates content within your current context, achieving over 95% token reduction by removing redundant text. The context-mode utility virtualizes large external contexts—compressing a 315 KB file down to approximately 5 KB—without loading the full content into your working memory. Use token-optimizer for deduplication and context-mode when referencing massive external libraries.
Can lazy loading slow down my workflow?
No. The trigger-table implementation in skills/strategic-compact/SKILL.md loads skills in milliseconds when trigger words are detected. Since skills typically add 1,000-5,000 tokens each, lazy loading improves response latency by keeping the context window lean while only incurring the load cost once per session when the skill is actually needed.
Why does file size matter for token optimization?
Claude Code loads entire files into context when making edits or answering questions about them. As documented in the-longform-guide.md (lines 41-44), files with thousands of lines consume proportionally more tokens than modular files with hundreds of lines. Smaller files allow Claude to load only relevant modules rather than entire monolithic codebases, reducing both token usage and improving the accuracy of multi-file edits.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →