Toggle theme
~/wiki / spravka / kak-snizit-rashod-tokenov-claude

How to reduce the consumption of Claude tokens: a complete guide for developers and vibcoders

Main chat

A chat for vibe coders: news, guides, live cases, marketplace, and finding executors.

$ cd section/ $ join vibe dev
How to reduce the consumption of Claude tokens: a complete guide for developers and vibcoders - обложка

Every time you send a new message, the model receives the entire conversation history - every previous message, every previous response - as input data and processes it again from scratch. This is a fundamental property of transformer models: there is no memory between API calls, each request reproduces the entire context from the start.

In practice, this means that the consumption of tokens increases quadratically with the length of the conversation. The long session, the connected MCP tools, the big CLAUDE.md, the extended thinking – all this is imperceptibly summed up and eventually turns into a score that surprises.

The Branch8 team documented the optimization: in the first month they spent $ 2,400 (about 240 million tokens). After the implementation of optimizations by the third month, expenses amounted to $680 - a decrease of 72%. >

Let’s take everything from the most obvious (model selection) to the subtle but meaningful things (right time for /compact and CLAUDE.md structure).


Why do you spend more than you think

Before optimizing, it is worthwhile to understand where tokens come from, because intuition often fails here.

The system prompt is always loaded. CLAUDE.md loads before Claude reads your code, before reading the task, before everything. A 5,000-token CLAUDE.md costs 5,000 tokens on every move, every session. A constant base value that you carry all the time. >

Tools and MCP connectors also take up space. Each MCP connector (Google Drive, Slack, Calendar, etc.) and each tool included uploads its full definition to the context box with each message whether you use it or not. If you have 5 connectors connected and you don’t use any of them for a code task – you’re spending thousands of tokens on a message just to define tools. >

Output tokens cost 5 times more than input. <cite index="29-1" Output tokens are paid exactly five times at the rate of input tokens in the current Anthropic API. You pay for a 2,000-word answer you didn’t need several times: once it’s written, and once for each subsequent move that rereads it. >

Extended thinking is enabled by default. Extended thinking is enabled by default because it greatly improves performance on complex planning and reasoning tasks. Thinking tokens are paid for as output tokens, and the default budget can be tens of thousands of tokens per request depending on the model. >


Layer 1: Model selection is the biggest lever

This is the most important decision, which depends on 50-70% of the total cost. Not every task requires a powerful model.

Current prices and opportunities

Модель Входящие / млн Исходящие / млн Для каких задач
Haiku 4.5 $1 $5 Классификация, переименование, форматирование, простые Q&A
Sonnet 5 $2 → $3* $10 → $15* Большинство задач кодирования, повседневная работа
Opus 4.8 $5 $25 Сложный архитектурный анализ, нетривиальный рефакторинг

*Introductory pricing until August 31, 2026, then standard prices.

Haiku costs 15 times cheaper than Opus on input tokens and 5 times cheaper than Sonnet. For tasks like “rename a variable throughout a file” or “convert JSON to a TypeScript interface,” Haiku is absurdly cheap and absurdly fast. >

Model selection rule

plaintext
Mechanical task (rename, formatting, simple Q&A) → Haiku
Standard task (most coding, multifile logic) → Sonnet 5
The problem is complex (architecture, non-trivial refactoring) → Opus 4. 8

Where Haiku breaks are tasks that look simple but require reading code and making decisions. It gives the wrong answers faster, which costs you a correction cycle. In doubtful cases, Sonnet is a reliable middle ground. >

opusplan: Opus for planning, Sonnet for implementation

<cite index="28-1" If you need Opus-level reasoning but want to control costs, the opusplan model pseudonym provides an automated hybrid approach: Claude uses Opus during scheduling mode for complex reasoning and architectural decisions, then automatically switches to Sonnet for code generation and implementation. >

In Claude Code, this is the /model opusplan command – you pay for Opus only at the planning stage, and all further work is done on Sonnet.


Layer 2: Levels of Effort – Depth of Thinking Management

The effort option allows you to directly control how many tokens Claude spends thinking about the response. This is one of the quickest ways to reduce costs without changing the model.

Five levels

You can raise the level to max for absolutely maximum opportunities, or lower it to more conservatively spend tokens, optimizing speed and cost while taking some reduction in capabilities. >

Уровень Когда использовать
low Простая классификация, быстрые поиски, высокообъёмные задачи
medium Большинство повседневных задач разработки
high По умолчанию. Сложные задачи, требующие глубокого рассуждения
xhigh Нетривиальные архитектурные решения
max Критически важные задачи, где любая ошибка дорого обходится

Claude Code: /effort command or /model configuration.

Through the API:

python
import anthropic

client = anthropic.Anthropic()

# Экономный вариант для простых задач
response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    effort="low",  # вместо high по умолчанию
    messages=[{"role": "user", "content": "Переименуй переменную foo в bar"}]
)

# Полная мощность для сложных задач
response = client.messages.create(
    model="claude-opus-4-8",
    max_tokens=8192,
    effort="max",
    messages=[{"role": "user", "content": "Спроектируй архитектуру системы кэширования"}]
)

