Skip to content

Claude Code's Code Mode "saves 37% of tokens". That number counts cache reads. ​

Short answer

Code Mode (Claude Code v2.1.323+, experimental, off by default) lets Claude write one piece of JavaScript that runs several tool calls and returns only what it needs to read. The "37% fewer tokens" figure going around comes from a single third-party run, counts cache reads, and leaves out output tokens. On the models Code Mode supports, a cache read is billed at 2.5% to 10% of the base input rate, so a 37% cut in input tokens can be almost nothing on the bill or more than half of it, depending on which tokens went away. Measure your own sessions before you change how you work. Code Mode also needs a Claude subscription or Console sign-in: it does not start through a gateway, a custom ANTHROPIC_BASE_URL, Bedrock, Google Cloud or Foundry.

Facts on this page were checked against Anthropic's documentation on 2026-11-16. Code Mode is experimental, and the docs say it "may change or be removed in any release".

What Code Mode changes ​

Without Code Mode, Claude asks for one tool call (Bash, Read, Edit), reads the full result, then decides on the next call. Every step is a model round trip, and every tool result lands in the conversation.

With Code Mode, Claude writes JavaScript that makes the calls, and Claude Code runs it in your session. One piece of code can run commands in parallel, feed one result into the next call, and return only the part of the output Claude needs. The example from the official docs:

javascript
const files = await $`rg -l "function retryPolicy" src`.text();
const target = files.trim().split("\n")[0];
await edit(target, "maxAttempts: 3", "maxAttempts: 5");
({ edited: target, tests: $`npm test -- retryPolicy`.nothrow() });

You turn it on with an environment variable, in your shell or in ~/.claude/settings.json (project settings files cannot turn it on):

bash
CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 claude

The docs suggest it for tasks with many related tool calls: the same change across many files, a search whose results need filtering before Claude reads them, or several independent commands that can run at once.

Where "37%" comes from ​

The figure circulating on X traces back to one third-party test on v2.1.323: one task, run once each way, 150,364 vs 94,659 input tokens, cache included. That is a 37.0% difference. The same summary reports wall-clock times of 37 s and 15 s without saying clearly which run was which, and quotes the tester: one run each is not a benchmark. We could not find the original test write-up, so treat the number as an anecdote.

Anthropic's Code Mode documentation makes no claim about token savings.

Why fewer tokens is not the same as a smaller bill ​

Claude Code sessions are dominated by cache reads. Every turn re-sends the system prompt, tool definitions and conversation so far, and almost all of that is served from the prompt cache. In two ordinary Claude Code sessions from our own work, 91% and 96% of input tokens were cache reads.

Cache reads are billed at a small fraction of the input rate, and on the models Code Mode supports that fraction is below the usual 0.1x. From Anthropic's pricing page, relative to each model's base input rate:

Token typeMultiplier
Uncached input1x
Cache write, 5-minute1.25x
Cache write, 1-hour2x
Cache read: Fable 5.20.025x
Cache read: Opus 5.5, Sonnet 5.50.05x
Cache read: Haiku 5.50.1x
Output5x

Haiku 5.5 also has a higher rate for prompts over 100,000 tokens, and US-only inference adds 1.1x to everything.

So the question is not "how many tokens did Code Mode save" but "which tokens". Two made-up sessions, both with exactly the 150,364 → 94,659 input totals from the test, priced as Opus 5.5 and expressed in base-input-token units:

Without Code ModeWith Code ModeBill change
A: savings are mostly re-read context5,364 uncached + 10,000 cache write + 135,000 cache read + 3,000 output → 39,6145,159 + 9,500 + 80,000 + 3,500 output → 38,534−2.7%
B: savings are mostly fresh tool output10,364 uncached + 50,000 cache write + 90,000 cache read + 3,000 output → 92,3645,000 + 9,659 + 80,000 + 3,500 output → 38,574−58%

Same headline, very different bills. Two things decide which case you are in:

  • Fewer round trips mostly remove cache reads. Each extra tool round trip re-reads the whole context at 0.05x. Removing it saves many tokens and little money.
  • Large tool output that Claude never needs to read is where the money is. A big search result or test log in the conversation is first written to the cache at 1.25x or 2x and then re-read on every later turn. If Code Mode filters it down before it reaches Claude, that saving compounds.

Output tokens can go the other way. Code Mode means Claude writes code, output is billed at 5x, and the test summary only compared input tokens.

Measure your own sessions ​

Claude Code keeps a transcript of every session as JSONL under ~/.claude/projects/<project>/, and each assistant message carries its usage block. This script sums it and applies the multipliers above. The transcript is not a documented interface, so treat the script as a convenience that may break.

python
#!/usr/bin/env python3
"""Usage: python3 session_cost.py ~/.claude/projects/<project>/<session-id>.jsonl [...]"""
import json, sys

