Token Optimization

How to Reduce Claude Code Tokens: Cut Usage by 75%

### Quick Answer: How to Make Claude Use Less Tokens

To reduce Claude Code token usage by up to 75%, implement four core optimizations: configure a strict .claudeignore to eliminate build artifacts and lockfiles, leverage Anthropic's 90% prompt caching read discount by structuring static prompts, isolate sub-tasks using dedicated scout subagents to prevent context rot, and select claude-3-7-sonnet with compact output or claude-3-5-haiku for routine AST discovery before escalating to Opus.


1. Introduction: The Silent Drain of Terminal Token Budgets

Autonomous terminal agents like Anthropic's Claude Code have revolutionized software development workflows. Unlike standard in-IDE completions, Claude Code operates across an autonomous agentic loop: inspecting directory trees, reading multi-thousand-line files, executing shell commands, analyzing compiler logs, and applying surgical code patches.

However, this autonomy comes at a steep economic price. Without proactive configuration, an innocuous prompt like "Refactor the authentication middleware to support JWT rotation" can exhaust 1.5M to 3.5M tokens in a single session. This token inflation stems from several critical vectors:

  1. Context Accumulation (Context Rot): Every bash command execution, grep result, compiler trace, and full-file dump remains trapped inside the agent's active conversational window.
  2. Uncached Context Re-Ingestion: Inadvertently mutating earlier turns in the conversation breaks Anthropic's 5-minute ephemeral prompt cache boundary.
  3. Redundant Artifact Ingestion: Claude Code repeatedly ingests generated assets (dist/, target/, .next/), multi-megabyte package lockfiles (package-lock.json, pnpm-lock.yaml), and database dumps during global regex searches.
  4. Model Overspecification: Deploying flagship reasoning models (claude-3-opus or max-thinking Sonnet) for routine file discovery or directory traversal.

By deploying systematic architectural constraints—.claudeignore hygiene, prompt caching mechanics, subagent context boundaries, and surgical CLI settings—engineering teams routinely reduce their daily Claude Code token consumption by 70% to 80% while improving task success rates.


2. Quantitative Economics: Token Ingestion & Pricing Architecture

To understand how tokens drain, examine the Anthropic API token pricing and caching tiers (2026 baseline):

Claude Model Variant Base Input ($/1M) Cache Write ($/1M) Cache Read ($/1M) Output ($/1M) SWE-bench Verified Ideal Terminal Role
Claude 3.5 / 3.7 Haiku $0.80 $1.00 $0.08 $4.00 41.2% Symbol discovery, regex filtering, commit messages
Claude 3.7 Sonnet (Standard) $3.00 $3.75 $0.30 $15.00 70.3% Core refactoring, multi-file edits, test fixes
Claude 3.7 Sonnet (Extended Thinking) $3.00 (in) $3.75 (write) $0.30 $15.00 (thought + out) 72.8% Complex architectural bugs, concurrency race conditions
Claude 3 Opus / Opus 4.6 $15.00 $18.75 $1.50 $75.00 74.1% High-stakes security audit, full system re-architecture

The Math Behind a 75% Cost & Token Reduction

Consider a typical 15-turn Claude Code session refactoring a REST API endpoint in a 150,000-line TypeScript repository:

[Unoptimized Naive Session]
Turn 1: Ingests repo map + package-lock.json + schema (180,000 tokens)
Turn 2-5: Grep output dumps, unignored build logs, full file reads (240,000 tokens/turn cumulative)
Cache Miss Rate: 45% (frequent cache invalidation due to dynamic headers/tools)
Total Input Tokens Processed: 3,250,000
Effective Cost (Sonnet): ~$9.75

[Optimized Session: .claudeignore + Prompt Cache + Subagents]
Turn 1: Clean AST summary (18,000 tokens) -> Cached at Turn 1
Turn 2-5: Incremental diffs, subagent scout returns compressed findings (22,000 tokens/turn)
Cache Hit Rate: 92% (read from cache at $0.30/1M)
Total Input Tokens Processed: 410,000 (87.3% physical token reduction)
Effective Cost (Sonnet): ~$0.82 (91.5% cost reduction)