Limiting Thinking Tokens Directly

For models with a fixed thinking budget, the constraint through the environment variable is:

bash
# Limit thinking to 8,000 tokens instead of tens of thousands by default
export MAX THINKING TOKEN=8000

<cite index="24-1" For simpler tasks where deep reasoning is not necessary, you can reduce costs by lowering the level of effort using /effort or in /model, turning off thinking in /config, or installing MAX THINKING TOKENS. Thinking off is not available on Fable 5 - it always uses extended thinking. >


Layer 3: Prompt caching – up to 90% savings

Prompt caching is the most profitable tool if you use the API directly.

How it works

Cash write-tokens cost 1.25× standard rate (one-time cost), but the cache read-tokens cost only 0.1× - a 90% discount. If your system prompt consists of 10,000 tokens and you make 100 API calls, you will save approximately 990,000 processing tokens. >

ProjectDiscovery's agent Neo documented a 59% cumulative decline from prompt caching alone, reaching up to 90%+ on fully optimized pathways. >

Rule of request structure

Static content should always come first, dynamic content should come last

plaintext
1. System instructions (cached)
2. Tool diagrams (cached)
3. Context from the knowledge base / documentation (cached)
4. Few-shot examples (cached)
5. A specific user message (not cached - changes each time)

Implementation through Python SDK

python
import anthropic

client = anthropic.Anthropic()

# Системный промпт с кэшированием
response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    system=[{
        "type": "text",
        "text": "Ты — старший Python-разработчик. Всегда пиши типизированный код...",
        "cache_control": {"type": "ephemeral"}  # ← включаем кэш
    }],
    messages=[{
        "role": "user",
        "content": "Напиши функцию валидации email"
    }]
)

The cache lasts 5 minutes from its last use (and is renewed every time it is used). This means that with active work with one prompt, the cache will be active throughout the session.

In Claude Code

Claude Code automatically optimizes costs through prompt caching, which reduces the cost for repetitive content such as system prompts. No need to disable - it works automatically.


Layer 4: Context Management is the Main Source of Invisible Spending

Context isn’t just “chat history.” This is everything Claude carries with it in every message: the files it has read, the command conclusions, the tool definitions, CLAUDE.md. Each request pays for the entire cargo again.

/compact: when and how

<cite index="33-1" Time is more important than people think. By the time Claude has checked multiple files, executed commands, and investigated a few false tracks, your session usually contains a lot of material that is no longer important. This is the right time for compact. A common mistake is to use /compact too late. If the compact is done earlier while the session is still healthy, the summary will be much better. >

bash
#Basic compression
/compact

# Instructions on what to save
/compact Save only: architectural decisions made, final function code, open bugs

# Focusing on the concrete.
/compact Focus on code samples and API usage

/clear: between tasks

When you switch to a fundamentally different task, complete cleaning is cheaper than dragging the entire context

bash
/rename "feature-auth-jwt" # first renamed for history
/clear # then clear

Controlling what gets into context

CLAUDE.md: Keep it compact. The 5,000 tokens in CLAUDE.md are 5,000 tokens on each turn of each session forever. Leave only what you really need for each request:

markdown
# What to Leave in Claude.md:
Architectural limitations of the project
- Test and assembly start commands
Code style (2-3 key rules, not the whole style guide)
Directories that do not need to be touched

# What to remove from Claude.md:
API documentation (read only if necessary)
Examples of code (transmit in the request when necessary)
Project history and decision context (in a separate file)

**Tools and connectors: * Turn off what you are not using in your current task. In claude.ai: + button → Connectors → Tool access → select only the necessary for the session.

Precision reading of files

Don’t ask Claude to read the entire repository – just give the right context:

bash
# Bad - Claude will read everything
"Look at the project and find the problem."

# Okay, concrete context.
<relevant code >>
paste only the relevant function
</relevant code >>
<error output >>
# paste only the relevant error
</error output >>
<constraints >>
- Do not change the Redis caching layer
Must be backward compatible with v2 API
</constraints >>

Layer 5: Subagents – isolate “noisy” work

Running tests, obtaining documentation, or processing log files can consume significant context. Delegate this to the subagents so that the verbose output remains in the context of the subagent, and only a brief summary returns to your main conversation. >

