Back to All Tutorials
AI & TechBeginner

Mastering Claude Code: The Token-Efficiency Playbook

How I cut my Claude Code token usage by 60% without sacrificing output quality — the exact system I use every day

Dr. Sam Mokhtari
~9m

Mastering Claude Code: The Token-Efficiency Playbook

How I cut my Claude Code token usage by 60% without sacrificing output quality — the exact system I use every day.

The Real Cost: Why Token Discipline Matters

Most developers blame the model when their AI coding bill spikes. The real problem is almost always the workflow. I have watched teams burn through their entire monthly allocation in days — not because they coded more, but because they let context bloat, never cleared sessions, and ran everything on the most expensive model.

$150–250

Average monthly cost per developer across enterprise Claude Code deployments

60%

Typical token reduction when teams apply disciplined context management

93.8%

Share of tokens routed to Opus by default — the most expensive model — if you change nothing

Sam's take

Token efficiency is not about using the tool less. It is about configuring it properly and managing conversations with intention. Fix the workflow and you fix the cost.

Token costs scale with context size: every message you send carries the entire conversation history, all loaded files, every MCP server definition, and your CLAUDE.md configuration. A one-line question in a session open all day still pays for everything that came before it.

The Four Layers of Token Efficiency

I organise my Claude Code cost-control system into four progressive layers. Each builds on the last. Start at the top and work down — the earlier layers give the biggest return for the least effort.

01

Observe

Use /usage, /context, and the status line to see where tokens actually go. You cannot fix what you cannot measure.

02

Reduce Base Context

Keep CLAUDE.md lean, use .claudeignore, uninstall idle MCPs, and move rare instructions into skills. Every byte here is paid on every single message.

03

Session Discipline

Use /clear between unrelated tasks, /compact within long tasks, and start fresh each day. Session hygiene is the highest-leverage habit.

04

Model Routing & Delegation

Use Sonnet as default. Reserve Opus for architecture decisions. Delegate heavy I/O to Haiku subagents. Use skills for on-demand playbooks.

Layer 1: Observe Your Usage

Before optimising anything, I check where my tokens are actually going. Claude Code gives you three commands for this, and I use all three at natural breakpoints — not after every prompt, but when a session starts feeling slow, after a large tool run, or before handing off.

CommandWhat it shows
/usageSession cost, model breakdown, cache hit rate, behaviour flags. Aliases: /cost, /stats
/contextWhat is consuming your context window right now — conversation, files, MCPs, memory
/insightsHTML report analysing up to 200 sessions: friction points, patterns, suggestions
Sam's take

Configure your status line to show context usage continuously. When you can see the number climbing, you naturally start clearing earlier.

Layer 2: Build a Lean CLAUDE.md

CLAUDE.md is sent on every single API call. Every word in it costs tokens on every message. I treat it as a tight index — only essentials, not an operations manual. Move rare instructions into skills; they load on demand.

Before — bloated (2,000 lines)

Full project history and decision rationale. Complete API documentation. Migration runbooks. PR review checklists. Code style guide with 50 examples. Deployment procedures. Every convention ever discussed.

⚠ Costs ~8,000 tokens per message before you type anything

After — lean (<200 lines)

Build and test commands. Key directory map. Hard constraints (never touch vendor/, generated/). Compact instructions. Pointers to skill files for rare workflows.

✓ Under 2,000 tokens — saves ~6,000 tokens per message

Lean CLAUDE.md template
# Project commands
build: npm run build
test:  npm test -- --reporter=dot
lint:  npm run lint

# Directories
src/       — app code
tests/     — test files
.planning/ — specs and ADRs (read only)

# Hard constraints
Never edit vendor/ or generated/
Always run lint before committing

# Rare workflows → use skills
/review, /deploy, /release

The goal is ruthless compression. If a rule is not violated at least once per week, it probably does not belong in CLAUDE.md. Put it in a skill instead — it will load on demand and cost nothing when it is not needed.

Scoped Inputs: Filter Before Claude Reads

The other side of base context reduction is what you feed Claude at runtime. Most developers hand over entire log files, full diffs, and broad directory scans. This is almost always wasteful.

TechniqueWhat it doesToken saving
.claudeignoreExcludes directories from scanning (like .gitignore). Add node_modules/, dist/, .git/, vendor dirsPrevents thousands of wasted file-read tokens
Filtered logsgrep -E "ERROR|FAIL" app.log | head -80 instead of the full logFrom 50K tokens to under 500
Scoped diffsgit diff --stat first, then git diff -- src/auth.ts for the specific fileAvoids reading entire repository diff
Fewer MCPsUninstall MCPs you are not actively using. Each one adds tool definitions to contextMCP optimisation saved 80–85% after Anthropic's deferred loading update
CLI over MCPPrefer gh, aws, gcloud CLI tools — they add zero per-tool listing overheadCLI tools are more context-efficient than MCP equivalents
Sam's take

I keep only one MCP installed: Playwright. Everything else gets installed when I need it and removed when I do not. Having MCPs "just in case" is throwing tokens away.

This pattern works because it does not hide data — it changes the first slice Claude sees. If that slice is insufficient, ask for the next section. Start narrow, widen on evidence.

Layer 3: /clear vs /compact — Know the Difference

These two commands solve different problems, and confusing them is the most common mistake I see. /clear starts a brand-new session with zero context. /compact summarises the current session to free space while keeping continuity.