3. Pillar 1: Mastering .claudeignore for Zero-Waste Context

The single highest-leverage configuration you can make in any repository is creating an aggressive, production-grade .claudeignore.

Claude Code respects standard .gitignore rules by default, but standard .gitignore files allow numerous massive files that poison LLM context windows. Lockfiles, documentation assets, build outputs, and minified bundles should never enter the agent's context.

The Production .claudeignore Template

Place this file at the root of your project repository:

# ==============================================================================
# .claudeignore - Production Token Pruning Matrix
# Prevents Claude Code from ingesting bloated artifacts during glob & grep operations
# ==============================================================================

# Package Lockfiles (Enormous JSON/YAML blobs with zero AST utility)
package-lock.json
pnpm-lock.yaml
yarn.lock
bun.lockb
composer.lock
Gemfile.lock
Cargo.lock
poetry.lock

# Generated Build Artifacts & Bundles
dist/
build/
out/
.next/
.nuxt/
.astro/
.svelte-kit/
storybook-static/
target/
*.min.js
*.min.css
*.map

# Test Coverage, Logs & Profiling
coverage/
.nyc_output/
*.lcov
*.log
npm-debug.log*
yarn-debug.log*
pnpm-debug.log*
*.heapsnapshot
*.cpuprofile

# Media, Assets & Binary Blobs
public/assets/
public/images/
*.png
*.jpg
*.jpeg
*.gif
*.svg
*.webp
*.avif
*.ico
*.pdf
*.zip
*.tar.gz
*.wasm

# Documentation & External Specs
docs/
*.mdx
specs/swagger/
*.postman_collection.json

# Local Environment & Secrets
.env*
!.env.example
*.pem
*.key
*.cert

# Database Migrations & Seeds
*.sql
*.dump
prisma/migrations/

Measuring the Impact of .claudeignore

When Claude Code executes a recursive directory map or symbol lookup, an un-ignored package-lock.json (often 25,000 to 80,000 lines) will instantly consume over 120,000 tokens in a single read. By blacklisting lockfiles and compiled output, your initial contextual snapshot drops from ~180k tokens to less than ~15k tokens.


4. Pillar 2: Prompt Caching Architecture & 90% Discount Exploitation

Anthropic's prompt caching mechanism allows input tokens to be cached for up to 5 minutes (refreshed on every cache hit). Prompt cache reads cost only 10% of base input cost ($0.30/1M vs $3.00/1M on Sonnet).

+-------------------------------------------------------------------------+
|                    Anthropic Prompt Caching Lifecycle                   |
+-------------------------------------------------------------------------+
                                     |
                                     v
+-------------------------------------------------------------------------+
| [System Prompt & System Tools] (Static Prefix - Always Cached)          |
+-------------------------------------------------------------------------+
                                     |
                                     v
+-------------------------------------------------------------------------+
| [Repository Architecture Map & Coding Guidelines] (Cached Checkpoint)   |
+-------------------------------------------------------------------------+
                                     |
                                     v (Cache Break Point!)
+-------------------------------------------------------------------------+
| [Dynamic User Prompts & Tool Invocations] (Uncached Tail)               |
+-------------------------------------------------------------------------+

Rules to Maintain Prompt Cache Integrity

  1. Never Inject Ephemeral Timestamps in System Context: Avoid dynamic dates or session IDs in system guidelines (CLAUDE.md). Any change to a single prefix character invalidates all downstream cached tokens.
  2. Batch Invocations within the 5-Minute Window: The cache TTL is 300 seconds. If you pause for 6 minutes while reviewing code, the next turn will incur a full cache write penalty ($3.75/1M). Keep interactive sessions moving, or plan multi-step prompts in structured sequences.
  3. Order Tools and System Directives from Most Static to Most Dynamic: Claude Code's internal harness aligns static system instructions and tool definitions at the prefix of the API payload. Ensure custom project instructions in CLAUDE.md remain deterministic.

5. Pillar 3: Subagent Spawning & Sub-Task Isolation

One of the greatest architectural traps in terminal agents is the monolithic session trap. In a monolithic session, the user asks Claude to research a bug, write tests, refactor code, run integration tests, and draft documentation—all in one unbroken conversational thread.

