All posts AI engineering, 13 min read

Reducing a coding agent's token usage: 3 changes, measured

3 ways to reduce token usage in coding agents, tested one at a time over 17 repos: a code graph, tool-output compression, and prompt caching behind a gateway.

I noticed the problem on an invoice. Coding agents pointed at a normal-sized repo were spending more per resolved task than I could account for, and no single prompt in them was expensive. The cost came from how the agent steps through a task.

A token is a chunk of text, about three-quarters of a word. Providers bill every token a model reads and writes, so token usage sets the bill.

For what a whole coding task costs, I later measured it from my session logs: what a coding task costs in Claude Code.

I'll go through 3 changes I made to reduce token usage and cut that bill, how much each saved, and how I measured them. They're independent, and they didn't pay off equally. None of them cut the bill by 10x, and the one I expected to win didn't.

Why an agent loop costs more than its prompts

The provider bills for tokens, and every model call has 2 sides:

  • Input tokens are everything you send: the system prompt, the conversation so far, and every tool result you paste back in.
  • Output tokens are everything the model generates: its reasoning, its tool calls, and the code it writes.

You pay for both, usually at different rates. The input side is what surprised me.

The model remembers nothing between calls

A model API is stateless: it keeps no memory of your last call. So every call has to carry the whole story again, from the system prompt to the latest tool result.

The "conversation" lives in your client, and you re-send it each time. An agent that takes 20 steps re-sends a growing history 20 times, and that explains the bill.

It works like a taxi meter that also charges for the passengers already in the car: the longer the ride and the more you carry, the more each extra block costs.

The arithmetic

Say each step adds one tool result of the same size to the history.

  1. Step 1 sends 1 result.
  2. Step 2 sends 2: the old one again, plus the new one.
  3. Step 20 sends 20.

Added up, a 20-step run pays for 1 + 2 + ... + 20 = 210 result-sized chunks of input, for 20 chunks of new information. The bill grows with the square of the run length, while the useful content grows in a straight line.1

Each bar is the input of one call (bars are not to scale). The prefix stays the same size, the newest result is one step's worth, and the history in between grows every step. Each of the 3 changes in this post targets a different layer of the bar.

Read less, shrink it, cache it, or skip the call

If the bill is (calls) x (what each call carries), there are 4 ways to shrink it:

LeverWhat it changesChange in this post
Read lessSmaller tool results enter the history1: code graph
Shrink what you readThe same results take fewer tokens2: compression
Pay less for repeatsThe fixed prefix is billed at a discount3: prompt caching
Skip the callA repeated question costs close to nothing3: shared semantic cache

None of these touch output tokens. That limit comes back later, because on some tasks output is the larger part of the bill.

What the traces showed

I read a week of agent traces token by token. 2 patterns explained the cost I couldn't account for:

  • Grep-and-read. The agent searched for a symbol, got a wall of matches, then read 4 or 5 whole files to find the one function it needed.
  • Raw tool output. Every tool result went into context unchanged: a 600-line grep -rn dump, a pretty-printed JSON response, a stack trace with 40 frames of framework noise, all of it pasted into the next prompt.

"Context" here means everything the model sees in the input of the next call. Both patterns are plumbing problems, so you can fix both in the code around the model.

The benchmark

The numbers in this post come from an internal benchmark on a code-graph-rag stack pointed at 17 backend repos. Each repo is a medium-sized service of 10,000 to 100,000 lines.

The stack makes 2 model calls per question:

  • a Cypher generator that turns a natural-language question into a graph query, running on Haiku 4.5 (Cypher is the query language of graph databases such as Memgraph and Neo4j)
  • an orchestrator that plans and answers, running on Sonnet 4.6

I instrumented the HTTP client to capture the exact request and response bodies against the Anthropic API. So every cost figure below comes from a measured usage object on the wire, the token counts the API returns with each response. Where a number is illustrative instead of measured, I say so.

The example repo

For worked examples I use a small imaginary service, widget-store:

  • an HTTP API
  • a few route handlers
  • a service layer
  • a data-access layer
  • tests

A typical agent task there is "add a discount field to orders and thread it through to the invoice." That task crosses layers. The agent has to find where orders are defined, where invoices are built, and what touches both.

Grep-and-read is bad at this kind of cross-file discovery, and it's the kind of question the real stack answers across the 17 repos.

