Anthropic Official Guide: How to Save Tokens When Talking to Claude Code

Why can a small fix turn into a long session? This guide shows where your usage goes and when to choose clear, compact, rewind, or a Subagent.

By Claude by Anthropic08-17 · 12 min
🎧 Listen to the podcast0:00 / --:--
0:00 / --:--
AI Programming · XiaoHu Explains
One-minute overview
  • Files, logs, and tool results stay in the session and travel with later requests. The earlier irrelevant content enters, the more turns it survives—and the more usage and distraction it creates.
  • Start with long sessions that span multiple tasks, then inspect irrelevant context, an oversized model or Effort setting, and finally prompt-cache invalidation.

Why did my usage quota drop so much after changing only a few lines?

You ask Claude Code to fix a failing test. The final change might be only three lines; but before finding those three lines, it has searched the repository, opened a batch of candidate files, ran hundreds of lines of test logs, and tried a few turns in the wrong direction.

None of that work disappears when Claude finds the answer. Each time you continue, the model must process the system prompt, project rules, files, command results, and conversation history accumulated so far.

This cost model differs from traditional development tools. Editors are often free or sold as monthly or annual subscriptions; fixing one more bug usually does not change the software bill. A coding agent runs model inference for every task. Regardless of how many lines ultimately change, the tokens it reads and generates consume compute on GPUs, TPUs, and similar hardware. The same task can therefore use very different amounts depending on how you approach it.

This creates three direct pain points:

  1. Usage drops quickly, but you cannot see where it went. Subscription users usually see only a changing usage allowance, making it hard to trace the cost to a particular file, log segment, or search.
  2. The longer the session, the harder old information is to shed. Caching can make repeated reads cheaper, but old content still occupies context and may pull Claude's attention back toward directions that no longer matter.
  3. The commands are familiar, but their timing is easy to get wrong. Use /clear for a new task; consider /compact only when the same task enters a new phase; use /rewind when the last few turns went off track. A Subagent can isolate noise, but it also creates another billable context.

Anthropic published this guide to answer those session-management questions. By the end, you should be able to tell whether usage is driven mainly by a long session, irrelevant context, an oversized model or Effort setting, or an invalidated prompt cache. You should also know when to provide files directly, trim logs, cut off history, or hand noisy work to a Subagent.

The original article uses the same failing test to draw two paths. Pointing directly to the test file, Claude reads the test and implementation, modifies and verifies, completing in five requests; just saying "tests fail," it needs to search the repo, open candidate files, read logs, and finally reach the same fix, using eighteen requests.

The same fix task, direct reading of the target file used 5 requests, while searching the repository first used 18 requests. Numbers come from the original article's illustration, describing only this specific scenario.

The 5 and 18 requests describe only the illustrated scenario; they do not imply a fixed cost multiplier. The more important point is that the same code change can accumulate very different amounts of context along the way. The goal is to spend tokens on necessary code, reasoning, and verification while cutting off irrelevant searches, noisy output, and leftovers from other tasks as early as possible.

The five-request path also explains how the bill forms. The first round submits the system prompt, CLAUDE.md, and the task; Claude requests to read the test file, the file result is appended to the session and sent again; then it reads the implementation file, submits the change, runs the test, and finally generates a short summary. Each round includes the previous complete session, but with normal appending, the old continuous prefix can use cache read, and only new tool calls, new files, or new test results need Prefill at normal input price.

A typical call may therefore contain tens of thousands of input tokens while generating only a few hundred output tokens. That does not mean every input token is recalculated at the normal rate: each turn combines cached reads of history, newly added content at the normal input rate, and the current output. This is why avoiding one pointless search or one mid-session model switch can matter more than shaving a few dozen words off the final reply.

Here are the six actions to take first. The rest of the guide explains why they work.

First, do these six things

If you don't want to study token mechanics yet, you can adjust your usage according to the six points below.

  1. Choose model and effort at the start. Use an adequate model for mechanical changes, and raise capability and work depth for fuzzy failures and architectural judgments. Try to avoid frequent switching in the middle of a long session.
  2. Hand over known scope directly to Claude. Provide target files, failing tests, expected results, and verification commands; where the interface supports it, use @filename references from the first time.
  3. Control command output. Run only relevant tests, use quiet reporters, error filtering, or tail; don't leave hundreds of lines of success logs in the next dozens of turns.
  4. Use /rewind when the last few turns went off track. It trims the wrong branch from the end of the session, and the preceding cache prefix may still be preserved.
  5. Use /clear before starting a new task. If you need to recover the old task later, first /rename, then clear the current context.
  6. Use Subagents only when the process is very noisy and the main session only needs conclusions. Scanning long logs, full test outputs, and Git history suits isolation; handing off small issues may be more expensive.