By turn 12, the context window contains hundreds of lines of failing test logs, compiler traces, and obsolete file versions. Every subsequent prompt re-submits this entire context balloon.

The Two-Tier Agent Architecture: Scout & Worker

To cut token waste, decouple exploratory reconnaissance from active code mutation:

[User Request]
       |
       v
+---------------------------------------------+
|  Tier 1: Read-Only Scout Subagent           |
|  - Runs on claude-3-5-haiku / smol model    |
|  - Uses glob, grep, and targeted line reads |
|  - Filters 500,000 tokens down to 2KB summary|
+---------------------------------------------+
       |
       v (Compressed Context Handoff)
+---------------------------------------------+
|  Tier 2: Primary Worker Agent               |
|  - Runs on claude-3-7-sonnet                |
|  - Receives EXACT file paths & AST symbols  |
|  - Executes surgical line-anchored patches   |
+---------------------------------------------+

Implementing Sub-Task Isolation in Claude Code

When working on complex features, structure your workflow into distinct terminal sessions or explicit subagent delegations:

# Bad: Monolithic context inflation
claude "Find all endpoints using deprecated auth, update them to OAuth2, fix tests, and document"

# Good: Isolated Reconnaissance -> Focused Execution
# Step 1: Scout with low token footprint
claude --model claude-3-5-haiku -p "List only the file paths and line numbers using deprecated auth middleware. Output as JSON list." > auth-audit.json

# Step 2: Surgical mutation with clean context
claude --model claude-3-7-sonnet "Refactor endpoints listed in auth-audit.json to use OAuth2 middleware. Touch no other files."

By separating discovery from mutation, the primary reasoning model never ingests thousands of lines of irrelevant files.


6. Pillar 4: Optimal Model Selection — Which Claude Model Uses Less Tokens?

A common misconception among developers is that all Claude models consume the same number of tokens for the same task. In practice, token consumption varies wildly based on:

  • Thinking Budget: Models with extended thinking generate thousands of internal reasoning tokens that bill as output tokens ($15.00/1M on Sonnet).
  • Tool Call Verbosity: Certain models emit verbose explanations before invoking tools, inflating generation tokens.
  • Context Search Efficiency: Smarter models locate symbols with fewer grep calls, whereas smaller models might blindly read entire files.

Token Consumption Comparison Across Tasks

Task Type Claude 3.5 Haiku Claude 3.7 Sonnet (Normal) Claude 3.7 Sonnet (Thinking: 8k) Claude 3 Opus
Locate Symbol in Repo 12k tokens / $0.01 14k tokens / $0.04 24k tokens / $0.18 18k tokens / $0.27
Single Function Bugfix 28k tokens / $0.03 22k tokens / $0.07 35k tokens / $0.24 30k tokens / $0.45
Multi-File Refactor (5 files) High failure rate 140k tokens / $0.48 190k tokens / $1.25 220k tokens / $3.30
Complex Concurrency Race Incapable 320k tokens (fails) 240k tokens (solves) / $1.60 280k tokens / $4.20

Strategic Recommendation

  • Default Workhorse: Use claude-3-7-sonnet without extended thinking for 80% of daily programming tasks.
  • Scouting & Scripting: Use claude-3-5-haiku for file discovery, regex generation, simple bash scripting, and test runner triage.
  • Thinking Mode Reservation: Enable extended thinking (thinking: { budget_tokens: 4000 }) strictly when encountering tricky algorithmic edge cases or compiler errors that fail after the first attempt.

7. Advanced Claude Code Settings & Configuration Optimization

Claude Code allows granular behavioral tuning via its configuration file. You can configure user-level defaults in ~/.claude.json or workspace-specific rules in .claude/config.json.

High-Efficiency .claude/config.json Configuration

{
  "$schema": "https://json.schemastore.org/claude-code-config.json",
  "model": "claude-3-7-sonnet",
  "maxThinkingTokens": 2048,
  "autoCompactContext": true,
  "contextCompactionThreshold": 0.65,
  "allowedTools": [
    "Edit",
    "Bash",
    "Glob",
    "Grep",
    "Read"
  ],
  "toolLimits": {
    "bashOutputMaxLines": 150,
    "readFileMaxLines": 300
  },
  "enableTelemetry": false
}