Where the tokens go

Before changing anything, split each task's bill into 2 buckets:

  • Input you send the model: the system prompt, the running history, and every tool result.
  • Output the model generates: its reasoning, its tool calls, and the code it writes.

The split tells you what can help. If a task's cost is mostly input you control, retrieval and compression have room to work. If it's mostly output the model writes, smarter reading won't help much, because you can't compress tokens the model hasn't produced yet.

I underestimated how much of the bill is output on tight tasks. With a clear target file, the agent reads a little and writes a lot, and the input-side changes barely move the bill. That's why the code graph was a smaller win than I expected.

per-task token bill
├── input (you control this)
│   ├── system + instructions
│   ├── conversation history
│   └── tool results  ← grep dumps, JSON, logs live here
└── output (model controls this)
    ├── reasoning
    ├── tool calls
    └── generated code

3 ways to reduce token usage, at a glance

ChangeWhat it doesWhere it helpedWhere it did not
1. Code graphAnswers "where is X used" from a prebuilt map of the codeDeep cross-file discoveryShallow and write-heavy tasks
2. CompressionShrinks tool output before it re-enters contextEvery tool-heavy taskNever use it on source code
3. Gateway + cachingDiscounts the repeated prefix, reuses answersRepeated, clustered useSingle-shot calls, prefixes below the minimum

Change 1: a code graph for structural retrieval

A code graph lets the agent ask about structure instead of reading files to discover it.

You build a graph of the codebase once:

  • Nodes are files, classes and functions.
  • Edges are calls, imports and definitions.

The agent queries the graph and gets back the 3 functions it needs instead of the 5 files that contain them.

You can build this with code-graph-rag, which parses a repo into a queryable graph, backed by a graph store such as Memgraph. The agent's "find where orders connect to invoices" becomes a graph traversal instead of a grep plus 4 file reads.

The discovery phase of the widget-store discount task, both ways. The token counts illustrate this one task only.

On the widget-store discount task, the graph helped. Without it, the agent pulled 4 files into context to trace the path from order to invoice. With it, the agent pulled the 3 relevant functions. As an illustration, that takes the discovery phase from about 9,000 input tokens to about 2,500.

Results across the task set

Across a full task set, the result was uneven:

Task shapeResultWhy
Deep cross-file discoveryThe graph wonFewer files read, less context, lower input cost
Shallow, obvious target fileBreak-evenThe query overhead canceled out the reading it saved
Write-heavy, output dominatesSlightly worseI paid to build and query a graph whose savings landed on the smaller part of the bill

So the code graph helps on discovery and does little elsewhere. If a team's agents mainly make small, targeted edits, the graph can cost more than it saves. I'd expected a discount on every task, and only got one on some.

Change 2: compress tool output before it re-enters context

I almost skipped this one. It gave the steadiest savings.

Why tool output compresses well

Tool output is repetitive and machine-shaped:

  • Grep results repeat paths and line numbers.
  • JSON repeats keys.
  • Logs repeat timestamps and framework frames.

A prompt compressor like LLMLingua-2 is built for this kind of input. It's a small model that scores each token by how much information it carries for the main model, then drops the low scorers. On tool output, it compresses without changing what the agent does next.

Why source code must not be compressed

I settled on a rule: compress tool output, and leave source code untouched.

In source code, removing one token can change what the code does. Nothing raises an error. The model gets a slightly wrong picture and writes slightly wrong code.

So the compressor sits only where tool results re-enter context, and source files pass through as they are.

The compressor sits at one boundary, where tool results re-enter context. The router reads the kind tag, so a source file can never reach the compressor by accident.

In code, the boundary is one routing function:

# illustrative: compress only at the tool-output boundary
def feed_to_context(payload, kind):
    if kind in ("grep", "json", "logs", "shell_output"):
        return compress(payload, target_ratio=0.45)  # LLMLingua-2
    if kind == "source":
        return payload  # never touch source code
    return payload

What it saved

On tool-heavy tasks, this cut total input tokens by about 40 percent, and the quality gate still passed. A quality gate is the fixed bar every run has to clear for its cost to count; I describe it in the measurement section below.

How sure I am: the caching figures in change 3 are measured on the wire. This compression figure comes from lighter runs on the same stack, outside the full instrumented benchmark, so I treat it as directional.