READ = {"claude-fable-5-2": 0.025, "claude-opus-5-5": 0.05, "claude-sonnet-5-5": 0.05}
WRITE_5M, WRITE_1H, OUTPUT = 1.25, 2.0, 5.0

def read_mult(model):
    for prefix, m in READ.items():
        if (model or "").startswith(prefix):
            return m
    return 0.1

def summarize(path):
    msgs = {}  # one message can appear on several lines; keep the last
    for line in open(path, encoding="utf-8"):
        try:
            d = json.loads(line)
        except ValueError:
            continue
        m = d.get("message")
        if d.get("type") == "assistant" and isinstance(m, dict) and m.get("usage"):
            msgs[m.get("id") or d.get("uuid")] = m
    t = dict(uncached=0, write_5m=0, write_1h=0, read=0, output=0, weighted=0.0)
    for m in msgs.values():
        u = m["usage"]
        cc = u.get("cache_creation") or {}
        w1h = cc.get("ephemeral_1h_input_tokens", 0)
        w5m = cc.get("ephemeral_5m_input_tokens", u.get("cache_creation_input_tokens", 0) - w1h)
        r, i, o = u.get("cache_read_input_tokens", 0), u.get("input_tokens", 0), u.get("output_tokens", 0)
        for k, v in (("uncached", i), ("write_5m", w5m), ("write_1h", w1h), ("read", r), ("output", o)):
            t[k] += v
        t["weighted"] += i + w5m * WRITE_5M + w1h * WRITE_1H + r * read_mult(m.get("model")) + o * OUTPUT
    return t

for p in sys.argv[1:]:
    t = summarize(p)
    total_in = t["uncached"] + t["write_5m"] + t["write_1h"] + t["read"]
    print(f"{p}\n  input incl. cache {total_in:,} (read {t['read']:,})  output {t['output']:,}"
          f"\n  bill in base-input-token units: {t['weighted']:,.0f}")

To compare fairly, run the same task in two interactive sessions, one with CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1 and one without (Code Mode does not work with -p, so you cannot script this headlessly), then run the script on both transcripts. Do it on several tasks, not one. Subagent transcripts are stored separately, under the session's subagents/ folder; include them if your task uses subagents.

Who cannot use Code Mode ​

From the requirements section of the docs:

  • Account: a Claude subscription or Console account. Not through a gateway, Amazon Bedrock, Claude Platform on AWS, Google Cloud's Agent Platform or Microsoft Foundry. A custom ANTHROPIC_BASE_URL triggers the "it only works with the Anthropic API" message.
  • Auth settings: not with apiKeyHelper, ANTHROPIC_AUTH_TOKEN, or an Authorization / X-Api-Key header in ANTHROPIC_CUSTOM_HEADERS.
  • Models: Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.2.
  • Surface: an interactive claude session in a terminal, native build. Not -p, the Agent SDK, the VS Code panel, the Desktop app or cloud sessions.
  • Organization: not with the HIPAA configuration or zero data retention.
  • Other settings: not with agent teams, OpenTelemetry export or DISABLE_TELEMETRY.

If Code Mode is not available to you ​

Use a supported sign-in for the sessions where it matters. If most of your work goes through a gateway or a cloud provider, you can still start a separate interactive session signed in with a subscription or Console account for the batch-heavy tasks Code Mode is built for.

Ask for the batching by hand. Without Code Mode, Claude can still write one script and run it in a single Bash call. Asking it to "write a script that does all of this and print only the summary" gets you part of the effect: fewer round trips, less tool output in the context. You lose Code Mode's per-call permission checks inside the script, so review what it runs.

Keep bulky output out of the main conversation. A subagent reads the large search results or logs in its own context and hands back a short answer.

If you build your own agents on the API, the same idea exists as programmatic tool calling: Claude writes code that calls your tools inside the code execution container, and intermediate results do not enter its context. It is listed as stable on the Claude API, Claude Platform on AWS and Microsoft Foundry (hosted on Anthropic), needs the code_execution_20260120 tool version or later, and is marked not eligible for zero data retention. If you call Claude through a gateway or proxy, check that it passes the code execution tool and the container field through before you depend on it.

Before you turn it on ​

The docs list trade-offs that matter more than tokens for some teams. In auto mode the classifier reviews each piece of code before it runs, not each tool call, and it does not see values computed at run time, such as a path taken from search output. Each tool call inside the code still goes through your deny and ask rules and PreToolUse hooks, so keep those on anything you must control. Code that cannot run in the background stops after ten minutes. Code Mode sessions can only be resumed in the terminal with Code Mode on, and Remote Control, Claude in Chrome and computer use are unavailable.

Sources ​


Disclosure: byesu is an LLM API gateway. Code Mode does not start through gateways, ours included, for the reasons listed above.

Got a problem? Contact support or join our group.