The original article's final diagram gives the priority order: look at long sessions first, then excessive context, then model or effort exceeding needs, and then cache invalidation. This order avoids repeatedly saving in small places while letting old task history be resent every round.

Claude Code session cost four priorities: long sessions, excessive context, model or effort too high, breaking prompt cache.

The following decision diagram distinguishes four easily confused actions. The four applicable boundaries are visible by default; after choosing a scenario, the change is whether history is cleared, compressed, trimmed, or isolated.

Session Action Decider

First determine what happened, then choose the action

Select the current scenario to see whether history is left, compressed, trimmed, or isolated.

Before operation
System contentTask A filesTask A logs
Recommended action/rename → /clear
After operation
System contentTask BClean context

Applicable boundary: If you need an entry point, rename first, then clear. Old session can still be recovered; new task starts from clean context.

Starting another task · /clear
Old task has ended
Same task enters new phase · /compact
Old details have lost value
Recent turns went wrong · /rewind
Previous history is still valid
Process is noisy, only conclusions needed · Subagent
Large amount of logs, tests, or searches
Four actions correspond to four session states; command behavior may change with versions.

First priority: Don't let one session contain multiple tasks

Each request in Claude Code carries the session content up to that point. Files, logs, and tool results from the first task, if they continue into the second and third tasks, will appear repeatedly in subsequent requests.

You can use an approximate relationship to understand cumulative burden:

Session burden ≈ accumulated content in context × subsequent turns this content will experience × number of concurrently running independent contexts.

Finally consider model, output, and cache multipliers. This is an approximation to aid understanding; Anthropic has not published it as an exact billing formula.

The original three-task illustration shows this accumulation. The first segment of history is carried into three turns, the second into two, and the third into one; when all are stuffed into one long session, the token amount in the illustration reaches 1.9 times that of separate sessions. This number belongs only to the illustration's conditions; what to take away is "old content multiplies by the number of turns it survives afterward."

Same three tasks, token comparison between clearing between tasks and putting all in one session. The 1.9 times figure in the original illustration represents only this hypothetical scenario.

Therefore, /clear should follow task boundaries. Its exact timing is when preparing to start a new task, not necessarily waiting until the context is almost full. To keep an entry point to the old session, first /rename then /clear.

/loop applies the same judgment. Each loop iteration is a full request. If periodic monitoring is mounted in a long main session, it will periodically carry the entire history; starting a separate new session with only the materials the loop truly needs is more appropriate.

Second priority: Don't let irrelevant content enter the session too early

The session's initial burden may form before the first task message. Tool definitions, system prompts, CLAUDE.md, and enabled MCP services may enter the context. A new session can run /context once to check what loads at startup; MCP services not currently needed can be checked and disabled via /mcp.

Short project rules that apply over the long term belong in CLAUDE.md. Longer instructions used only in specific workflows are better loaded on demand. The test is simple: anything loaded by default should deserve to appear in every turn.

The task description also determines whether Claude needs to rediscover scope you already know. "Tests fail" triggers search and candidate file reads; "fix utils.test.ts" can save most of the search; in interfaces supporting file references, using @utils.test.ts allows the file to enter the context with the first message, saving one Read tool call.

From "tests fail" to explicit file name, then to @-referencing the file, the search and read tool calls before the fix decrease stepwise. The 6, 1, 0 counts in the illustration are hypothetical.

After a file enters the session, it stays there. @file saves the search, read, and a round trip; the context occupied by the file itself does not shrink. Don't repeatedly @ the same file in subsequent turns, as it may attach a second copy. CLI, Desktop, IDE, and remote environments may have different support for file references; rely on the current interface.

Command output is even easier to lose control of. Tests, builds, git log, and debug logs are appended to history just like files. When the original article was published, output over 30,000 characters was written to a file, with only a preview and path returned to the context; BASH_MAX_OUTPUT_LENGTH can adjust that threshold, and the behavior may change by version. The more common problem is a few hundred lines of noise—not enough to trigger the safeguard, but enough to burden every later turn.