Unlike the graph, compression doesn't depend on what kind of question it is, because tool output is verbose whatever you ask.

The bug that set the rule

The boundary has to stay strict. The first time sloppy wiring let the compressor see a source file, the agent confidently edited a function that no longer matched what was on disk. I now tag every payload by kind and route on the tag.

Change 3: a gateway with virtual keys, a spend ledger, prompt caching and a shared cache

The first 2 changes make each call cheaper, and the third removes some calls entirely. It's also the change I have the most measured data on, because I benchmarked it end to end.

What a gateway is for

Without a gateway:

  • provider keys sit on each engineer's machine
  • nobody has a shared view of spend
  • each person's agent answers the same questions from scratch

A gateway is a proxy that every agent calls instead of the provider. Putting the keys behind one like LiteLLM gives you 4 things:

  • Per-developer virtual keys. A virtual key is a gateway-issued key that maps to the real provider key. You can rotate, scope and rate-limit one person's key without touching a provider dashboard.
  • A spend ledger. Every call is attributed, so you can see cost by repo, by task type and by person, and set budgets on those. The ledger is also what made the per-change measurements below possible.
  • Prompt caching. You mark the stable prefix of a request, the system prompt and tool definitions, with cache_control. On a later call within the cache window, the provider charges a reduced rate to re-read that prefix instead of the full price. This is the one I measured most precisely, and it has a catch I'll get to below.
  • A shared semantic cache. When one engineer's agent asks "how does invoice rounding work", the answer is cached by meaning. The next engineer who asks a similar question gets a cheap hit instead of a fresh model call. A tool like GPTCache does the embedding and lookup.
flowchart LR
    D1["dev A agent"] --> G["gateway<br/>(virtual keys + ledger)"]
    D2["dev B agent"] --> G
    G --> C{"semantic<br/>cache hit?"}
    C -->|yes, same repo| H["cached answer<br/>~0 tokens"]
    C -->|no| M["model call"]
    M --> C2["write to cache<br/>(scoped to repo + commit)"]

How prompt caching works

The provider stores the processed form of your prefix for a short window. Within that window, a call that starts with the same prefix is billed in 3 ways:

  1. Cache write, the first call: the prefix costs 1.25x the input rate.
  2. Cache read, each later call in the window: the prefix costs a tenth of the input rate.
  3. No cache, if the prefix is below the provider's minimum cacheable length: full price, and no error.

You pay a premium once to write the cache and win it back on every reuse.

What prompt caching returned, per model

I turned on Anthropic prompt caching across the 2-model stack and measured the per-call usage on the wire. The result depended on the model.

Haiku 4.5 (Cypher generator): zero reduction.

  • Its system prompt is about 1,750 tokens, below Haiku's minimum cacheable prefix, so the provider didn't cache it.
  • The marker was on the wire, but cache_creation_input_tokens came back zero on every call.
  • At about $0.0023 per Cypher call, that model was already cheap, so the miss cost little. I wouldn't have noticed it without reading the usage object.

Sonnet 4.6 (orchestrator): caching paid off. Its system prompt plus tool definitions come to about 3,400 tokens, above the threshold, so it cached:

Orchestrator callInput billingTotal costvs uncached
Uncached3,400 tok at full rate$0.0132reference
First call (cache write)3,400 tok at 1.25x$0.0158+20% (the write premium)
Warm call (cache read)3,400 tok at 0.10x$0.0042about 68% cheaper
Top: the write costs more, every warm read costs much less, so caching pays only when reads follow the write. Bottom: a prefix below the model's minimum carries the cache marker and caches nothing, with no error.

The first call costs more, because a cache write is billed at 1.25x the input rate. Each later call within the window reads the cached prefix at a tenth of the input rate and costs about 68% less than an uncached call.2

Whether the bet pays depends on the session

It comes down to how clustered the usage is. Here a session is one developer asking a series of questions in close succession, each triggering one Cypher call and one orchestrator call:

Session shapeNet cost changeWhy
Single question, cold cache+17% worseYou pay the write premium and never read it back
5 questions (4 within the window)about 43% cheaper4 warm orchestrator reads outweigh 1 write
20 questions, heavy useabout 54% cheaperThe write is spread across 19 warm reads

