Reduce Claude Code Token Usage: Context Mode and Headroom
Measure Claude Code context and billing separately, trim noisy tool output, and choose between Context Mode and Headroom. Follow verified setup paths, check retrieval and cache behavior, and use cheaper models only for bounded, verifiable subtasks.
Contents

To reduce Claude Code token usage, identify what fills the context, then keep unnecessary tool output out of the conversation. Start with Claude Code’s native controls; try Context Mode for selective processing and continuity across compaction, or Headroom for compression through a local proxy. If reasoning and repeated failed attempts dominate your usage, improve task scope and model selection before adding either tool.
As of 2026-10-21, the current Claude Code release is 2.1.306. The Headroom installation below pins version 0.41.0.
Where are Claude Code tokens going?
Use /context to diagnose context occupancy and /usage to inspect usage and estimated cost. They answer different questions.
| Question | Check | What it tells you |
|---|---|---|
| Why is this conversation filling up? | /context | Space occupied by instructions, messages, tools, and other context |
| What did this session consume? | /usage | Token categories and estimated session cost |
| Am I approaching a subscription allowance? | The plan information in /usage | Plan usage, separate from an API invoice |
| What was actually charged? | Your billing provider’s usage records | Charges under that provider’s rates and billing rules |
In current Claude Code, /cost is an alias for /usage. The dollar figure is an estimate; it does not mean that every included Pro or Max request generates that additional charge. See the distinction in Claude Code’s cost documentation.
Large logs, browser snapshots, dependency files, and repeated tool results can occupy substantial context. Previous messages also participate in subsequent requests, but prompt caching can make reused input cheaper than fresh input. A 50% reduction in visible content therefore does not automatically produce a 50% lower bill.
Use native controls before adding compression
Match the control to the source of waste: narrow retrieval for noisy output, a fresh conversation for unrelated work, and compaction for a long task you need to continue.
Give Claude exact file paths, failing test names, and a concrete verification command. Asking it to inspect one failing module usually creates less unnecessary work than asking it to understand the entire repository before making a small change.
Use /clear between unrelated tasks after recording any usage figures you need. Use a targeted /compact when continuing the same task, for example:
/compact Preserve the current goal, modified files, failing test names, exact errors, and the next verification command.
These are documented context-management practices, but compaction is a summary, not exact archival memory. Keep critical acceptance criteria in durable project instructions or task notes.
Avoid compacting after every exchange. Compaction makes a summarization request and replaces the message history, so the next request must establish a shorter cached prefix. Frequent compaction can trade context savings for additional work and cache rebuilding.
For straightforward tasks on models that support effort controls, try /effort low. Lower effort can reduce reasoning work; it does not shrink a log already returned by a tool. Typed effort changes persist for the selected model, so restore your preferred setting after the comparison. The model configuration documentation explains supported controls and model aliases.
Subagents offer another native boundary: they work in separate context and return a summary. That protects the parent conversation, but their requests still consume tokens.
Context Mode vs Headroom: which should you try?
Choose Context Mode when you can reduce data before returning it to Claude; choose Headroom when you want existing tool calls to pass through a compression layer.
| Your bottleneck | Try first | What changes |
|---|---|---|
| Large files or logs that can be queried or processed locally | Context Mode | Claude uses execution and search tools to receive selected results |
| Losing selected task state after compaction | Context Mode | Lifecycle hooks record events and restore continuation information |
| Verbose output from an existing tool workflow | Headroom | A local proxy compresses eligible tool content before forwarding requests |
| Short tasks dominated by reasoning or retries | Native scope, effort, and model controls | The amount of work changes before another component is introduced |
Test one tool at a time so you can attribute the result.
The published percentages are not directly comparable. Context Mode’s benchmark material measures output bytes for selected examples. Headroom’s 21%–57% figures come from seeded offline tool-output workloads. Neither establishes the reduction in your complete Claude Code bill, and neither substitutes for checking whether the task still succeeds.
Context Mode: return the result, not the entire file
Context Mode is useful when a local operation can produce the answer without putting all its input into Claude’s conversation. Its plugin also records selected session events in SQLite and uses hooks to restore continuation information after compaction.
The current package requires Node.js 22.5.0 or newer. Check your installation in Bash:
claude --version
node --version
Inside Claude Code, use the project’s documented marketplace installation:
/plugin marketplace add mksglu/context-mode
/plugin install context-mode@context-mode
Restart Claude Code, then run:
/context-mode:ctx-doctor
The doctor command checks components including runtime support, plugin registration, hooks, and SQLite search support. Resolve relevant failures before treating the plugin as active. Installing only its MCP server does not provide the same lifecycle-hook integration.
For a concrete check, open an npm project with an existing version 2 or version 3 package-lock.json. Ask Claude to call ctx_execute_file with path: "package-lock.json", language: "javascript", and this code:
const lock = JSON.parse(FILE_CONTENT);
if (!lock.packages) {
console.log("This example requires an npm v2/v3 lockfile.");
} else {
const rows = Object.entries(lock.packages).filter(([path]) => path !== "");
console.log(JSON.stringify({
lockfileVersion: lock.lockfileVersion,
packageEntries: rows.length,
entriesMarkedDev: rows.filter(([, pkg]) => pkg.dev === true).length
}, null, 2));
}
The tool supplies the file through FILE_CONTENT. The expected result is a small JSON object containing the three requested fields, rather than the complete lockfile. Actual counts depend on your project; they count lockfile entries, not unique package names.
Then run:
/context-mode:ctx-stats
The statistics command should show Context Mode activity. If it reports no calls, the requested execution path has not been demonstrated. Its output-reduction figures are not an invoice calculation.
Apply the same pattern to logs: calculate counts locally, select relevant errors, and return exact excerpts with source locations. Keep direct reads for small source files where Claude needs the precise code.
Context Mode uses Elastic License 2.0. Its execution isolation is also not a full operating-system security sandbox: execution tools can inherit filesystem access. Preserve the permissions and sandbox controls you normally use for agent-run commands.
Headroom: put eligible tool output through a local proxy
Headroom suits workflows where you want ordinary Claude Code tools to continue operating while a proxy reduces eligible output. Its default coding-oriented behavior also considers cache stability; it does not promise to compress every source file or every request.
This example uses an Anthropic Console API key, so it incurs API charges separately from a Claude subscription. It assumes uv and Claude Code are installed, no Headroom proxy is already running, and no conflicting custom gateway or cloud-provider configuration is active. Existing organization gateways need their own integration path.
In Bash, install the versioned proxy package, following Headroom’s installation guidance:
uv tool install --python 3.13 "headroom-ai[proxy]==0.41.0"
headroom --version
The version check should identify 0.41.0. Read your key without echoing it, press Enter, and then start the wrapper:
read -rs ANTHROPIC_API_KEY && export ANTHROPIC_API_KEY
HEADROOM_TELEMETRY=on HEADROOM_BEACON=off headroom wrap claude --code-memory none
Approve the custom API key if Claude asks, then inspect /status to confirm the active credential and model. If you previously declined the key, Claude’s authentication documentation describes the “Use custom API key” setting in /config.
The wrapper starts or reuses a local proxy, launches Claude through it, and registers Headroom’s retrieval MCP server in Claude Code’s configuration. --code-memory none skips the additional Serena integration; it leaves Headroom retrieval available. Do not add --no-mcp to this walkthrough, because that removes the retrieval path associated with compressed-content markers. These options are defined in the 0.41.0 wrapper implementation.
The environment switches enable the local telemetry collector and disable its optional upload beacon. Requests still go to the configured model provider.
Record the proxy address printed at launch. The usual port is 8787, but the wrapper can select another available port. In a second Bash terminal, substitute the actual port if necessary:
curl -fsS http://127.0.0.1:8787/health
curl -fsS http://127.0.0.1:8787/stats
Now give wrapped Claude a bounded task using an existing, substantial test.log: list unique failing tests and quote the first exact error for each, without modifying files. After it finishes, request /stats again.
A healthy endpoint proves that the proxy is running. An increase in requests.total shows completed requests reaching its accounting path; inspect requests.failed and requests.rate_limited separately. The metrics documentation explains these fields. Zero savings on a short or protected payload does not establish a routing failure.
If authentication fails, inspect conflicting ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL, and provider settings before retrying. If no requests appear, verify the printed port and the launched session’s route.
Headroom’s compress-cache-retrieve mechanism can retrieve retained originals when Claude needs omitted detail. Retrieval adds work, and retention is finite; if an original is unavailable, return to the source file or rerun the command.
After exiting wrapped Claude, clean up this trial in the original terminal, from the same project and using the actual port:
headroom unwrap claude --port 8787
unset ANTHROPIC_API_KEY
Unwrap removes Headroom-managed setup and attempts to stop the matching proxy. Unsetting the key removes the API credential exported for this trial; verify /status before resuming your usual authentication path.
Use cheaper models for bounded subtasks
Use a lower-priced model for tasks whose output you can verify cheaply, such as extracting failures from a supplied log. This changes the price of work; it does not guarantee fewer tokens.
For a native baseline, create .claude/agents/log-summary.md:
---
name: log-summary
description: Summarize supplied test logs and identify failing tests.
model: haiku
tools: Read, Grep, Glob
maxTurns: 6
---
Read only the log paths supplied in the task.
Return failing test names, exact error excerpts, and file or line references.
Report uncertainty and missing evidence.
Do not modify files.
Restart Claude Code after creating the agents directory, then invoke the worker against an existing log:
Use log-summary to inspect ./test.log and return the first failing test and its exact error. Stop after the summary.
Check /tasks while it runs to inspect the worker’s actual model, and compare its excerpt with the source log. maxTurns limits turns, not dollars or tokens; reaching it can leave a partial result. These fields and lifecycle details are documented in the subagent reference.
haiku is an alias, so provider configuration determines the concrete model. Keep difficult design decisions or ambiguous debugging on the model that resolves them reliably. A cheap worker that requires repeated correction can cost more overall.
If you use BetterToken for pay-as-you-go model access, follow its Claude Code configuration: the Anthropic-compatible base URL is https://bettertoken.ai, without /v1. Check ANTHROPIC_DEFAULT_HAIKU_MODEL and the other alias mappings. Assigning every alias the same model ID means selecting haiku does not select a different, cheaper model. Choose supported IDs deliberately, compare current model and cache rates, and verify the recorded model and charge. BetterToken API billing is separate from a Claude subscription; treat this as a separate provider configuration from the direct-Anthropic Headroom trial above.
Decide using complete-task cost and correctness
Keep a compression tool only if it improves the completed task after you include cache effects, workers, retrieval, and retries.
Compare the same repository state, prompt, concrete model, effort setting, and verification command. Record whether each run starts with a warm or cold cache, since mixing those conditions can distort the result. Check both the final patch or answer and the exact evidence it cites.
For Anthropic API accounting, input_tokens, cache_creation_input_tokens, and cache_read_input_tokens are separate categories; input_tokens alone is not total input. Include output tokens too. For rates quoted per million tokens, calculate sum(token_count × category_rate / 1,000,000) across every request, splitting cache writes by duration where rates differ. Add any mandatory non-token charges.
Claude Code’s main-conversation cache display requires version 2.1.251 or later and does not cover subagents. Proxy savings counters are useful diagnostics, but use your billing provider’s records for the spending comparison.
If an omitted error causes another investigation, a worker repeatedly needs rescue, or retrieval recreates the original context volume, reduce the compression or change the task boundary. The useful outcome is a correct result with less total paid work.