The most effective moves are to run only the relevant test file, use a quiet reporter, show only the lines around errors, filter by log level, or use tail to cap the output. For example, documenting a common command such as npx vitest run <file> --reporter=dot with its quiet flags can save a round of command discovery and keep hundreds of passing-test lines out of the session. For a consistent policy, Claude Code Hooks can also rewrite noisy commands before they run.

The slider below shows how irrelevant content entering too early is amplified by "content amount × subsequent turns." It is a structural illustration, not a Claude Code billing calculator.

Context Debt

Once added, it continues to participate in processing every subsequent turn

Each square represents one subsequent processingColor band length corresponds to amount of irrelevant tokens
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
8,000Tokens8turns64,000Cumulative context processing · token-times
Keep in session64,000
Clear at task switch0
If each turn hits 0.1× cache6,400 full-price input token equivalent

Current: 8,000 irrelevant tokens remain for subsequent 8 turns.

Explanatory estimate: clear only zeros the subsequent carry; does not include first read, output, model price, cache invalidation, or attention effects.

Third priority: Set model, effort, and cache early in the session

The price of a request is affected by three variables: model, input and output stages, and prompt cache state.

Choose a model based on total cost to complete the task

Larger models usually have higher per-token rates. A model that is merely sufficient is often the better choice for clear small fixes, mechanical renames, and formatting. Architectural decisions, ambiguous failures, and cross-system reasoning are where stronger capability is worth paying for.

Looking only at per-token price can also mislead. On difficult tasks, smaller models may need more search, retries, and verification, and still not achieve the same quality. When choosing, compare the total work required to achieve an acceptable result.

Relationship between model quality and token consumption. Left chart shows convergence on simple tasks; right chart shows possible non-convergence on difficult tasks; curves are explanatory, not benchmark measures.

Effort affects how many files the model reads, how many tools it calls, and how thoroughly it verifies. Model defines capability range; effort adjusts how much work it is willing to invest in this round. Mechanical tasks can lower effort; tasks requiring investigation and judgment should keep sufficient depth.

The original article also mentions MAX_THINKING_TOKENS=0 to disable Thinking in a single session, noting Fable 5 as an exception. Such environment variables and model behavior change quickly, so they are better as advanced settings after confirmation with the current version, not as a general default recommendation for all sessions.

Input is read in full; output is generated token by token

A request first goes through Prefill, where the model reads tool definitions, system prompt, CLAUDE.md, messages, files, and command results. This computation happens on the GPU, TPU, or other hardware running the model. Then Decode begins, generating tokens one by one for thinking, tool calls, and visible replies.

Among mainstream Claude models currently listed by Anthropic, output token price is about 5 times input. Reducing unnecessary explanations from the agent helps; but the larger portion in long sessions is often the input history re-carried each round.

Prefill reads the full request at once; Decode generates thinking, tool calls, and answers token by token.

Prompt caching works automatically, but does not clear history

Claude Code manages prompt caching automatically; no extra action is needed. It still resends the full session; when the beginning of the request matches the previous round, the server can reuse the cached state. In Anthropic's current API pricing, cache read is about 0.1 times normal input; five-minute cache write is 1.25 times, and one-hour cache write is 2 times.

Caching requires that the request prefix matches continuously from the start. Requests are typically assembled as tool definitions, system prompt, conversation history; CLAUDE.md is near the front. The earlier a part changes, the more content needs to be re-prefilled afterward. When normally appending files or tool results, old prefix may still hit a 0.1 times read rate; switching model mid-way, changing effort, enabling Fast Mode, running /compact, or waiting until cache expires and returning may cause related history to re-prefill. opusplan switches models when entering and exiting Plan Mode, also such a case. The original article specifically notes that turning off Fast Mode back to the original state does not incur the same recalculation cost at the cache level.

Subscription sessions and API usage also have different default TTLs. The source article gives a current boundary of one hour for subscription sessions and five minutes by default for API keys; API users can opt into a one-hour cache. Each continued turn restarts the TTL timer. If you return to an old session much later, the cache has usually expired and the startup system prompt will be rebuilt. Check the product documentation in effect when you use it for current behavior and prices.