Projected onto a month of usage, the saving rises with how much people use it, because caching beats the baseline only when there are reads within the window:

  • about 26% for one light-use developer
  • about 46% for a team of 3 asking regular questions
  • close to 50% for a team of 8

Before measuring, I'd estimated "35 to 50% across the board." The floor was lower than I guessed, and the upper end holds only with repeated use, and only on the model whose prefix clears the threshold.

2 findings I would have got wrong without reading the wire

  • Below the prefix threshold, caching does nothing and reports no error. Haiku's minimum cacheable prefix is around 2,048 tokens; Sonnet's is lower. A prompt below the line carries the marker on the wire and caches zero tokens. Check cache_creation_input_tokens in the response.
  • A single-shot call costs more with caching on. The 1.25x write premium with no read afterwards makes a one-question session 17% more expensive. Caching pays off on repeated use, so its value depends on how your sessions look.

2 rules for the shared cache

A semantic cache matches questions by meaning, using embeddings (vectors that place similar text close together), so "how is invoice rounding done" can hit an entry stored for "how does invoice rounding work". 2 problems with the shared cache only showed up in production:

  • Invalidate on code change. A cached answer about invoice rounding is correct until someone changes the rounding. If the cache outlives the code it described, it returns stale answers. I key cache entries to the repo state, so a relevant commit invalidates the entries that depended on it. A stale hit costs nothing and returns a wrong answer, so it does more harm than a miss.
  • Scope entries per repo. Without scoping, an answer derived from one project can come back as a hit in another, and the 2 repos don't share the same rules. I scope every entry to its repo so answers can't cross projects.

With both rules in place, the shared cache had the highest ceiling of the 3 changes, because a hit costs close to nothing. Its value depends on repetition:

  • On a team asking overlapping questions about a shared codebase, the hit rate rose and the savings added up.
  • A solo developer on a fast-changing repo would see entries invalidated before anyone reused them.
Interactive: combine the 3 changes
2,400,000 tokens / month (illustrative) baseline
Code-graph retrieval Pull the relevant functions from the call graph instead of whole files. The saving depends on the question. ~ -28%
Tool-output compression Compress logs, diffs and command output before they re-enter context. The steadiest saving. ~ -40%
Prompt caching and shared cache The provider bills a cached prefix at a tenth of the input rate, and the shared cache answers repeated questions. Both pay off with repeated use. ~ -54%

Each saving is the figure from the results table below, applied to an illustrative baseline for the example repo. Your savings depend on your codebase, your questions, and how often they repeat.

Measuring each change on its own

If you ship all 3 changes in a weekend and compare next month's invoice, the bill goes down and you can't tell which change did it.

  • The compressor might be carrying the whole saving while the code graph costs money on every small edit.
  • The cache hit rate might be near zero.

The method

So I benchmarked each change on its own:

  1. Fix a task set. A frozen list of representative tasks against the widget-store repo, run the same way every time.
  2. Fix a quality gate. Every run has to pass the same bar: tests green, and the diff does what the task asked. Each of these changes can cut cost by cutting quality, so a change that saves tokens by producing worse code doesn't count as a saving.
  3. Change one thing at a time. Baseline, then baseline plus graph, then baseline plus compression, then baseline plus cache. Never 2 at once.
  4. Attribute the difference. Whatever the bill moved when you added one change, and only that change, is what that change saved. The spend ledger from change 3 makes this measurable per run.

The results

RunToken ΔQuality gateVerdictBasis
baseline--passreference--
+ graph-28% on discoverypasswins on deep discovery onlyillustrative
+ compression-40% totalpassreliable, broaddirectional
+ prompt cache-54% per 20q sessionpassrepetition-bound, per-enginemeasured on wire
+ semantic cachevariespassbest ceiling, repetition-boundillustrative

In words:

  • The code graph, which I expected to win, helped only on deep discovery.
  • Tool-output compression, which I almost skipped, was the dependable saving.
  • Prompt caching, which I measured to the cent, saved about 68% per warm call on the model whose prefix cleared the threshold, did nothing on the model below it, and cost 17% more on single-shot use.