Subagents (.claude/agents/*.md) run in their own context windows. The task of "check 30 files for style violations" would have polluted the main session with a huge context. The subagent isolates this noise and returns only: "12 violations found, here's a list.".

bash
# Create a subagent for a resource-intensive task
/agents create code reviewer
“Check the /src directory for compliance with our coding standards.
Return only the list of files with violations and specific lines

Instead of Claude dragging all 30 files into the main context—the subagent works in isolation—the main session remains easy.


Layer 6: Prompt Structure – Accuracy as Compression

<cite index="29-1" Sluggish or unclear prompts lead to worse performance. The vague 15-word prompt, forcing Claude to ask three clarifying questions, costs more in the end than the exact 60-word prompt, which works the first time. >

It’s counter-intuitive, but it’s important: saving tokens on a prompt is a bad idea if it leads to a poor-quality response and a request cycle. A longer, but accurate prompt is ultimately cheaper.

Separate system prompt and user request:

python
# Duplicate instructions in each request
user message = You are a security expert. You're a security expert. Check this code..."

# Good: Separation
System = "You are a senior security officer." Analyze to OWASP standards.
user = "Check this code for vulnerabilities."

Limit the length of the answer explicitly:

python
response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=512,  # не 4096 если нужен короткий ответ
    messages=[...]
)

Use stop sequences to avoid paying for excess tokens:

python
response = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    stop_sequences=["###", "END"],  # остановиться при достижении маркера
    messages=[...]
)

Layer 7: Batch API for non-urgent tasks

<cite index="27-1" Many organizations send requests one at a time, whereas batch processing would be more efficient. >

The Anthropic Batch API offers a 50% discount on incoming tokens for asynchronous queries that do not require an immediate response. Suitable for: generation of documentation, analysis of the code base, creation of test cases, package refactoring.

python
import anthropic

client = anthropic.Anthropic()

# Отправить несколько запросов пакетом
batch = client.messages.batches.create(
    requests=[
        {
            "custom_id": "task-1",
            "params": {
                "model": "claude-sonnet-5",
                "max_tokens": 1024,
                "messages": [{"role": "user", "content": "Задача 1"}]
            }
        },
        {
            "custom_id": "task-2", 
            "params": {
                "model": "claude-sonnet-5",
                "max_tokens": 1024,
                "messages": [{"role": "user", "content": "Задача 2"}]
            }
        }
    ]
)
# Результаты доступны через несколько минут, входящие токены — -50%

Layer 8: Monitoring – Optimize what you see

<cite index="31-1" You cannot optimize what you cannot see. Manufacturing AI teams in 2026 launch a layer of observation that tracks the consumption of tokens per function, user, model with monetary attribution. >

In Claude Code

bash
/usage # current session consumption

The conclusion shows a breakdown by skills, subagents, plugins and individual MCP servers – each as a percentage of the total.

For API applications

Each response from the API contains precise usage data:

python
response = client.messages.create(...)

print(f"Входящие токены: {response.usage.input_tokens}")
print(f"Исходящие токены: {response.usage.output_tokens}")
print(f"Кэш прочитано: {response.usage.cache_read_input_tokens}")
print(f"Кэш записано: {response.usage.cache_creation_input_tokens}")

It is useful to log this data into the database and build analytics: how much each feature of your product costs, which sessions are most expensive, where the cache works and where it does not.


Typical traps

** Mistake #1: Save on Prompt → Pay for Request.** A vague prompt is cheaper only if Claude guessed correctly. If not, you pay for clarification and processing.

Error #2: /compact is too late. By the time the context warning appears, the session is already overloaded and the summary is dirty. Compact is 50-70% cheaper and better.

**Error #3: Tools that are not used. ** Every connected MCP connector costs a token on every message – whether or not you use it.

Error #4: Extended thinking on simple tasks. Default thinking enabled. For the task of “rename the variable” is literally thousands of extra tokens.

Error #5: one big conversation instead of focused sessions. Branch8 broke up big ticketing into short "sprints," covering only one function at a time. Each sprint begins with a compact of existing context and /clear at the end. This resulted in a 67% reduction in cost. >


Quick checklist optimization

plaintext
Model selection:
Haiku for mechanical tasks (rename, formatting, Q&A)
Sonnet 5 for most coding tasks
Opus only for complex architecture and non-trivial analysis
Opusplan for tasks where you need Opus for the plan and Sonnet for implementation

Effort level:
/effort low for simple tasks in Claude Code
MAX THINKING TOKENS = 8000 for limiting thinking costs
Effort high/max only where it really matters

Caching:
∙ cache control: ephemeral on system prompt in API
● Static content comes first in the query structure
Cache in Claude Code is enabled by default - do not turn off

The context:
CLAUDE.md is compact – only what you always need
/compact 50-70% full, not by warning
/clear when switching between unrelated tasks
● Disabled connectors not needed in the current session

Architecture:
● Subagents for noisy output tasks (tests, logs, file analysis)
Batch API for non-urgent batch tasks (-50% input)
∙ max tokens corresponds to the required response size

Monitoring:
/usage tracked in Claude Code
Usage from API responses logged with task attribution

Outcome

A developer who uses Claude effectively does not cut corners. It demonstrates the same engineering judgment that has always distinguished senior engineers: understand a problem before it is formulated, decompose cleanly, provide the right context and no more, critically evaluate the conclusion. The number of tokens is a side effect of clear thinking. >

There is no single silver bullet. <cite index="27-1" Cost optimization is rarely achieved by a single change. It comes from a combination of smart model selection, efficient prompt design, context management, caching strategies, and API settings. >

Order of priorities: correct model for the task → level of effort → cache of prompts → pure context → subagents → batch for non-urgent. Each level is independent, and even the use of the first two gives a noticeable result today.


*Relevant to Claude Sonnet 5, Opus 4.8, Haiku 4.5 and Claude Code 2.x July 2026. Prices and options are updated – check the current values at docs.anthropic.com. *

$ cd ../ ← back to Reference