CommandWhen to use
/clearSwitching tasks. Costs zero tokens. Resets session.
/compact [focus]Same task, heavy context. Costs tokens to summarise. Keeps decisions.
/rewindWrong direction. Restores to a checkpoint. Undo wasted work.
The rule

Switching to unrelated work? /clear. Same task but the context is heavy? /compact with a focus prompt. Never let a session hit auto-compaction — by then you have already paid the tax.

The Cache You Lose When You Sleep

Anthropic caches the token prefixes that repeat between calls, and reading from cache costs a fraction of the normal price. But that cache has a limited lifespan — if you pause for more than an hour, it evaporates.

When you resume an old conversation after the cache expires, the entire context has to be reprocessed from scratch at full price. You are effectively paying for the same conversation twice. This is why I start a new conversation each day rather than trying to pick up yesterday's thread.

Subscription cache TTL

1 hour on seat-based plans. Drops to 5 minutes when drawing on usage credits.

API / Cloud cache TTL

5 minutes by default. Can be extended with explicit TTL configuration.

Resume from summary

On Pro/Max, Claude Code offers to resume from a summary so later requests skip the full history.

Git as session boundary

Commit before closing a session. Start next session with state from the commit, not from memory.

Sam's take

My rhythm: start fresh each morning. Commit progress at the end of each session. If I need Claude to know something from yesterday, I pass a one-paragraph summary — not the whole history.

Warning

Background token usage happens even when idle: conversation summarisation for claude --resume, prompt suggestions, goal check-ins, scheduled tasks, and cross-session messages all send your full context. Disable what you do not need.

Layer 4: Right Model for the Right Job

The single highest-impact change I made was setting Sonnet as my default model instead of Opus. The difference between a refactor on Opus and the same refactor on Sonnet can be $5 versus $0.50 — on a single task. Over a month, it compounds dramatically.

Opus — Complex reasoning

Architecture decisions. Multi-step debugging across files. Novel design patterns. Tasks requiring deep analysis where getting it wrong costs more than the model premium.

Sonnet — Daily default

Most coding work. Feature implementation, refactoring, code review, test writing. Practically the same quality as Opus for 80% of tasks at a fraction of the cost.

Haiku — Bulk operations

Code search, browser interactions via Playwright, file scanning, running tests, log parsing. Fast and cheap for high-I/O tasks where reasoning depth is not critical.

/effort — Fine-tune depth

The /effort command controls how many tokens Claude spends per response. Lower effort = fewer tokens for simple tasks. Available as low, medium, high, max.

Sam's take

Use /model to switch mid-session. Set your default to Sonnet in /config. Only escalate to Opus when you genuinely need deep reasoning — not out of habit.

Subagents and Skills Architecture

Each subagent works with its own context window, separate from the main conversation. When it finishes, only a summary returns. All intermediate work — file reads, searches, tests — stays isolated.

This means your main conversation stays clean for much longer. You delay or avoid compaction entirely. Skills work similarly: they are reusable instructions that load only when invoked, unlike CLAUDE.md which is always present.

Sam's take

I run 3–5 well-defined agents: main orchestrator on Opus, development agent on Sonnet, testing agent on Haiku. Each has the right model for its job. No waste.

My Pre-Flight Checklist

I run through these steps before every significant coding session. It takes 30 seconds and saves thousands of tokens — and often hours of degraded output from a bloated context.

1

Start a fresh session

Never continue yesterday's conversation. Cache is gone, context is stale. Start clean, pass a one-paragraph summary if needed.

2

Check your model

Run /model. Is it Sonnet? Good. Only switch to Opus if this task genuinely needs deep reasoning.

3

Scope the task precisely

Write a specific prompt: "Add input validation to the login function in auth.ts" — not "improve the auth module."

4

Use plan mode for complex work

Press Shift+Tab twice to enter plan mode. Let Claude propose an approach before it starts coding. Prevents expensive re-work.

5

Monitor context window

Watch the status line. At 50% window usage, consider /compact. At task boundaries, /clear.

6

Commit and close

When the task is done: git commit, then /clear or close the session. Do not carry finished work into the next task.

Sam's take

Think of each session like a clean workbench. You would not start welding with yesterday's scraps still covering the table. Same principle applies to your context window.

Hooks: Automate the Discipline

Hooks are shell commands that run at fixed Claude Code lifecycle events. The most powerful token-saving hook intercepts test output and filters it down to just the failures — before Claude ever sees it.

Without hook

Claude runs npm test, receives 10,000 lines of output including passing tests, verbose logs, stack traces. The entire output enters context. Next question costs tokens to re-read all of it.

~50,000 tokens consumed by test output

With PreToolUse hook

Hook intercepts the test command, pipes output through grep -E "FAIL|ERROR" | head -100. Claude sees only the 15 lines that matter. Full log saved to disk for reference.

~800 tokens — a 98% reduction

Hook setup
// In settings.json → hooks → PreToolUse
{
  "matcher": "Bash",
  "hooks": [{
    "type": "command",
    "command": "~/.claude/hooks/filter-test-output.sh"
  }]
}

// The script: intercepts test commands,
// filters to failures, keeps full log on disk

Other high-value hooks: filter git log output to recent commits, truncate large file reads, strip verbose compiler warnings. The principle is always the same: Claude needs evidence, not a dump.

Sam's take

Start with the test-output filter hook. It is the single most effective hook I use. Then add hooks for any command that regularly dumps more than 200 lines into your context.