How to Cut Token Costs in Claude Code, Cursor & Cline
Coding agents are token-hungry by design: every turn re-sends system prompts, tool definitions, file contents, and a growing pile of conversation history, so a long Claude Code or Cline session can burn millions of input tokens before it lands a fix. The good news is that most of that spend is redundant — the same context, sent again and again. This guide ranks the techniques that actually move your bill: prompt caching (cached reads bill at 10% of input), context editing that auto-clears stale tool results, trimmed memory/context files, cheaper models for routine steps, not re-sending the whole repo, and routing through a gateway. We end with a worked before/after cost example so you can see the arithmetic, not just the advice.
Why coding agents burn so many tokens
Because they re-send stable context on every turn and let history grow unbounded — and you pay for input tokens each time. A Claude Code, Cursor, or Cline session is a loop: read files, call tools, get results, reason, repeat. Every iteration re-transmits the system prompt, the tool definitions, whatever files are in context, and the entire accumulated transcript. A 20-turn session on a large file can re-send the same 30,000-token prefix twenty times — 600,000 input tokens where 30,000 of unique content ever mattered.
Anthropic frames the discipline of fixing this as context engineering — "the set of strategies for curating and maintaining the optimal set of tokens (information) during LLM inference" — an evolution beyond prompt engineering for multi-turn agents (Anthropic engineering). It matters for cost and for quality: Anthropic's term "context rot" describes how, as the number of tokens in the window grows, the model's ability to accurately recall information from that context decreases. A bloated context is both more expensive and less accurate — so trimming is a two-for-one win.
Token-saving techniques, ranked by impact
Start at the top — the highest-leverage lever for a repetitive multi-turn agent is caching, then context trimming, then model routing. This ranking is our synthesis for a typical coding-agent workload (high context reuse, long sessions); your mix may reorder the middle rows.
| Rank | Technique | What it does | Typical leverage | Effort |
|---|---|---|---|---|
| 1 | Prompt caching | Cache the stable prefix; reads bill at 10% of input | Very high (repetitive turns) | Low |
| 2 | Context editing | Auto-clears stale tool calls/results near the limit | High (long sessions) | Low |
| 3 | Grep-before-read | Locate lines first, read only what matters | High (large repos) | Medium |
| 4 | Cheaper model for routine steps | Route searches/boilerplate to a low-cost model | Medium–high | Medium |
| 5 | Trim memory / rules files | Keep CLAUDE.md / rules terse and high-signal | Medium | Low |
| 6 | Compaction & sub-agents | Summarize history; delegate to clean contexts | Medium | Medium |
| 7 | Terse output style | Answer-first, no preamble/postamble | Low–medium | Low |
Leverage is directional, not a guaranteed percentage — it depends on your cache hit rate, session length, and repo size. Sources for each row appear in the sections below.
Prompt caching: cached reads at 10% of input
This is the single biggest lever for a coding agent, because the agent re-sends the same prefix every turn. Per Anthropic's official docs, cache reads (cache hits) are billed at 0.1x — 10% — of the base input token price for that model (Prompt caching docs). That turns a full-price re-send of your system prompt, tool definitions, and long file context into a 90%-off read.
There is a write premium to account for: writing to the cache costs 1.25x the base input price for the default 5-minute TTL, and 2x for the 1-hour TTL. The cache has a default 5-minute lifetime and is refreshed for no additional cost each time the cached content is used — so an active agent keeps its own cache warm. Minimum cacheable prompt length varies by model (for example, 1,024 tokens for Claude Opus 4.8 and Claude Sonnet 5), and you set a breakpoint with cache_control type ephemeral.
{
"model": "claude-sonnet-5",
"system": [
{
"type": "text",
"text": "<long system prompt + tool docs + repo map>",
"cache_control": { "type": "ephemeral" }
}
],
"messages": [ /* per-turn user content, uncached */ ]
}
Watch the response usage object to confirm it is working: cache_creation_input_tokens counts tokens written, cache_read_input_tokens counts tokens read from cache, and total input = cache_read_input_tokens + cache_creation_input_tokens + input_tokens. If your reads stay near zero, your prefix is changing every turn — reorder so the stable part comes first. Net savings depend on the hit rate and the write premium, so treat any headline percentage as illustrative, not a guaranteed figure. The same lever also raises throughput and cost efficiency on the cheapest models — see our cheapest-LLM cost guide.
Context editing & memory files
Let the platform prune stale tool results, and persist what matters to a memory file instead of the transcript. Anthropic's context editing automatically clears stale tool calls and results from within the context window when you approach token limits — removing dead weight while preserving conversation flow so agents run longer (Context management). The reported numbers are strong, though they are Anthropic's own internal-evaluation figures: in a 100-turn web-search evaluation, context editing cut token consumption by 84%; context editing alone improved agentic-search performance by 29%, and the memory tool combined with context editing by 39% over baseline.
The memory tool lets Claude create, read, update, and delete files in a dedicated memory directory stored in your own infrastructure, persisting across conversations; it operates client-side through tool calls with you managing the storage backend. For long-horizon tasks Anthropic recommends three complementary techniques: compaction (summarize history and reinitiate a fresh context window), note-taking / persistent external memory, and sub-agent architectures where specialized agents work in clean context windows and return condensed summaries to a lead agent.
The everyday version of this is your rules file — CLAUDE.md, Cursor rules, or an AGENTS.md. Every token in it is re-sent every turn, so keep it terse and high-signal; the guiding principle Anthropic states is to find "the smallest possible set of high-signal tokens that maximize the likelihood of the desired outcome."
Stop re-sending the whole repo
Locate the relevant lines first, then read only those — never paste whole files speculatively. The most wasteful pattern in coding agents is dumping entire files (or, worse, whole directories) into context on the chance something is relevant. You pay for every one of those tokens on every subsequent turn, and "context rot" means the extra tokens actively dilute recall.
The emerging convention here is grep-before-read: search for the symbol or string, then open only the lines around the hits. As defined by the token-diet project (Kulaxyz) — an always-on token-efficiency skill for Claude Code, Codex, Cursor, Windsurf, and Cline — grep-before-read context management sits alongside batching independent tool calls and delegating searches to cheaper sub-agent models as its core tactics. It is one project's approach, not an industry standard, but it maps directly onto how every agent already exposes search-then-read tools. If you compare agents on how well they do this, our Claude Code vs Cline comparison digs into their context-handling differences.
Cheaper models for routine steps
Reserve frontier models for reasoning; send the mechanical work to a low-cost model. A coding agent spends a lot of its turns on things that do not need an Opus-class brain: locating files, running searches, summarizing tool output, generating boilerplate. Routing those to a cheaper model is one of the token-diet skill's named tactics ("delegating searches to cheaper sub-agent models"), and it compounds with caching — a cheap model with a cached prefix is about as low-cost as an agent step gets.
Good routine-step candidates as of July 2026 include open and low-cost models such as GLM-5.2 and gpt-oss-120b, with a frontier model like Claude Opus 4.8 held back for the hard reasoning. For picking the reasoning model, see our best coding LLM guide; for the mechanical tier, the cheapest-LLM API rundown. If your agent uses a planning step, note that sequential-thinking in Claude Code spends extra reasoning tokens — worth it for hard problems, wasteful for routine ones, so gate it.
The token-diet convention (attributed, not a standard)
Two unrelated projects share the name "token-diet" — both are single-project approaches, and both report their own numbers. Be precise about what is verified here: these are the projects' self-reported claims, not independently benchmarked results.
| Project | What it is | Approach | Self-reported result |
|---|---|---|---|
| Kulaxyz/token-diet | Always-on token-efficiency skill for coding agents | Terse replies, grep-before-read, batch tool calls, cheap sub-agents, YAGNI code | ~31% lower bill on average (−17% to −54% by session type), real Sonnet 5 runs, o200k_base tokenizer |
| LakshmiSravyaVedantham/token-diet | CLI prompt compressor | Offline rule-based substitutions (gentle/balanced/aggressive) + optional Claude-Haiku-powered rewriting | 72.4% token reduction on one sample prompt (README example) |
The Kulaxyz skill's ethos — lead with the answer, no preamble/postamble, minimal-wording docs, targeted tests, YAGNI code — is a sensible checklist even if you never install it. Just do not cite either project's percentage as an industry benchmark: they are illustrative, single-source figures (verified against the repos, July 2026).
A worked before/after cost example
Here is the arithmetic on one realistic session so you can see where the money goes. Assume a 20-turn coding session on Claude Sonnet 5 at $2 per million input tokens (the price shown on the model page), a stable prefix of 30,000 tokens (system prompt + tool defs + repo map) re-sent every turn, plus 3,000 new input tokens per turn. Output cost is held constant across scenarios so we isolate the input lever. These are illustrative numbers using the published input price, not a measured benchmark.
| Scenario | Prefix billing | Input tokens billed | Input cost |
|---|---|---|---|
| Before — no caching | 30k × 20 at full price | 660,000 | $1.32 |
| After — prompt caching | 1 write (1.25x) + 19 reads (0.1x) | ~154,500 effective | ~$0.31 |
After math: prefix write = 30k × 1.25 = 37,500 effective input-token-equivalents; 19 cached reads = 30k × 19 × 0.1 = 57,000; new content = 3k × 20 = 60,000. Total ≈ 154,500 effective units × $2/M ≈ $0.31. That is roughly a 4× reduction on input spend on this profile — driven entirely by the 0.1x cache-read price and the 1.25x one-time write premium. Add context editing to stop the transcript from growing unbounded and a cheaper model for the routine sub-agent turns, and the two levers stack on top of this.
Routing through a gateway
A gateway turns "which model for which step" into config, keeps caching on by default, and fails over on rate limits — behind one OpenAI-compatible key. The techniques above are individually simple but tedious to wire per provider: caching flags, a cheap model for sub-agents, a frontier model for reasoning, retries when one provider is rate-limited. A gateway consolidates all of it. You point your agent at one base URL, choose the model per call, and the routing and failover happen underneath.
from openai import OpenAI
client = OpenAI(
base_url="https://www.datallmlab.com/v1",
api_key="YOUR_DATALLMLAB_KEY",
)
# routine sub-agent step -> cheap model
search = client.chat.completions.create(
model="z-ai/glm-5.2",
messages=[{"role": "user", "content": "grep for the failing symbol and summarize"}],
)
# hard reasoning step -> frontier model
plan = client.chat.completions.create(
model="anthropic/claude-opus-4.8",
messages=[{"role": "user", "content": "design the fix given this summary"}],
)
Because the endpoint is OpenAI-compatible, it drops into Cursor, Cline, or any agent that speaks the OpenAI schema. For how routing and failover are wired, see what an LLM gateway is; for choosing the model tiers, the best LLMs for AI agents.
Cut your coding-agent bill on one key
DataLLM Lab routes across 300+ models: send routine sub-agent steps to a cheap model, reserve a frontier model for reasoning, keep prompt caching on by default, and fail over on rate limits — all behind one OpenAI-compatible endpoint.
FAQ
What is the single biggest way to cut token costs on a coding agent?
Prompt caching. Per Anthropic's docs, cache reads bill at 0.1x (10%) of the base input price. A coding agent re-sends the same prefix every turn, so caching that stable content turns a full-price re-send into a 90%-off read. Writes cost more (1.25x for 5-minute TTL, 2x for 1-hour), so net saving depends on your hit rate — high for a repetitive agent.
Does prompt caching actually save money or just add latency?
It saves money when content is reused. The first write is 1.25x base input (5-min TTL) or 2x (1-hour); every hit within the TTL reads at 0.1x. The 5-minute cache refreshes for free on each use, so an active agent stays warm. Minimum cacheable length varies by model — e.g. 1,024 tokens for Opus 4.8 and Sonnet 5.
What is context editing and how much does it save?
An Anthropic feature that auto-clears stale tool calls/results near the token limit while preserving flow. In Anthropic's own 100-turn web-search eval it cut token use by 84%; context editing alone lifted agentic-search performance 29%, and with the memory tool 39% over baseline. These are Anthropic-reported internal figures.
Should I use a cheaper model for routine coding-agent steps?
Yes for mechanical steps — searches, grep lookups, boilerplate, summarization rarely need a frontier model. The token-diet skill (Kulaxyz) delegates searches to cheaper sub-agent models as a core tactic. Reserve Opus-class models for reasoning; a gateway makes the split trivial.
Why does re-sending the whole repo cost so much?
Input tokens are billed every turn, so pasting whole files repeatedly pays for them again and again. Anthropic's "context rot" also means the extra tokens hurt recall. Fix it with grep-before-read — locate the relevant lines, then read only those.
Do the token-diet repos really cut bills by 30-70%?
Those are self-reported project numbers, not verified benchmarks. Kulaxyz/token-diet claims ~31% lower bill on average (−17% to −54%) from Sonnet 5 runs. A separate LakshmiSravyaVedantham/token-diet CLI compressor shows 72.4% reduction on one sample prompt. Treat both as illustrative.
How does a gateway help cut token costs?
It lets you route each step to the cheapest capable model, keep caching on by default, and fail over on rate limits — behind one OpenAI-compatible key. Routine sub-agent work goes to a low-cost model, frontier models handle reasoning, and the routing is config rather than a rewrite.
DataLLM Lab