Claude Code Token Usage: How to Track, Inspect, and Reduce Token Burn
Claude Code token usage measures the cumulative input, output, prompt-cached, and tool-invocation tokens consumed during an interactive terminal coding session. Managing these costs requires inspecting live session consumption with built-in commands, understanding prompt cache invalidation dynamics, and keeping multi-turn contexts compact. For large codebases and reference corpora, offloading search to an external workspace prevents verbose file reads from exhausting the model's context window.
What Drives Claude Code Token Consumption in Terminal Sessions
Across enterprise deployments of Claude Code, the average cost is around $13 per developer per active day and $150-250 per developer per month, with costs remaining below $30 per active day for 90% of users, according to Anthropic's official Claude Code documentation. In web chat and project interfaces, file attachments operate under strict vendor boundaries: according to Anthropic's upload guidelines, Claude chat uploads accept up to 20 files per chat at up to 500MB each, while Claude Projects accept files up to 30MB each with no fixed file count, bounded only by the model's 200,000-token context window.
In Claude Code, file handling follows a different technical mechanism. Developers do not drag files into a browser window. Instead, Claude Code operates directly in your local shell as an agentic command-line interface. It searches directories with ripgrep, views source code through file-reading tools, runs compiler commands, and inspects git status. Every time a tool emits text, whether a ten-line patch or a four-hundred-line test trace, that raw text enters the conversation context.
Claude Code token usage measures the cumulative input, output, prompt-cached, and tool-invocation tokens consumed during an interactive terminal coding session. Unlike human chat where messages remain short, command-line coding agents continuously accumulate state. Every execution turn sends the foundational system prompt, project instructions from the root CLAUDE.md, active skill definitions, conversation history, and raw tool outputs back to the model for inference.
This compounding state means that a single command can alter the session's memory profile. When Claude Code executes a build script or reads candidate files to diagnose an import failure, it can ingest thousands of tokens before proposing a single line of code.
The following comparison table breaks down how different terminal operations, tool outputs, and model configurations affect context consumption during an active session:
Understanding these distinctions allows developers to separate healthy context accumulation from unmanaged token burn.
Related guides
- Cursor Token Usage: How to Track, Monitor, and Reduce AI SpendCursor token usage measures the volume of prompt and completion tokens processed during chat, codebase indexing, and...
- How to Track and Manage Token Usage in OpenClawMost OpenClaw users discover that the bulk of their token spend comes from context accumulation and background...
- Claude Token Usage: How to Track, Manage, and Optimize Session LimitsClaude token usage measures the cumulative input and output tokens consumed during a Claude conversation, including...
- Claude Code Limits: Quotas, 200K Context Windows, and 5-Hour Usage CapsClaude Code operates under two distinct boundaries: length limits dictated by a 200,000-token context window and usage...
- Claude Code Token Limit: Output Caps, Compaction, and Workspace ArchitectureThe Claude Code token limit defines the boundaries on input context, per-turn output generation, and rolling session...
- Claude Code Context Window: Managing Token Limits in Terminal AgentsThe Claude Code context window determines how much conversation history, source code, and command output a terminal...
More on this subject: Claude and Claude Code (278 guides)
How to Inspect Active Token Usage with Built-in CLI Commands
Claude Code provides built-in terminal commands that allow developers to monitor token consumption, prompt cache performance, and estimated financial costs without leaving the command line.
Inspecting the Session Block with /usage
Running /usage displays an itemized breakdown of token activity for the active session. The Session block reports four distinct token streams across each model invoked:
- Input tokens: Raw prompt text, un-cached tool definitions, and user instructions sent to the API.
- Output tokens: Generated completions, streaming code, tool arguments, and internal thinking scratchpads.
- Cache read tokens: Input tokens retrieved directly from Anthropic's prompt cache at discounted rates.
- Cache write tokens: New tokens written to the cache when creating a checkpoint or encountering a cache miss.
/usage
In Claude Code v2.1.251 and later, /usage appends a dedicated Prompt cache (main) diagnostic line. This line details the exact request count, the share of input tokens served from cache, cache misses, expected rebuilds from compaction, and cache temperature (warm versus cold with TTL expiration). On subscription tiers, /usage also shows an attribution section breaking down consumption across skills, subagents, and Model Context Protocol (MCP) servers.
Estimating Dollar Costs with /cost
For developers working with API keys or administrators tracking budget consumption, the /cost command computes the dollar equivalent of tokens consumed in the current session:
/cost
Claude Code calculates this figure locally from token counts at standard list prices. When an administrator deploys a modelPricing table through managed settings, the output automatically reflects contracted enterprise rates and displays the note at your organization's configured rates.
Visualizing Memory Allocation with /context
To understand where tokens are allocated across your session, run /context. This command renders a proportional visual diagram dividing active context space into system instructions, conversation transcript, loaded file memory, and deferred tool definitions.
/context
Monitoring Live Generation with the Spinner Indicator
During active execution, Claude Code displays an elapsed time counter and output token metric directly beside the terminal spinner:
Deciphering… (14s · ↓ 3.2k tokens)
The downward arrow indicates live token emission as the model streams thinking steps, code modifications, and tool calls. This counter tracks the active turn only and resets at the start of each new prompt, providing immediate feedback when a command triggers verbose reasoning.
Running Historical Audits with /insights
For a comprehensive review of development efficiency across sessions, run /insights. This command scans up to two hundred recent sessions stored on your local machine and generates an HTML report at ~/.claude/usage-data/report.html. The report identifies friction points, repeated prompts, bug cycles, and areas where autonomous operations can replace manual interactions.
Why Multi-Turn Sessions Burn Tokens and Invalidate Prompt Caches
Developers frequently wonder why a command line session that begins at a few cents per turn can escalate to several dollars an hour later. The root cause lies in the mechanics of stateless model inference and prompt cache invalidation.
The Stateless Context Multiplier
Large language model APIs do not maintain continuous server-side memory across HTTP requests. To preserve conversational continuity, Claude Code must send the entire interaction transcript back to the model on every execution turn.
Consider a typical debugging workflow. A developer asks Claude Code to resolve a failing test suite. In the first turn, Claude Code executes npm test, generating five hundred lines of console logs, compiler warnings, and stack traces. Claude then reads two source files and proposes an initial fix. That turn adds roughly fifteen thousand tokens to the session context.
When the developer replies with a concise two-word instruction like "run again", the API request does not transmit merely those two words. It resends the foundational system prompt, the complete CLAUDE.md file, the original user request, the five hundred lines of test output, the two source files, the previous agent response, and the new prompt. If the developer iterates through ten debugging turns, that single five-hundred-line test log is processed and billed ten separate times.
Prompt Caching Dynamics and Miss Triggers
Anthropic mitigates repetitive context processing through prompt caching. The API automatically caches stable prompt prefixes for up to one hour on subscription tiers (and five minutes on usage-based plans or API keys). When a request matches a cached prefix, cache read tokens are billed at a fraction of standard input rates, saving substantial token overhead.
However, prompt caching relies on exact prefix alignment. Any modification to the token sequence before a cache checkpoint invalidates subsequent cached data, forcing a full cache rewrite at full price. Common cache invalidation triggers include:
- Modifying project configuration mid-session: Editing
CLAUDE.md, changing environment variables, or adding active skills invalidates the top-level prompt prefix. - Non-deterministic tool outputs: Shell commands that output varying timestamps, process IDs, or system memory metrics early in the transcript alter the token stream for all subsequent turns.
- Session idle timeouts: If a session remains idle longer than the cache TTL (one hour on subscription plans, five minutes on API usage credits), the server-side cache goes cold. The next prompt incurs a complete cache write penalty.
- Unconstrained background tasks: Session-scoped scheduled tasks, continuous loops, or cross-session message polling transmit full context payloads on every tick, accelerating token consumption even when the developer is away from the terminal.
Practical Techniques to Cut Token Burn and Retain Critical State
Controlling Claude Code token consumption does not require sacrificing agent autonomy. By applying targeted terminal habits and context controls, developers can reduce token burn while preserving critical problem-solving capabilities.
1. Reset Context Proactively with /clear and /resume
The single most effective habit for controlling token burn is clearing context between distinct engineering tasks. When you finish implementing a feature or fixing a defect, the preceding debugging logs and file reads become dead weight.
Running /clear flushes the active context window completely, resetting the next turn's cost to baseline. Code modifications on disk remain untouched. To preserve work for later reference, rename the session before clearing, then return to it when needed:
/rename auth-refactor-phase-1
/clear
/resume auth-refactor-phase-1
2. Guide Compaction with Explicit Focus Instructions
When a session approaches context limits, Claude Code automatically compacts the conversation history. However, automatic compaction uses a general summarization algorithm that may discard details you need while preserving verbose logs you do not.
Developers can invoke manual compaction at any time with targeted focus arguments:
/compact Focus on modified database schemas, API routes, and unit test contracts
You can also establish permanent compaction rules by adding instructions to your project's root CLAUDE.md:
### Compaction preferences
When compacting conversation context, preserve modified file paths, database schemas, and architectural decisions. Discard bash directory listings, passing test runner logs, and redundant package installation output.
3. Pre-Filter Verbose Tool Outputs with PreToolUse Hooks
A primary source of context inflation is unformatted terminal output. When a test suite fails, Claude Code often ingests thousands of lines of passing test logs just to read five lines of stack traces.
Using Claude Code PreToolUse hooks, developers can intercept commands before execution and filter their standard output. Create an executable script at ~/.claude/hooks/filter-test-output.sh:
#!/bin/bash
input=$(cat)
cmd=$(echo "$input" | jq -r '.tool_input.command')
if [[ "$cmd" =~ ^(npm\ test|pytest|go\ test) ]]; then
filtered_cmd="$cmd 2>&1 | grep -A 5 -E '(FAIL|ERROR|error:)' | head -100"
echo "$input" | jq --arg filtered "$filtered_cmd" \
'{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: (.tool_input + {command: $filtered})}}'
else
echo "{}"
fi
Register the hook in your ~/.claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/filter-test-output.sh"
}
]
}
]
}
}
This hook ensures that only failing assertions enter Claude's context window, transforming a thirty-thousand-token test trace into a concise two-hundred-token snippet.
4. Move Specialized Procedures from CLAUDE.md into Skills
The root CLAUDE.md file loads into context on every execution turn. If your configuration file contains extensive documentation for deployment checklists, database migrations, and release workflows, those tokens burn continuously even during routine bug fixes.
Keep CLAUDE.md under two hundred lines by retaining only core coding conventions. Move specialized workflows into modular skill files. Skills load on demand only when Claude invokes them, keeping baseline prompt overhead minimal.
5. Tune Extended Thinking and Match Models to Tasks
Extended thinking in Claude 3.7 Sonnet delivers impressive reasoning for difficult architectural problems, but thinking tokens are metered as output tokens. For straightforward refactoring or boilerplate generation, high thinking budgets generate unnecessary token expense.
Adjust reasoning depth with /effort or set MAX_THINKING_TOKENS=8000 in your environment. For routine script execution or lightweight subagent tasks, specify Claude 3.5 Haiku to maintain low operational costs.
Stop Burning Context on Bulky Project Documentation
Keep Claude Code focused on code generation by offloading large technical manuals and project corpora to a searchable Fast.io workspace with MCP access. Monthly plans include a 14-day free trial.
How to Offload Large Document Corpora Using Fast.io MCP
While context hygiene and filtering scripts optimize local code editing, engineering teams frequently encounter an architectural bottleneck: providing Claude Code with access to large reference corpora.
The Context Penalty of Local Document Ingestion
Complex software projects require constant reference to external knowledge: architectural decision records (ADRs), internal API specifications, security compliance frameworks, and third-party SDK documentation.
When developers attempt to provide this context locally, they typically store PDF manuals, markdown archives, or swagger definitions directly in the project repository. When Claude Code needs information, it runs ripgrep or reads entire multi-megabyte files into its active context window. A single technical manual can easily consume thirty to sixty thousand tokens in one turn, crowding out application source code and triggering premature compaction.
Storing Knowledge in Intelligent Workspaces
Rather than forcing Claude Code to ingest raw documentation into its local context, teams store reference materials in a shared Fast.io workspace. Fast.io provides an intelligent workspace platform designed for human developers and autonomous agents.
When Intelligence Mode is enabled on a workspace, Fast.io automatically indexes uploaded documents for hybrid retrieval, combining full-text search with semantic understanding. Instead of reading whole files from disk, Claude Code queries the workspace remotely via the Model Context Protocol (MCP) and receives only the exact paragraphs relevant to the task.
Connecting Claude Code to Fast.io via Streamable HTTP
Claude Code connects to Fast.io using the remote MCP server over Streamable HTTP. To connect Claude Code, run the MCP addition command in your terminal:
claude mcp add --transport http fast-io https://mcp.fast.io/mcp/code
After adding the server, enter /mcp inside Claude Code to complete browser-based OAuth authentication. Once authenticated, the connection persists across sessions.
For team repositories, you can also declare the connection in your project's .mcp.json file:
{
"mcpServers": {
"fast-io": {
"type": "http",
"url": "https://mcp.fast.io/mcp/code"
}
}
}
On the /mcp/code endpoint, Claude Code interacts with a consolidated toolset including search, execute, and upload. When Claude Code needs to verify an API contract or review an architectural requirement, it calls search with a natural language query:
{
"query": "authentication token renewal and session revocation rules"
}
The Fast.io workspace evaluates the query across indexed PDFs, Word documents, and text files, returning targeted excerpts with precise document citations. Claude Code receives the exact facts needed to write code without loading thousands of extraneous tokens into its local session context.
Enterprise Coordination and Cloud Sync
In addition to reducing token overhead, intelligent workspaces provide enterprise-grade coordination for agentic workflows:
- Per-file version history: Every file modification creates a permanent version checkpoint, allowing developers to audit or revert agent updates.
- Role-based permissions: Access controls are enforced per organization, workspace, and share, keeping sensitive infrastructure documents protected.
- Detailed activity logs: Every upload, edit, move, and deletion is recorded in a detailed activity log of changes, providing visibility into both human and agent actions.
- Automated Cloud Sync: Connect existing folders from Google Drive, Dropbox, Box, and OneDrive to a workspace on a schedule or on demand, keeping documentation synchronized without local file bloat.
Monthly plans begin with a 14-day free trial that requires a credit card. Fast.io plans include Starter at $9.99/mo (3 seats, 250 GB storage, 5 workspaces, 100,000 credits monthly), Business at $49.99/mo (10 seats, 5 TB storage, 50 workspaces, 600,000 credits monthly), and Enterprise at $199.99/mo (30 seats included, 25 TB storage, 200 workspaces, 3,000,000 credits monthly).
Sources
References used to verify factual claims in this guide.
-
Across enterprise deployments, the average cost of Claude Code is around $13 per developer per active day and $150-250 per developer per month, with costs remaining below $30 per active day for 90% of users.
-
Claude chat uploads accept up to 20 files per chat.
Frequently Asked Questions
How do I check token usage in Claude Code?
Run the /usage command inside your terminal session to view detailed token statistics across all models used. The command displays input tokens, output tokens, cache read tokens, cache write tokens, and prompt cache hit percentages. For financial estimates, enter /cost to see estimated dollar spend calculated from current token counts, or run /context to inspect proportional memory allocation across system instructions, conversation history, and tools.
Why is Claude Code using so many tokens?
Claude Code is an agentic terminal tool that maintains environmental awareness across multi-turn interactions. Because API requests are stateless, every message resends the foundational system prompt, project settings from CLAUDE.md, conversation history, and raw outputs from terminal tools like bash, git diff, and file views. Reading large source files or unconstrained test runner logs injects thousands of tokens into context, compounding costs on every subsequent prompt.
How can I reduce Claude Code token costs?
To reduce token costs, clear stale context between tasks using /clear, invoke manual /compact with specific focus instructions, and install PreToolUse hooks to filter verbose test runner outputs before Claude sees them. Additionally, keep your root CLAUDE.md under two hundred lines by moving specialized procedures into on-demand skills, and store large documentation archives in an external Fast.io workspace to search files via MCP instead of reading them into context.
Does running /clear delete my code changes?
No. The /clear command resets only the in-memory conversation history and tool execution transcripts within the active CLI session. All files created, modified, or deleted on your local file system remain intact. If you want to retain the conversation transcript before clearing, use /rename to label the session and /resume to return to it later.
How does prompt caching lower costs in Claude Code?
Prompt caching stores stable prompt prefixes on Anthropic API servers. When Claude Code sends requests where the system prompt, tool definitions, and top-level project instructions match a cached checkpoint, the API reads those tokens from cache at a discounted rate compared to standard input pricing. Keeping configuration files stable and avoiding dynamic timestamps in early turns preserves cache hits.
Can organizations set hard token spend limits in Claude Code?
Yes. On Claude for Teams and Enterprise plans, administrators can set per-member spend limits and review daily usage reports within the admin console. For organizations authenticating via the Claude Console, administrators can configure workspace spend caps to enforce hard budget ceilings on total Claude Code consumption.
Related Resources
Stop Burning Context on Bulky Project Documentation
Keep Claude Code focused on code generation by offloading large technical manuals and project corpora to a searchable Fast.io workspace with MCP access. Monthly plans include a 14-day free trial.