What I would set up first on a new team

  1. Gateway, virtual keys and spend ledger. Before any cache pays off, you need attribution and a budget per developer. AI spend management covers the per-initiative version. You can't measure the rest without a per-call usage number, and reading that number is what showed me the Haiku cache did nothing.
  2. Prompt caching, with a threshold check. Turn it on for the model whose system-plus-tools prefix clears the provider's cacheable minimum, and confirm cache_creation_input_tokens is non-zero before you trust it. Expect it to help repeated sessions and to cost more on single-shot calls.
  3. Compression at the same time. The savings don't depend on the question, and the only rule is keeping source code away from the compressor.
  4. Semantic cache once there is repetition. Turn it on when more than one person asks overlapping questions about the same codebase, and turn on invalidation and per-repo scoping the same day.
  5. The code graph last, and only for discovery-heavy work. If the agents mainly do large cross-file investigations, build it. If they mainly make small targeted edits, skip it and the infrastructure that comes with it.

Key takeaways

  • You pay for input on every call, and input grows with the history, so a run with no expensive prompt can still produce a large bill.
  • Split each task's cost into input you control and output the model generates. These changes only work on the input side, so write-heavy tasks limit how much they help.
  • A code graph wins on deep cross-file discovery and is break-even or worse on shallow or write-heavy tasks.
  • Compress tool output and leave source code alone. Tool output is repetitive and machine-shaped. In source code, dropping one token can change the meaning without any error.
  • Prompt caching depends on the model and the session. Check cache_creation_input_tokens on the wire.
    • Zero saving on the Haiku engine, whose prefix sat below the threshold.
    • About 68% cheaper on warm Sonnet orchestrator calls.
    • 17% more expensive on a single-shot session.
  • A shared semantic cache has the highest ceiling, once it invalidates on code change and is scoped per repo. A stale hit costs nothing and returns a wrong answer.
  • Benchmark each change alone, against the same task set, behind a fixed quality gate, one change at a time. If you measure them together, you can't tell which one paid for itself.
  • On a new team: gateway, keys and ledger first, prompt caching with a threshold check next, compression alongside, a semantic cache once there is repetition, and a code graph last, only if the work is discovery-heavy.

Footnotes

  1. This assumes every step adds a result of the same size and nothing is trimmed. Runs vary in practice, and some harnesses summarize or drop old turns, but the shape holds: the early context is paid for again on every later call. ↩

  2. The 68% is the per-read saving that follows from the current Anthropic cache-read and cache-write multipliers at this stack's prefix size. The multipliers and thresholds change, so read the usage object on your stack instead of carrying this number forward. ↩

Common questions

Does a code graph always cut token cost?↓

No. In my runs it won on deep cross-file discovery, where brute-force reading would have pulled 5 or 6 files into context. On shallow questions, or any task where the model's output dominates the bill, the graph was break-even or slightly worse once you count the retrieval overhead.

Why compress tool output but not source code?↓

Tool output like grep dumps, JSON and logs is repetitive and machine-shaped, so a compressor such as LLMLingua-2 can drop a large share of tokens without losing what the model needs. In source code, removing one token can change what the code does, and the model then works from a wrong picture without any error. I leave source untouched and compress only where tool output re-enters context.

Is a shared semantic cache safe across projects?↓

Only if you scope it. An answer derived from one repo can be wrong or leak information in another, so I key the cache per repo and invalidate entries when the code changes. Without those 2 rules a cache hit can return a confident wrong answer, which costs more than the tokens it saved.

Why does an agent loop cost so much when no single prompt is expensive?↓

You pay for input tokens on every call, and the conversation history is part of the input. A 20-step task re-sends a growing history 20 times, like a taxi meter that also charges for the passengers already in the car. The bill comes from that accumulation, so look at cost across the whole run instead of per prompt.

How do I know which change saved money?↓

Benchmark each change on its own against the same task set with a fixed quality gate, change one thing at a time, and attribute the difference to that change alone. If you ship all 3 together and measure once, you cannot tell which one paid for itself, and you keep paying for the ones that did not.

How do you reduce a coding agent's token usage?↓

Measure 1 change at a time behind a fixed quality gate. In my tests, compressing tool output was the steadiest saver, prompt caching cut warm Sonnet orchestrator calls by about 68% and did nothing on a Haiku prompt below the cacheable minimum, and a code graph helped only on deep cross-file questions.

Keep reading

All posts Get in touch

Get the next study by email

I publish a data study when the numbers are in, with its method and raw data. One email per study.

Send me

I send an email when something new goes up. Unsubscribe with a click. Privacy.