Key Parameters Explained

  1. maxThinkingTokens: 2048: Caps the extended thinking generation budget. By default, uncontrolled thinking can consume 8k to 16k tokens ($0.12 - $0.24) per turn on simple tasks.
  2. autoCompactContext: true: Automatically triggers conversational summarization when the context window reaches 65% capacity (contextCompactionThreshold: 0.65). This condenses past tool calls and bash outputs into a dense digest, shedding dead tokens.
  3. bashOutputMaxLines: 150: Prevents test suites or package installations from dumping 5,000 lines of raw stdout into your LLM context.

8. Tactical CLI Prompting Patterns for Token Efficiency

Your interactive prompting habits dictate up to 40% of session token burn. Adopt these battle-tested terminal prompt patterns:

Pattern 1: Targeted Line Range Reads

Instead of letting Claude read entire files, explicitly instruct line-bounded inspection:

# BAD: Consumes 1,800 lines (14,000 tokens)
"Read src/auth/session.ts and see why user token verification fails"

# GOOD: Consumes only 60 lines (450 tokens)
"Inspect lines 120-180 of src/auth/session.ts where verifyJwt() is defined"

Pattern 2: Headless Output Truncation

When directing Claude to execute test suites or builds, enforce silent or truncated shell runs:

# BAD: Dumps thousands of passing test lines into context
"Run npm test and fix the failure"

# GOOD: Forces output containment
"Run npm test -- --reporter=dot or pipe to grep for failures. Do not dump passing test logs."

Pattern 3: Explicit Single-Turn Exit (/compact & /clear)

Make aggressive use of Claude Code's internal commands:

  • /compact: Manually forces an immediate context compaction turn, replacing previous chat history with a compressed technical brief.
  • /clear: Wipes the context completely between distinct tasks without restarting the terminal shell.

9. Comprehensive Comparison: Token Reduction Strategies

The following matrix ranks each optimization technique by token savings, implementation effort, and risk to task accuracy:

Optimization Strategy Typical Token Savings Implementation Effort Risk of Regressing Code Quality Primary Mechanism
Strict .claudeignore 40% – 60% Low (5 min setup) Zero Prevents ingestion of lockfiles, media, and build trees
Context Compaction (/compact) 30% – 50% Instant (CLI command) Low Flushes stale bash traces and obsolete file iterations
Subagent Reconnaissance (Scout) 35% – 55% Medium (Workflow change) Very Low Decouples read-heavy discovery from high-cost mutation
Thinking Budget Capping 20% – 35% Low (Config edit) Low-Medium Prevents runaway reasoning loops on routine refactors
Line-Anchored Patching 15% – 25% Low (Prompt guideline) Low Replaces whole-file rewriting with surgical diffs
Prompt Cache Alignment 10% – 20% (Cost) Medium Zero Maximizes 90% read discount by freezing static prefixes

10. Conclusion & Actionable Implementation Checklist

Slashing Claude Code token usage by 75% does not require sacrificing coding accuracy. In fact, leaner context windows directly improve model reasoning by eliminating the noise that causes attention drift and hallucinations.

5-Step Action Checklist:

  1. [ ] Deploy .claudeignore: Add the production template to your project root immediately. Blacklist all lockfiles and build outputs.
  2. [ ] Tune config.json: Cap thinking tokens to 2048 and enable autoCompactContext at 0.65.
  3. [ ] Use the Right Model: Keep claude-3-7-sonnet for editing, claude-3-5-haiku for discovery, and reserve extended thinking for complex algorithmic roadblocks.
  4. [ ] Guard Shell Outputs: Enforce concise test runner flags (--reporter=min, pipe through head/grep) to keep bash stdout under 100 lines.
  5. [ ] Clear Context Regularly: Run /compact or /clear between architectural tasks to eliminate context rot.

By integrating these controls into your everyday terminal workflow, you preserve deep agentic capabilities while drastically shrinking your monthly API expenditures.

← All Articles
0 / 4