I pay Anthropic a few hundred dollars a month for Claude Code. I could be paying 3× that. I cut the difference using three levers: prompt caching, model routing, context pruning. Here's what works — with numbers from my own setup and code from the project that inspired me.
Inspiration: github.com/JuliusBrussee/caveman. a token-optimization wrapper for Claude Code. Short code, several great ideas. Plus my own stack: .claude/settings.json, smart-router skill, hooks, fewer-permission-prompts.
Where Claude Code costs come from
Claude Code is an LLM-driven coding assistant with a large context window. A typical 2-hour session burns:
- Input tokens: 2-5 million (system prompt + tools + entire conversation history + every file you read)
- Output tokens: 100-300 thousand (code, explanations, narration)
- Cache reads: 60-90% of input (in well-configured sessions)
Claude Sonnet 4.6 pricing (April 2026):
- Input without cache: $3 / 1M tokens
- Cache write: $3.75 / 1M (1.25× input)
- Cache read: $0.30 / 1M (0.1× input — 10× cheaper)
- Output: $15 / 1M tokens
Without cache: 3M input × $3/M = $9 per session, plus output. With a good cache hit ratio (80%): 2.4M cache read × $0.30/M + 0.6M write × $3.75/M = $0.72 + $2.25 = $2.97. Three times cheaper for the same work. At a monthly scale: instead of $300 → $100.
Lever 1: prompt caching — your biggest impact
Prompt caching is an Anthropic API mechanism: a small cache-write fee on the first request, then 5-minute TTL where you read the cached prefix at 10× lower cost.
What to cache:
- System prompt (always the same for a project)
- Tool definitions (Read, Edit, Bash etc. — schemas rarely change)
- CLAUDE.md (project instructions, static)
- Project documentation files referenced repeatedly
Claude Code caches system + tools by default. But in long sessions (3+ hours) you have to mind the TTL — every 5 minutes the cache expires, the next request becomes a write again instead of a read.
My trick: if a session has been idle > 30 minutes, restart it. Don't keep going — the cache expired, every following prompt pays full write. Better to start a fresh session with fresh cache than to drag along an old one paying full price.
Lever 2: model routing — Haiku/Sonnet/Opus
Three Claude 4.X models:
| Model | Input $/1M | Output $/1M | Use case |
|---|---|---|---|
| Haiku 4.5 | $1 | $5 | routine: lint fixes, format, simple search-replace, status summaries |
| Sonnet 4.6 | $3 | $15 | typical coding: feature work, bug fixes, refactors, code review |
| Opus 4.7 | $15 | $75 | complex: architectural decisions, multi-file refactors, security audits |
The heuristic that works for me: 80% of tasks go to Haiku or Sonnet. 20% to Opus. Classification:
- "Fix typo in README" → Haiku
- "Add POST /webhook endpoint to server.js" → Sonnet
- "Refactor auth system to support multi-tenant" → Opus
I use a ~/.claude/skills/smart-router skill in my setup. It classifies the task based on prompt keywords (e.g. "simple/typical/complex", "1 file/many files") and picks a model. Routing logic in SKILL.md + delegation to a subagent with the chosen model.
Lever 3: context pruning
The third lever — hardest but most effective in long sessions. Claude Code keeps the entire conversation history in context by default. After 2 hours you have 1.5M input tokens of which 80% are files no longer relevant.
What to do:
- Subagent for any large exploration. Instead of reading 30 files in the main context — fire a subagent through the Agent tool, it does the research, comes back with a 200-word summary. The main context doesn't bloat.
- /compact every 1-2 hours. Built-in Claude Code command. Summarizes the conversation so far, continues with 30K tokens instead of 1.5M.
- Deliberate Reads. If a file has 2,000 lines and you only need
getUser()at line 450 — useoffset+limit. Do not load the whole thing. - Hook on session end.
~/.claude/settings.json→ a Stop hook reminding "session burned X tokens, continue or fresh?".
What caveman does
caveman is a ~90-line Python wrapper that automates 3 tricks:
- Shortens the system prompt — Claude Code's default system prompt is ~2K tokens. caveman keeps essentials at 800 tokens (no full descriptions for tools the LLM already knows).
- Rotates cache every 4 minutes — to never hit the 5-min TTL expiry. Cache is ALWAYS fresh, every following request is a read (not a write).
- Detects "redundant" tools in the prompt — if the task is pure code editing, it doesn't load schemas for WebFetch/Bash etc. Smaller system = fewer input tokens.
Do I run caveman 1:1? No — my use cases vary, and some genuinely need the full toolset. But I adapted 3 ideas:
- Shortened system prompt for skill subagents (each skill has its own system, shorter than the global one)
- Cache TTL monitoring (not rotation every 4 min — but an alert "cache expires in 30s, send a prompt now or restart")
- Dynamic tool loading via
ToolSearch— tools don't load up-front, only when needed
My setup — what I actually do
Configuration: ~/.claude/settings.json
{
"permissions": {
"allow": [
"Bash(git status:*)",
"Bash(npm test:*)",
"Read(./)"
]
},
"hooks": {
"Stop": [{ "command": "echo 'Session ended. Tokens used: $CLAUDE_TOKENS_USED'" }]
},
"env": {
"CLAUDE_DEFAULT_MODEL": "sonnet"
}
}
Skills:
smart-router— classifies task complexity, routes to Haiku/Sonnet/Opusfewer-permission-prompts— analyzes my common Bash commands and auto-allowlists read-only ones (fewer interruptions = fewer tokens spent on re-explaining)update-config— modifies settings.json without manual editing
Hooks:
PreToolUse— logs each tool call to~/output/claude-tool-log.jsonl(I have metrics on what gets called how often)UserPromptSubmit— if a prompt is <5 words, prepends a standard template "be concise, answer in 1-2 sentences"Stop— reminds me to /compact if session >1h
Numbers from my setup
March 2026: $387 on Anthropic API + Pro subscription.
April 2026 (after 3 weeks): $142 for the same workload.
What I changed:
- Enabled cache rotation alert — eliminates cache writes in 4-hour sessions
- Smart-router skill — 60% of tasks now go to Haiku instead of Sonnet
- Stop hooks — I /compact more often, less context accumulates
That's a 63% reduction while maintaining the same productivity. It might end up lower (April isn't done yet), but even the current state is 3-4× ROI on the time I invested in setup.
FAQ
When Sonnet vs Opus — how to decide?
I default to Sonnet. I escalate to Opus only when: (1) the task requires understanding >5 files simultaneously, (2) security / architectural decisions are involved, (3) Sonnet's first-pass output is worse than expected. Not the other way around.
Does cache always work, or are there exceptions?
A cache hit requires that the first N tokens of the request are identical to the previous one. Any change in system prompt, tool definitions, CLAUDE.md = cache miss, write instead of read. That's why CLAUDE.md should be stable (don't edit it mid-session).
Is the 1M context window worth it?
Rarely. Sonnet 4.6 with 1M context (my CLI tier) charges 2× for input above 200K tokens. If your session truly hits 1M input tokens — usually it's better to complicate the strategy (subagents, /compact) than to pay long-context premium.
SDK vs CLI — cost difference?
The SDK (Claude Agent SDK) gives you full control over cache control headers, model selection per request, batch API. Annual differences can be >30% (cheaper on the SDK with deliberate implementation). The CLI is "good defaults" without fine-tuning.
How much does my session actually cost?
Anthropic Console shows "Usage" per request. Plus my PreToolUse hook logs per-tool-call to JSONL — I can sum it up by day/week. Without that you fly blind. The first move in optimization = turn metrics on.
Want to optimize your Claude Code spend?
I've been building automation tools in Claude Code since early 2025 — lots of practice on cost optimization. If your team spends >$300/month on Anthropic API and you don't know what to do about it, Book a free call (30 min). in 30 minutes I'll spot 2-3 concrete levers.
Plus check my knowledge base and Claude Code page. I update them weekly with new tricks. DM TOKEN on LinkedIn — I'll send .claude/settings.json snippets that cut session costs by 40-60%.