/model and /effort also remember the last selection; new sessions do not necessarily return to defaults. So confirm the actual configuration at the start; when switching is needed, put it at the beginning of a new session or right after /clear, not after long history has formed.

Cache Prefix Lab

Select an action to see where the next round recalculates from

Cache read · about 0.1×Re-Prefill · about 1×Trimmed / replaced
Baseline: Normal Append
Tools0.1×System Prompt0.1×Project Rules0.1×Session History0.1×New Results1×
Current operationNormal Append
Next round after selected action
Tools0.1×System Prompt0.1×Project Rules0.1×Session History0.1×New Results1×

What happens: Tool results are appended at the end, old history continues to hit cache, only the new tail is processed at full input price.

Multipliers are a simplified expression of Anthropic's current pricing relationships; actual billing is also affected by model, output, cache write TTL, and product version.

Caching saves on repeated computation cost, but does not remove old files and logs from context, nor prevent them from influencing model judgment. Therefore, cleaning up irrelevant history is usually more important than repeatedly pursuing caching tricks.

/compact and /rewind also serve different purposes. When the same task enters a new phase and old details lose value, you can use /compact to rewrite history into a summary; if only the last few turns went wrong, prefer /rewind because it only trims the wrong branch and the preceding cache prefix may still be preserved.

When you plan to leave for a long time and return to continue the same task, you can /compact first within the cache validity period. Generating the summary can also leverage the current cache, usually more economical than waiting for expiration and then fully re-reading the old session before compressing.

Subagent is suited for isolating noise, not for all complex tasks

Subagents use an independent context. They have their own system prompt, tools, and CLAUDE.md, and do not inherit the entire history of the main session; after the task, usually only the answer or summary returns to the main session, and the logs and attempts read in between do not follow the main task. The main session also only receives what the Subagent deliberately writes into its report; missed details do not automatically return.

A main session hands logs, tests, and Git history to three independent contexts, finally receiving three answers only.

Scanning long build logs, running full tests with huge output, and searching large Git histories are usually suitable for this isolation. The main session needs conclusions, not to carry all process materials to the end.

The cost is also clear: the Subagent has to reload its own startup context, may re-read files the main session has already seen, and generates an independent multi-turn request. A problem that needs only a few dozen lines of code is often more expensive when handed off.

If a certain type of high-noise task recurs, you can create a dedicated Subagent and explicitly specify a smaller, cheaper model; the original article cites Haiku or Sonnet. Without a separate specification, it uses the main session's current model. This controls the per-task cost of repeated dirty work, provided the main session only needs the final report.

One question suffices: does the main session need the intermediate process later? If only conclusions are needed and the process is noisy, isolation is valuable; if the process itself will serve as a basis for subsequent decisions, keep it in the main session.

When using this guide, remember four boundaries

First, this is an official Anthropic practice guide for Claude Code users. It explains the product's current mechanisms and recommendations, but does not prove that Claude Code is cheaper or more efficient than other agent tools.

Second, subscription quota and API billing are two cost surfaces. Subscribed users may not see per-token amounts, but the same context still consumes usage quota; API users directly face input, output, and cache multipliers.

Third, models, pricing, cache TTLs, interface capabilities, commands, and environment variables all change. The multipliers and operating boundaries here are based on Anthropic's 2026 article published in August and the documentation current at that time.

Fourth, 5 vs 18 requests, 6/1/0 tool calls, and 1.9 times the tokens are explanatory scenarios, applicable only to the conditions in their respective charts.

The useful goal is to reserve tokens for the code, reasoning, and verification the task actually needs. Choose the model and Effort at the start, provide the known scope, and trim logs. Use /rewind when the last few turns go wrong, /clear when switching tasks, and a Subagent only for high-noise work. This will not make every task cheaper, but it removes the most common sources of wasted session overhead.

Source
Maximizing the value of your Claude Code sessionsLydia Hallie·2026-08-14·View primary source
Site note
Based on an official Anthropic Claude Code practice guide published on 2026-08-14; commands and pricing may change with versions.
↑ End of article
✓ This article is free to read in full

Members can copy or download the full Markdown, and let their AI subscribe and ask.

Read the original ↗
📮 New explainers, straight to your inbox

Found this useful? Leave your email — every new explainer, the moment it's out. Unsubscribe anytime.