How to Reduce LLM Costs for a Coding Agent: Keep the Prompt Cache Hitting, Shrink Context, Route With Care
A coding agent's bill is context size times turns. Prompt caching cuts a modelled Claude Sonnet 5.5 task from $6.68 to $1.04; context pruning and effort limits come next, and a mid-session model switch can cost more than it saves.
The way to reduce LLM costs for a coding agent is to attack the number that drives them: the agent resends its whole context on every turn, so cost grows with context size times the number of turns. Start with prompt caching and keep it hitting, then shrink the context with tool-output filtering and /clear, then lower thinking effort. Route to a cheaper model at task boundaries rather than mid-session, because each model keeps its own cache and a switch rereads the whole conversation at full price. On Anthropic's list prices for Claude Sonnet 5.5, caching alone takes a modelled 40-request coding task from $6.68 to $1.04.
Where a coding agent's money goes
A chat assistant answers once. A coding agent loops: it reads a file, runs a command, reads the result, edits, runs the tests, and every one of those steps is a fresh API request that carries the system prompt, the tool definitions, the project instructions and everything said and returned so far. Anthropic's Claude Code documentation puts it plainly: Claude Code "sends your full conversation with every request," and each tool call sends another request carrying that batch of results.
Two published observations show how lopsided that makes the bill. The team behind the Manus agent wrote in July 2025 that its "average input-to-output token ratio is around 100:1." JetBrains Research, studying the SWE-agent scaffold on the SWE-bench Verified coding benchmark, found that tool observations (file contents, command output, test logs) make up "around 84%" of an average turn. A coding agent's cost is overwhelmingly the cost of rereading what its tools printed.
To make that concrete, take a task of 40 requests on Claude Sonnet 5.5. Assume it starts with 20,000 tokens of system prompt, tools and project instructions, that each request adds 3,000 new tokens (a tool result plus the previous reply), and that each request produces 1,000 output tokens including thinking. The context ends at 137,000 tokens, and the 40 requests send 3.14 million input tokens in total. At Sonnet 5.5's list price of $2 per million input tokens and $10 per million output, that task costs $6.68 without caching, and 94 percent of it is input.
For scale, Anthropic says enterprise Claude Code deployments average "around $13 per developer per active day," with 90 percent of users under $30. Nobody has published a breakdown of real coding-agent spend into uncached input, cache reads, cache writes, output and thinking across a public trace set; the split above is a model, and your own is one command away (see the checklist below).
Prompt caching: the lever that matters most
Prompt caching lets the provider reuse the processed form of a prompt's opening section when the next request starts the same way. Because an agent's requests are append-only, each one is the previous request plus a little more, so almost everything can be served from cache.
Anthropic's prompt caching documentation sets the prices as multiples of the base input rate: writing to the cache costs 1.25 times base input with the default five-minute lifetime, or 2 times with the one-hour lifetime, and reading costs 0.1 times on most models. On Opus 5.5 and Sonnet 5.5 reads cost 0.05 times. Sonnet 5.5 got there on October 7, 2026, when Anthropic's release notes announced it had lowered cache reads "from $0.20 USD to $0.10 USD per million tokens." A new token is written once and then read on every later request, so on Sonnet 5.5 the price that matters for most of the context is $0.10 per million, not $2.
Applied to the 40-request task, caching cuts the cost to $1.04, 84 percent less. The bill also changes shape: cache writes become 33 percent, reads 29 percent and output 38 percent. Once caching works, output and the volume of new tokens matter more than the size of the history.
Independent measurement points the same way, though not on coding work. A January 2026 study by Elias Lumer and colleagues ran more than 500 sessions of a web-research agent across OpenAI, Anthropic and Google and found that "prompt caching reduces API costs by 41-80%." The study also found that naive caching of everything was less reliable than keeping dynamic content at the end and out of the cached block.
What breaks the cache
The cache matches on an exact prefix. Anthropic's docs say the cache is built in the order tools, then system prompt, then messages, and that "changes at each level invalidate that level and all subsequent levels." Changing a tool definition therefore throws away everything. Claude Code's own caching page lists the actions that can cost a full re-read: switching models, changing effort on most models, turning on fast mode, connecting an MCP server or denying a whole tool when tool definitions load upfront, enabling some plugins, compacting, accumulating many images and upgrading Claude Code. Anthropic engineer Thariq Shihipar wrote in April 2026 that past breaks came from "putting an in-depth timestamp in the static system prompt, shuffling tool order definitions non-deterministically, and updating parameters of tools." The team runs alerts on cache hit rate "and declare SEVs if they're too low."
Idle time is the other cache killer. The cache lives five minutes by default, refreshed free each time it is read. The first request after a longer break rereads the full context at the write price. In the model task, one break past five minutes halfway through adds $0.19, taking the task to $1.23; three breaks take it to $1.60.
The one-hour lifetime fixes that at a price. Writes cost $4 instead of $2.50 per million on Sonnet 5.5, so the same task with no breaks costs $1.25 on the one-hour cache. On these assumptions the longer lifetime roughly breaks even with one idle gap and wins with two or more. Claude Code requests the one-hour lifetime by default only for subscribers within plan usage; API-key and cloud-provider users get five minutes unless they set promptCacheTtl to 1h.
One more trap: a gateway that strips the cache markers but still returns success means, in Claude Code's words, that "your entire conversation history bills as uncached input on every turn." If you route traffic through a proxy, check that cache reads appear at all.
Shrinking the context: filtering, masking, and /clear versus /compact
Caching makes each reread cheap, but it does not make it free, and the new tokens each turn adds are still written at full write price. The second lever is to stop large, low-value tool output entering the context at all.
The best public measurement of this comes from JetBrains Research. Its paper "The Complexity Trap," presented at a NeurIPS 2025 workshop, compared a raw SWE-agent with two context strategies across five model configurations on SWE-bench Verified: hiding all but the last ten turns' tool observations ("observation masking"), and having an LLM summarise older turns. Masking roughly halved cost against the raw agent while matching the summariser's solve rate. With Qwen3-Coder 480B, cost per task fell from $1.29 to $0.61 and the solve rate rose from 53.4 to 54.8 percent. Quality was not always held: with Gemini 2.5 Flash in thinking mode, masking cut cost from $0.56 to $0.24 but the solve rate fell from 40.4 to 36.4 percent. The summariser also cost more than it looked, because each summary call gets little reuse from the cache and runs got longer. The authors published their code and data.
In Claude Code the same idea is available through hooks and habits. Anthropic's cost docs show a hook that trims test output to its last 100 lines, and another that greps a 10,000-line log for errors, "reducing context from tens of thousands of tokens to hundreds." They recommend keeping CLAUDE.md under 200 lines, moving workflow instructions into skills that load only when used, preferring CLI tools such as gh over MCP servers, and running /context to see what is taking space. In the model task, halving the tokens each request adds, from 3,000 to 1,500, cuts the cached cost from $1.04 to $0.79, or 25 percent.
/clear and /compact are not interchangeable. /clear starts fresh at no cost and is the right move between unrelated tasks. /compact replaces the history with a summary, which means a request that reads the whole conversation and writes the summary, and a rebuilt cache afterwards. While the cache is warm, Claude Code's docs say that request costs "a fraction of what the context size suggests." In the model task, compacting at request 20 with a 5,000-token summary leaves the total at $1.04: on Sonnet 5.5's cheap reads, the saving on later rereads roughly cancels the summary's output cost. Compaction earns its keep by keeping a long session inside the context window, not by saving money; after a long break it is at its most expensive, because the summary request rereads everything uncached.
Parsec sells a context layer for Claude Code, Codex and opencode that trims unused tool output and thinking, with a free Pro tier. In Parsec's own benchmark, 100 SWE-bench Verified tasks run through headless Claude Code on Claude Sonnet 4.6 with only the compression layer changed, the run cost $89.65 against $147.30 with no compression, about 39 percent less, and solved 62 tasks against 57. The benchmark is Parsec's, not an independent test; its code and per-task results are public and can be re-run, but no independent re-run has been published, and the README says the ordering holds only for that setup. In the same benchmark, which Parsec ran without the other vendors taking part, two other compression tools cost more than no compression at all, a reminder to test any pruning tool against your own cost per task. Parsec also offers a separate service that post-trains models on a customer's traffic and routes per turn; it publishes no price, and its savings claims for that service give no workload or baseline.
Thinking and effort: the output side
On current Anthropic models thinking cannot be switched off. Claude Code's docs say Opus 5.5, Sonnet 5.5, Haiku 5.5 and the Fable models "always use extended thinking," that thinking tokens "are billed as output tokens," and that the default budget "can be tens of thousands of tokens per request." The control left is effort, set with /effort.
Once caching works, output is the largest single line in the model task, so this lever matters more than its reputation suggests. Cutting output from 1,000 to 600 tokens per request takes the filtered task from $0.79 to $0.63. The catch is quality: lower effort means less reasoning on steps that may need it. On most models, changing effort mid-session breaks the cache; Claude Code's caching page says the change keeps the cache on Opus 5.5, Sonnet 5.5 and Haiku 5.5 when you use an API key or subscription, though not on Bedrock, Google Cloud or Anthropic's apps gateway.
| Lever, applied in order | Model task cost | Change |
|---|---|---|
| No caching | $6.68 | baseline |
| Prompt caching, no idle gaps | $1.04 | −84% |
| Tool-output filtering (half the new tokens) | $0.79 | −25% |
| Lower effort (600 output tokens, not 1,000) | $0.63 | −20% |
| Caching with three idle gaps past 5 minutes | $1.60 | +53% vs $1.04 |
These are list-price calculations on stated assumptions, not measurements on real traces, and quality is assumed constant.
One lever sits outside the interactive loop. For agent work nobody waits on, such as bulk code review, evals or CI jobs, Anthropic's pricing page offers the Batch API at "a 50 percent discount on both input and output tokens."
Model routing, and why it fights the cache
Routing sends routine turns to a cheaper model and keeps hard ones on a stronger one. Anthropic's advice is Sonnet for most coding, Opus "for complex architectural decisions or multi-step reasoning," and Haiku for simple subagents. The big numbers on routing come from vendors who sell routers: Morph's guide estimates 40 to 70 percent savings on the assumption that "60-80% of coding agent requests are routine," a mix it assumes rather than measures.
What those estimates leave out is the cache. Claude Code's docs say "each model has its own cache," so switching "means the next request reads the entire conversation history with no cache hits." Morph's guide makes the same point. Shihipar gave the example of a conversation 100,000 tokens deep on Opus: switching to Haiku for an easy question "would actually be more expensive" than letting Opus answer.
List prices show when a switch pays. At 100,000 tokens of context, a request on Opus 5.5 with a warm cache costs about $0.055 in the model (3,000 new tokens, 1,000 output). The same request on Sonnet 5.5 costs $0.0275 warm but $0.27 on a cold cache. A switch from Opus to Sonnet at that depth therefore pays back only after about nine requests on Sonnet; at 50,000 tokens about five, and at 200,000 about thirteen. Switching back costs again if Opus's cache has expired. Haiku 5.5 is cheap enough at $0.10 per million input that a cold start under 100,000 tokens is cheaper than a warm Opus request, but above 100,000 tokens Haiku's price rises fivefold, and the first request costs more than Opus's before later ones save.
The practical pattern is the one Anthropic uses internally: switch models at task boundaries, or hand self-contained work to a subagent on a cheaper model with a short brief, so the main conversation's cache stays intact. Claude Code's opusplan setting is a model switch on every plan-mode toggle, so it carries this cost too. The other cost of routing is failure: a weak model on a quality-critical step can produce retries and rework that cost more than the saving, and that cost has not been measured on coding agents in public.
Measure your baseline first
The levers above have different payoffs in different setups, so start with numbers. In Claude Code, /usage shows the session's cost at list price and, from version 2.1.251, a prompt-cache line with the share of input tokens served from cache, the number of misses and, from 2.1.260, the likely cause of the last miss. On subscription plans, it also lists recommendations with the share of usage each applies to, which Anthropic notes is "not how much the change saves." For an organisation, the cache fields cache_creation_input_tokens and cache_read_input_tokens in every API response are enough to compute a hit rate; Anthropic's docs say a high read-to-creation ratio means caching is working.
Track four things: share of input from cache, misses per session and their causes, tokens per completed task, and cost per developer-day against Anthropic's $13 average.
A checklist for this week:
- Record a baseline: run
/usageafter typical sessions and note cache share, misses and cost. - Fix cache breaks: keep tools, system prompt and model fixed within a session; move timestamps and changing data to the end.
- If you take breaks longer than five minutes on an API key, set the one-hour cache lifetime.
- Add a hook that trims test and log output, trim CLAUDE.md to under 200 lines, and disable unused MCP servers.
- Use
/clearbetween unrelated tasks; save/compactfor natural breaks within long ones. - Lower effort for routine work, and send noisy or simple jobs to subagents on a cheaper model rather than switching the main session.
- Re-run
/usagea week later and compare cost per task, not just total spend.
Bottom line
If your cache share is low, fix that before anything else: it is the largest saving and costs nothing but discipline. If it is already high, the money is in new tokens and output, so filter tool output and lower effort on routine work. If you want cheaper models in the loop, put them at task boundaries or in subagents; a mid-session switch on a long context can take nine or more requests to pay back. Treat any routing or pruning savings figure without a disclosed trace set as an estimate, and judge it against your own /usage numbers.
Sources
- Anthropic, Prompt caching: https://platform.claude.com/docs/en/build-with-claude/prompt-caching
- Anthropic, Pricing: https://platform.claude.com/docs/en/about-claude/pricing
- Anthropic, Claude Platform release notes: https://platform.claude.com/docs/en/release-notes/overview
- Claude Code, Manage costs effectively: https://code.claude.com/docs/en/costs
- Claude Code, How Claude Code uses prompt caching: https://code.claude.com/docs/en/prompt-caching.md
- Thariq Shihipar, Lessons from building Claude Code: Prompt caching is everything: https://claude.dev/blog/lessons-from-building-claude-code-prompt-caching-is-everything/
- Lindenbauer et al., The Complexity Trap (JetBrains Research): https://arxiv.org/abs/2508.21433
- The Complexity Trap, full text and results: https://arxiv.org/html/2508.21433v3
- The Complexity Trap, code: https://github.com/JetBrains-Research/the-complexity-trap
- Lumer et al., Don't Break the Cache: https://arxiv.org/abs/2601.06007
- Manus, Context Engineering for AI Agents: https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus
- Morph, LLM Cost Optimization: https://www.morphllm.com/llm-cost-optimization
- Parsec for coding agents: https://parseclab.ai/parsec/
- Parsec, code-compression-bench (Parsec's own benchmark): https://github.com/daseinlabs/code-compression-bench
- Parsec vs routers: https://parseclab.ai/compare/routers/
- Parsec, Inference: https://parseclab.ai/inference/