Cost Optimization
Optimize model selection, caching, and token management for efficiency.
What You’ll Learn
Using AI coding tools at scale has real cost implications. Every API call consumes tokens, and tokens cost money. But cost optimization is not about using the cheapest model for everything --- it is about using the right model for each task, keeping context lean, and avoiding unnecessary work.
By the end, you’ll understand:
- What drives cost in AI-assisted coding
- How to select the right model and effort level for each task
- The model cascade pattern
- Token management and context efficiency
- Caching strategies that reduce redundant work
- How to measure what a session actually spent
The Problem
A developer who uses the most capable model for every task --- including simple file searches, listing directories, and reading configuration --- is overspending dramatically.
Typical session breakdown:
5 file searches (simple) ← Haiku could do this
3 code explorations (moderate) ← Sonnet is ideal
1 architecture decision (complex) ← Opus is worth it
10 small edits (simple) ← Sonnet handles fine
2 test investigations (moderate) ← Sonnet is ideal
All 21 ops with Opus → expensive
5 Haiku + 15 Sonnet + 1 Opus → lower cost, strongest model where it matters
The difference compounds over days and weeks across hundreds of sessions.
How It Works
Understanding Cost Drivers
┌──────────────────────────────────────────────────┐
│ Cost Drivers │
│ │
│ 1. INPUT TOKENS │
│ System prompt, CLAUDE.md, conversation │
│ history, file contents, tool outputs │
│ │
│ 2. OUTPUT TOKENS │
│ Thinking, responses, tool call arguments, │
│ generated code │
│ │
│ 3. MODEL CHOICE │
│ Haiku → Sonnet → Opus → Fable (highest) │
│ │
│ 4. EFFORT LEVEL │
│ Higher effort = more thinking tokens, │
│ billed as output │
│ │
│ 5. NUMBER OF API CALLS │
│ Each tool use = another round trip │
│ Each call re-sends the full context │
│ (cached prefixes bill at a lower rate) │
│ │
└──────────────────────────────────────────────────┘
The critical detail: input tokens are sent on every API call. If your context is 50,000 tokens and the agent makes 20 tool calls, that is 50,000 tokens sent 20 times. Claude Code softens this with automatic prompt caching --- the unchanged prefix of each request is billed at the much lower cache-read rate --- but a long context still costs something on every call, and a cache miss re-processes all of it at the full input rate. A lean context pays dividends on every single call.
Model Selection Strategy
┌─────────────────────────────────────────────────┐
│ Model Selection Guide │
│ │
│ HAIKU 5.5 (fastest, lowest cost) │
│ ├── File search and exploration │
│ ├── Listing directory contents │
│ ├── Simple text transformations │
│ ├── Reading and summarizing files │
│ └── Pattern matching across codebase │
│ │
│ SONNET 5.5 (balanced, moderate cost) │
│ ├── Writing and modifying code │
│ ├── Debugging and fixing errors │
│ ├── Refactoring, writing tests │
│ └── Most day-to-day coding tasks │
│ │
│ OPUS 5.5 (Claude Code's default, higher cost) │
│ ├── Architecture decisions │
│ ├── Complex multi-file refactors │
│ ├── Resolving subtle bugs │
│ └── Long-running agentic work │
│ │
│ FABLE 5.1 (most capable, highest cost) │
│ ├── Demanding, long-horizon tasks │
│ └── Work that Opus 5.5 at higher effort │
│ still can't finish │
│ │
└─────────────────────────────────────────────────┘
Update (October 2026): The current lineup is Claude Fable 5.1, Opus 5.5, Sonnet 5.5, and Haiku 5.5, which the
fable,opus,sonnet, andhaikualiases select on the Anthropic API. Fable 5, Opus 5, Sonnet 5, Opus 4.8, Opus 4.7, and Haiku 4.5 are older models. On Amazon Bedrock, Google Cloud’s Agent Platform, and Microsoft Foundry, some aliases still resolve to older models, so check/model. See Session 25 for the full model strategy.
Opus 5.5 is Claude Code’s default model on Pro, Max, Team, and Enterprise plans and on the Anthropic API, and Anthropic’s suggested starting point for most workloads. When cost is the constraint, Claude Code’s cost guide notes that Sonnet handles most coding tasks well for less. Fable is never the default: select it with /model fable, and note that, depending on your plan, Fable usage can bill to usage credits instead of your plan’s included limits.
List prices on the Claude API (per million tokens, October 2026):
| Model | Input / output | Cache reads | Default effort in Claude Code |
|---|---|---|---|
| Claude Haiku 5.5 | $0.10 / $0.50 for prompts up to 100K tokens; $0.50 / $2.50 above | $0.01 up to 100K; $0.05 above | medium |
| Claude Sonnet 5.5 | $2 / $10 | $0.10 | medium |
| Claude Opus 5.5 | $4 / $20 | $0.20 | medium |
| Claude Fable 5.1 | $10 / $50 | $0.25 | high |
On a Pro, Max, Team, or Enterprise subscription, usage counts against your plan’s limits instead of being billed per token; /usage shows what is using them.
Effort: The Second Dial
Model choice is not the only lever. Thinking tokens are billed as output, so effort level changes cost too. Opus 5.5, Sonnet 5.5, and Haiku 5.5 run at medium effort by default in Claude Code; Fable 5.1 runs at high. Drop to /effort low for mechanical work and raise effort only for problems that need deeper reasoning. Haiku 5.5 is the first Haiku model with an effort setting; Haiku 4.5 has none.
Skills and subagents can set their own effort in frontmatter, and teams can cap it with the maxEffortLevel setting. On the 5.5 models and Fable 5.1, with an API key or a Claude subscription, changing effort mid-session keeps the prompt cache; on most other models it does not.
The Model Cascade Pattern
Start with the cheapest model, escalate only when needed:
┌──────────────────────────────────────────────────┐
│ Model Cascade │
│ │
│ Task arrives │
│ │ │
│ ▼ │
│ Try with HAIKU │
│ ├── Quality OK? → Done (lowest cost) │
│ │ │
│ ▼ │
│ Escalate to SONNET │
│ ├── Quality OK? → Done (moderate cost) │
│ │ │
│ ▼ │
│ Escalate to OPUS → Done (highest quality) │
│ │
│ Error at any step → Classify and recover │
│ (see Session 20) │
│ │
└──────────────────────────────────────────────────┘
In practice, you pre-assign models based on task category rather than cascading every individual task. The cascade is a mental model for deciding which tasks deserve which model. Escalate by delegating to a subagent that uses a stronger model, or by starting the next task on it: switching the main session’s model mid-task discards its prompt cache, because each model has its own cache.
Token Management
Keeping context lean reduces the cost of every subsequent API call:
1. TARGETED FILE READS
Bad: "Read all files in src/" → 50 files, 40K tokens
Good: "Read src/auth/middleware.ts" → 1 file, 800 tokens
2. SPECIFIC SEARCHES
Bad: Search "config" (200 hits)
Good: Search "databaseConfig" in src/db/ (3 hits)
3. SUBAGENT ISOLATION
Bad: Explore in main context → 20 reads in history
Good: Delegate to a subagent → only its summary returns
4. CLEAR OR COMPACT AT TASK BOUNDARIES
Bad: Carry a finished task's context into unrelated work
Good: /clear for unrelated work;
/compact <focus> when you need continuity
5. TOOL AND MCP OVERHEAD
Bad: Keep every MCP server connected "just in case"
Good: Check /context; disable unused servers in /mcp
/clear costs nothing, while /compact is itself a request that reads the conversation it summarizes, so compact at natural breaks rather than mid-task.
Caching Strategies
Prompt Caching (automatic in Claude Code):
First call: prefix written to the cache (cache-write rate)
Later calls: unchanged prefix read from cache (cache-read rate,
e.g. Opus 5.5: $0.20 vs $4 per MTok of input)
Cache miss: switching models, or a break longer than the
cache lifetime (5 minutes by default; 1 hour for
the main conversation on a Claude subscription
within its plan limits)
→ full context re-processed
Avoid Re-Reading:
Read file once, keep info in conversation. Second read = wasted tokens.
Batch Related Reads:
Bad: Read A, B, C sequentially (3 round trips)
Good: Read A, B, C in parallel (1 round trip)
Lean CLAUDE.md:
Bloated: 5000 tokens × every API call
Lean: 800 tokens × every API call
Savings: 4200 tokens × every call in session
Pick your model and effort level at the start of a session; the fewer changes you make mid-task, the higher your cache hit rate. Keep CLAUDE.md to essentials and move workflow-specific instructions into skills, which load only when used.
Subagent Model Selection
Matching subagent models to the work is one of the biggest savings in exploration-heavy workflows:
Exploration → haiku ("Find all test files", "List API routes")
Implementation → sonnet ("Write unit test", "Refactor to async/await")
Architecture → opus ("Design data model", "Evaluate trade-offs")
Set the model in each subagent’s frontmatter (model: haiku), or let Claude pass a model when it delegates. The built-in Explore subagent runs on your main conversation’s model, so define your own exploration subagent, or a project subagent named Explore, with model: haiku to route exploration to Haiku 5.5. CLAUDE_CODE_SUBAGENT_MODEL sets a default for subagents that don’t choose a model, except the built-in Explore and Plan subagents. Subagent requests still count toward your usage.
Key Insight
Cost optimization is not about using the cheapest model. It is about using the right model for each task, which often means a mix of models at different price points.
A workflow using Haiku for search, Sonnet for coding, and a top-tier model for architecture keeps quality where it matters while spending far less than running the top-tier model for everything.
The second insight: context size is a multiplier. Because the full context is sent on every API call, reducing context from 50K to 20K tokens saves 30K tokens on every subsequent call. Over a 30-call session, that is 900K tokens saved --- and even at cache-read rates, that adds up.
This is why the patterns from earlier sessions --- subagent isolation (Session 4), context compaction (Session 6), targeted tool use --- are not just about quality. They are directly about cost.
Hands-On Example
Configuring a Cost-Optimized Workflow
Step 1: Categorize your tasks
Feature: Add search functionality
Exploration (Haiku):
- Find existing search-related code
- List database tables
- Check package.json for search libraries
Implementation (Sonnet):
- Write search API endpoint
- Create search index
- Build search UI component, write tests
Architecture (Opus):
- Decide: full-text vs fuzzy match vs external service
- Design search index schema
Step 2: Use a subagent for exploration
Save this as .claude/agents/explorer.md so exploration runs on Haiku 5.5 in its own context:
---
name: explorer
description: Read-only codebase search and summaries. Use proactively for finding files, listing routes, and tracing usages.
tools: Read, Glob, Grep
model: haiku
---
Search the codebase and answer with file paths and a short summary.
Do not propose or make changes.
Step 3: Keep CLAUDE.md lean
# Expensive (2000 tokens):
This project is a web application built with React 18,
TypeScript 5.3, Tailwind CSS 3.4, Prisma ORM 5.x...
[extensive descriptions, standards, deployment procedures]
# Lean (400 tokens):
Tech: React 18, TypeScript, Tailwind, Prisma, PostgreSQL
Style: Prettier defaults, no semicolons
Test: Vitest, run with "pnpm test"
Build: "pnpm build", deploys via GitHub Actions
Key dirs: src/api/, src/components/, src/db/
The lean version gives Claude Code what it needs on every call. Move deployment procedures and other workflow detail into skills, which load only when invoked.
Step 4: Measure and adjust
After a session, run /usage (alias /cost):
- Session cost estimate and tokens by model (API billing)
- Prompt cache line: share of input served from cache, misses
- On Pro/Max/Team/Enterprise: what counted against plan limits
(skills, subagents, MCP servers), with recommendations
Over time, you'll develop intuition for:
- When to delegate to a cheaper subagent
- Which effort level a task needs
- When to /clear instead of carrying context forward
Step 5: Know the cost-quality tradeoff
SAVE money on: INVEST money on:
├── File search ├── Security-critical code
├── Directory listing ├── Data migration logic
├── Running commands ├── Architecture decisions
├── Simple formatting ├── Complex debugging
├── Boilerplate generation ├── Performance optimization
└── Repetitive edits └── API design
Rule of thumb: if getting it wrong costs more than getting it right, use the best model. If the task is mechanical and easily verified, use the cheapest.
What Changed
| Unoptimized | Cost-Optimized |
|---|---|
| One model for everything | Right model per task |
| Default effort for every task | Effort matched to the task |
| Large CLAUDE.md (2000+ tokens) | Lean CLAUDE.md; workflow detail in skills |
| Read all files in directory | Targeted, specific reads |
| Explore in main context | Explore via Haiku subagents |
| Context fills up, re-sent bloated | /clear and /compact at task boundaries |
| No awareness of token cost | /usage checked, conscious model and context decisions |
Next Session
Session 22 covers Human-in-the-Loop --- how to design workflows where the AI operates autonomously on routine tasks but pauses for human approval on critical decisions, balancing speed and safety.