Why Fewer Tokens Can Cost More

Prompt caching sets most of a coding agent's bill. See how cache reads and cache writes are priced, and why sending fewer tokens can cost more.

By Hasan Demirkiran, Jens Ernstberger.

Published 2026-11-21.

AgentLoopFigure, Aside, AttentionFigure, BillFigure, BreakEvenFigure, EditCasesFigure, IntroFigure, IntroTable, KvCacheFigure, NoCacheFigure, PrefixFigure, ServingPathFigure, Tex, TexBlock, } from "@/components/mdx/token-efficiency";

A coding agent is billed by the token. The provider counts the tokens that go into the model and the tokens that come out, and charges for each one. So the natural way to think about what an agent costs is to count its tokens, and the natural way to make it cheaper is to send fewer of them.

A whole family of tools is built on that idea. They trim shell output, compress old tool results, or tell the model to answer in fewer words. They report how many tokens they removed, usually between 20 and 90%, and the saving in dollars is assumed to follow.

Much of what shows up on a bill fits this picture. A long session costs more than a short one, for example. That is not surprising, since an agent resends its history with every request, and a longer history means more tokens each time.

What is more surprising is the following. Suppose an agent sends a long prompt, and a minute later sends exactly the same prompt again. Not one token has changed, yet the provider charges a twenty-fifth as much for the input the second time. Now suppose a tool deletes a single line near the top, and the agent sends the prompt a third time. It is shorter than before, and its input costs almost as much as it did the first time.

The usual way of thinking about cost has no room for this. We will call it the "token count" model: what an agent costs follows the number of tokens it sends. The model is not entirely wrong. Every token an agent sends is billed, and none is free. But it predicts the same price for the first two requests, which contain the same tokens, and a lower price for the third, which contains fewer. Both predictions are off by a factor of about 25.

To understand what an agent costs, we have to look at what the provider does with a prompt after it arrives.

The short answer is that the provider keeps some of its work. This is the prompt cache. The provider stores what it computed for a prompt, and sells the reuse of that work at a twentieth of the normal input price. As a result the same token is sold at more than one price, and which price applies depends on the text in front of it. But the short answer raises more questions than it settles. What exactly is stored? Why would deleting one line throw away the work done on everything after it? And if it does, when is it worth making a prompt shorter at all?

In this post we explain what the "token count" model leaves out, what a provider stores between requests and why it is priced the way it is, and how to tell in advance whether a shorter prompt will cost less. We start from the beginning, with what a cache is and the three things any cache needs in order to work. Then we ask each of those three things about a language model. The answers lead, one step at a time, from how a transformer computes to the provider's price list, and they end in a single inequality that says when a shorter prompt saves money and when it costs money.

What is a cache?

A cache is a table of answers to questions you have been asked before. When a question arrives, you look it up. If it is in the table, that is a hit, and you return the stored answer. If it is not, that is a miss. You do the work, store the result, and return it.

def cached(compute, key, table):
    if key in table:          # hit
        return table[key]
    value = compute(key)      # miss: do the work
    table[key] = value        # and remember it
    return value

That is the whole idea. Whether a particular cache is any good comes down to three questions.

  1. Is the stored answer still the right answer? The table is only sound if the key captures everything the answer depends on. If the result depends on something that is not in the key, the cache will sooner or later return an answer that is wrong. So the first job in designing a cache is to find out exactly what the computation depends on.
  2. Does the same key come back? A table of answers to questions nobody asks twice is wasted memory.
  3. Is remembering cheaper than recomputing? A stored answer occupies memory for as long as you keep it, and finding it takes time. Both have to cost less than doing the work again.

Your browser's cache is a good example. The key is the address of a file together with a version tag, so a changed file gets a new key. The same logo is requested on every page of a site. Reading from disk is far cheaper than fetching over the network. Three times yes, so the cache works.

Keep these three questions in mind. The rest of this post is these three questions, asked about a language model.

The obvious cache, and why it does not help an agent

The most direct way to cache a language model is to cache its answers. The key is the whole request and the value is the response. If the same request arrives twice, return the stored response and skip the model entirely. This is called response caching, and for a support bot that is asked the same ten questions all day, it works.

Now ask the second question. Does the same key come back? Here is what a coding agent sends while it fixes a failing test.

request 1   [instructions][task]
request 2   [instructions][task][run pytest][test log]
request 3   [instructions][task][run pytest][test log][open auth.py][file contents]

No two requests are the same. A cache keyed on the whole request never hits.

But look at how they differ. Request 3 is not a new question. It is request 2 with a little more at the end, and almost all of it has been seen before. An answer cache cannot use that, because the answer to request 2 is no help in answering request 3.

To use the overlap, we have to cache something smaller than an answer: the work the model did on the part that repeats. So we need to look at what that work is.

What does the model compute on the way to an answer?

A language model reads its input as a sequence of tokens, which are words or pieces of words. It writes its output one token at a time, and it chooses each new token by looking at all the tokens so far.

The looking is done by a mechanism called attention, and it is the only part of the model we need. The model is a stack of layers. At every layer, each token position holds a vector, and attention lets a position collect information from the positions before it. To make that possible, each position publishes two vectors at each layer. One is a key, which says what kind of information the position holds. The other is a value, which is the information. A later position forms a query, compares it with every earlier key, and takes a weighted average of the matching values:

{String.raw\text{output}_i \;=\; \sum_{j \le i} a_{ij}\, v_j \qquad\text{with}\qquad a_{ij} \;=\; \operatorname{softmax}_j\!\left(\frac{q_i \cdot k_j}{\sqrt{d}}\right)}

In words: position i scores each earlier position j by how well its query {String.rawq_i} matches the key {String.rawk_j}, turns the scores into weights that add up to one, and averages the values {String.rawv_j} with those weights.

Each cell in the figure is one layer's keys and values for one position. When the pass is done, every position has a full column of them.

Now watch what happens while the model writes. It writes one token, feeds that token back in as input, and writes the next. To produce each new token it needs the keys and values of every position so far, at every layer. If nothing is kept between steps, that means computing all of them again, every time.

But the columns it computes again are the same vectors as a moment ago, because nothing to their left has changed. Computing them again is pure waste, so every inference engine keeps them. This store is the KV cache, named for the keys and values it holds.

A request therefore has two phases. In prefill, the model processes the whole prompt in one parallel pass and fills the cache, as in Figure 1. In decode, it writes the output one token at a time, and each step adds one column and reads the rest, as in Figure 3. The split between a heavy first pass and many light steps is described well in Transformer Inference Arithmetic and measured in Splitwise.

So far this cache lives inside one request and is thrown away when the request ends. The step that matters for the bill is to keep it. If the provider holds on to the state after request 2 has finished, and request 3 begins with the same tokens, the prefill for those tokens can be skipped. Providers call this prompt caching. It is a cache of the model's work on a prompt, where the obvious cache from the last section was a cache of answers.

This gives every agent session two histories. One is the agent's: the text it sends, which grows with every step, and which the agent or a tool sitting in front of it is free to edit. The other is the provider's: the state it has computed for that text and is still keeping. A cache hit is the stretch where the two agree. Most of the time they move together, which makes them easy to confuse. The rest of this post is about how they come apart.

Four different things get called a cache around coding agents. Only the third has its own line on the bill.

  • A response cache stores finished answers. A hit skips the model.
  • The KV cache stores keys and values inside one request. Every engine has one, and it is never billed separately.
  • A prompt cache keeps that state between requests. This is the one this post is about.
  • A tool-result cache, on the agent's side, stores the output of a command or a file read. A hit skips the tool. The model still runs.

First question: what does the stored state depend on?

A cache is sound only if its key contains everything the stored value depends on. So what do the keys and values at one position depend on?

Look at the sum in the formula above. It runs over the positions up to i and stops there. A position can look back and never forward. Generation needs this, because the tokens ahead of a position do not exist yet. It also settles the caching question.

At the first layer, the vector at a position comes from its own token. At the second layer it has been mixed with the positions before it. At the third it has been mixed with positions that were themselves mixed with what came before them. By the top of the stack, the state at position j is a function of every token from the first up to j, and of nothing after j.

That tells us what the key has to be. The stored state for position j is correct for a new request exactly when that request has the same tokens in positions 1 to j. Two requests can share state as far as they agree from the start, and no further.

The smallest example makes the point. Suppose the provider holds state for the four tokens A B C D, and the next request is A X C D. The tokens C and D are the same text in both. Their stored state is not valid, because it was computed by looking back at B, and B is no longer there.

This is why providers match prefixes. It is not a shortcut in how they compare strings, and it is not a pricing decision. It is the first cache question, answered: the state depends on the whole prefix, so the prefix is the key. Anthropic's documentation asks for prompt segments that are 100 percent identical, and OpenAI's for an exact prefix match. The rule is a ceiling on what can be reused. A provider looks for a match only at certain boundaries. On OpenAI's current models, when the caller sets no breakpoints of its own, those boundaries are the end of the latest message, up to 20 earlier message endings, and the end of the opening developer messages. So reuse can stop short of the first change, and it never goes past it.

In terms of the two histories: when the agent appends to its history, all of the provider's history stays usable. When anything edits the agent's history, the provider's history is useless from that point on, even though it is still sitting in memory.

Two refinements. The first layer's keys and values depend only on the token at their own position, so after a replacement they are numerically unchanged to the right of the edit. No serving stack reuses a single layer, and every deeper layer is affected. And the prefix rule can be bent: Prompt Cache reserves position ranges for reusable modules, and CacheBlend reuses state for text at any position by computing 10 to 20% of the tokens again. These are research systems. The prompt caches that Anthropic and OpenAI sell need an exact prefix.

Second question: does the same key come back?

For most workloads the honest answer is sometimes. Two users rarely send the same long prompt. An agent is different, because of the loop we saw earlier. Each request is the previous request plus one more step, so the key from the last request comes back as the prefix of the next one, every time.

We can count how much of an agent's input is repetition. Suppose the task starts with a prompt of P tokens, each step adds b tokens, and the agent makes N requests. Request n is {String.rawP + (n-1)\,b} tokens long. Adding these up gives the total the agent submits:

{String.raw\sum_{n=1}^{N} \bigl(P + (n-1)\,b\bigr) \;=\; NP \;+\; b\,\frac{N(N-1)}{2}}

But a token is only new once, in the first request that contains it. So the number of distinct tokens is just the length of the last request, {String.rawP + (N-1)\,b}.

Take a 10,000-token prompt, 1,000 tokens per step and 20 requests. The agent submits 390,000 input tokens. Only 29,000 of them are new when they are sent. The other 92.6% are repeats.

The submitted total grows with the square of the number of requests and the distinct total grows in a straight line, so longer tasks are more lopsided still. This is what we see in practice. In the usage data Kontext collects from coding agents, 97.7% of input tokens are billed as cache reads. Manus reported the same shape for its own agent in 2025, about 100 input tokens for every output token, and called the cache hit rate its most important production metric.

So the second question has an unusually good answer. The key comes back on every request, as long as nothing has changed it.

Third question: is remembering cheaper than recomputing?

A stored answer has to be kept somewhere and found again. For this cache, both are expensive enough to shape the product.

Start with size. The cache holds a key and a value for every position, at every layer, for every attention head that has keys and values of its own. With L layers, h such heads of dimension d, and s bytes per number, the state for n tokens takes

{String.raw\text{bytes} \;=\; 2 \cdot L \cdot h \cdot d \cdot s \cdot n}

The 2 is for keys and values. For Llama 3.1 70B, an open model whose dimensions are public, L is 80, h is 8, d is 128, and each number takes 2 bytes. That is 320 KiB for every token, and about 33 GB for a 100,000-token conversation. An NVIDIA H100 has 80 GB of memory. One long agent session would take 40% of it just to be remembered.

Engineers attack every factor in that product. Grouped-query attention lets several heads share keys and values, which is why h is 8 here and not 64. Quantization stores each number in as few as 2 bits. DeepSeek's latent attention keeps one small vector per position in place of separate keys and values. All three shrink the state for the same text. None of them changes how many tokens the customer sent or is billed for, which is why a percentage from this literature cannot be set beside a percentage from a tool that shortens prompts.

Memory this scarce cannot be held forever, so cached state has a lifetime. Anthropic keeps an entry for five minutes and renews it each time it is read, and sells a one-hour lifetime at a higher write price. Claude Code asks for the one-hour lifetime on its main conversation when it runs on a Claude subscription, and for five minutes when it is billed by usage, as with an API key. OpenAI's current models default to 30 minutes, with 12 hours at a higher price. This is the second way the two histories come apart. The agent's history sits on disk and waits. The provider's history expires on a clock, whether or not anyone has changed a single token.

Then there is finding it. The state sits in the memory of one machine, and a provider runs many. A request only gets its hit if it is sent to the machine that holds its prefix, and that machine may be busy. Open-source serving stacks show how this is done. vLLM cuts the prompt into blocks of 16 tokens and identifies each block by a hash of its tokens together with everything before them, so a lookup walks the chain until the first block that is missing. SGLang keeps the prefixes in a radix tree. Mooncake, the system behind the Kimi assistant, and NVIDIA's Dynamo route each request by weighing how much of its prefix a worker holds against how long that worker's queue is, and they move state between GPU memory, host memory and disk. Prime Intellect's serving report shows these pieces combined in one production stack.

We cannot see inside Anthropic's or OpenAI's serving stacks, and nothing in this post depends on which of these designs they use. What we can see are the consequences, and both providers document them: a hit needs an exact prefix, entries expire, and, as OpenAI's documentation notes, a request can reuse a prefix only if it reaches a machine that still holds it. On models before GPT-5.6 a cache key helped steer requests to that machine. On current models OpenAI does the routing itself, and the key only keeps the cache accounting of different customers apart.

The price list is this machinery expressed in dollars.

<thead> <tr> <th>Per million tokens</th> <th>Input</th> <th>Cache write</th> <th>Cache read</th> <th>Output</th> <th>Default lifetime</th> </tr> </thead> <tbody> <tr> <td>Claude Opus 5.5</td> <td className="tef-num">$4.00</td> <td className="tef-num">$5.00</td> <td className="tef-num">$0.20</td> <td className="tef-num">$20.00</td> <td>5 minutes, renewed on each read</td> </tr> <tr> <td>GPT-6.1 Sol</td> <td className="tef-num">$2.00</td> <td className="tef-num">$2.50</td> <td className="tef-num">$0.10</td> <td className="tef-num">$10.00</td> <td>30 minutes</td> </tr> <tr> <td>GPT-6 Astra</td> <td className="tef-num">$10.00</td> <td className="tef-num">$12.50</td> <td className="tef-num">$1.00</td> <td className="tef-num">$50.00</td> <td>30 minutes</td> </tr> </tbody>

<p className="tef tef-table-note not-prose">List prices on 21 November 2026, from the <a href="https://platform.claude.com/docs/en/about-claude/pricing">Anthropic</a> and <a href="https://developers.openai.com/api/docs/pricing">OpenAI</a> pricing pages. Write prices are for the default lifetime.</p>

On the first two models, a read costs 5% of the input price and a write costs 125%. Neither provider explains its multipliers, so this is our reading: a write is a full prefill plus a claim on memory, and a read is mostly that memory being used again. Whatever the reasoning, the ratio is what matters from here on. One token written costs as much as 25 tokens read. These are the numbers behind the twentieth and the factor of 25 at the top of this post.

What does a hit buy?

Before we price an edit, we need to be exact about what a hit saves, because it is less than it sounds.

A hit skips the prefill for the matched prefix. That is all. The cached tokens are still in the context, and every output token still attends to every one of them, as Figure 3 shows. A hit also does nothing for the output itself, and output tokens are the most expensive on the list.

So every request is billed in four parts:

{String.rawC \;=\; p_{\text{in}}\,T_{\text{in}} \;+\; p_{\text{read}}\,T_{\text{read}} \;+\; p_{\text{write}}\,T_{\text{write}} \;+\; p_{\text{out}}\,T_{\text{out}}}

Each T is a number of tokens and each p is the price for that kind of token. For Opus 5.5 the four prices, in this order, stand in the ratio 20 to 1 to 25 to 100.

The ratios are why counting tokens misleads. Take 100 input tokens, of which 95 are read from the cache and 5 are written to it. The reads cost 95 units. The writes cost 125. Five percent of the tokens is 57% of the input bill.

The same arithmetic shows how a prompt can get shorter and more expensive at once. Suppose a tool removes a tenth of an agent's input tokens, and the share billed as reads falls from 93% to 90%. For every 100 tokens the agent sent before, 7 were billed outside the read bucket. Now it sends 90, and 10% of those is 9. There are fewer tokens overall, but 29% more of the expensive kind, and each of those costs 20 to 25 times as much as a read.

That shows which line of the receipt moves. It does not yet say why making a prompt shorter would cost it reads. For that we have to price an edit.

One caution about what a receipt means. OpenAI's documentation separates being billed at the read price from physically reusing stored state, and says the cache lifetime "does not guarantee that every request reuses stored KV tensors". A provider can do the work again and still charge for a read. The receipt is what a customer can observe, so the receipt is what we reason about here.

When is a shorter prompt cheaper?

We now have everything we need for the question this post is about. Suppose an agent runs a test suite and gets a 24,000-token log, and a tool can cut the log to 4,000 tokens. Is that worth doing?

It depends on when. Start with the hardest case. The log is already in the history, the cache is warm, and 36,000 tokens of conversation have piled up after it. Now the tool shortens the log.

Let D be the number of tokens removed, here 20,000. Let R be the number of tokens that survive from the cut to the end of the history, here the 4,000 left of the log plus the 36,000 after it, so 40,000. These R tokens have not changed. But by the prefix rule their stored state no longer matches, so the next request has to write them again. This is the best case. The rewrite starts at the last boundary the provider checks before the cut, and that can lie earlier than the cut itself. Let r and w be the prices of a read and a write.

If we had left the history alone, the next request would have read all R + D tokens. After the cut it writes R tokens. On every request after that, the history is D tokens shorter, which saves D reads. So after N requests the cut has changed the bill by

{String.raw\Delta C \;=\; R\,(w - r) \;-\; N D\,r \;+\; K}

where K is whatever it cost to run the tool. The cut has paid for itself when this is negative:

{String.rawN \;>\; \frac{R\,(w - r) + K}{D\,r}}

In words: the one-time cost of writing again what survived, divided by what the shorter history saves per request.

When the tool is free and a write costs 25 times a read, as on the first two models in the table, this is {String.rawN > 24\,R/D}. So the number to look at is the ratio of what survives after the cut to what was removed. The size of the cut alone says little.

With Opus 5.5 prices and a tool that costs nothing to run, the part of the history from the log onward costs $0.012 to read on the next request if we leave it alone, and $0.20 to write if we cut it. Each request after that is $0.004 cheaper. The two paths have cost the same after 48 requests. At the one-hour write price of $8, it takes 78.

Forty-eight requests is within reach for a coding agent. But all 48 have to arrive before anything else disturbs the prefix: another cut, a compaction, or five quiet minutes.

The same 20,000 tokens could have been removed at two other moments, and the arithmetic is different at each.

<thead> <tr> <th>When the log is shortened</th> <th>What happens to reuse</th> <th>What can undo the saving</th> </tr> </thead> <tbody> <tr> <td>Before the model sees it</td> <td>The earlier history stays reusable. The removed text is never written and never read.</td> <td>The agent may need a detail that was removed, and fetch it again.</td> </tr> <tr> <td>After it is part of a warm prefix</td> <td>Everything that survives after the cut is written again.</td> <td>The one-time rewrite can cost more than the shorter history saves in reads.</td> </tr> <tr> <td>After the cache has expired</td> <td>The whole history has to be written again anyway, with or without the cut.</td> <td>The tool has a cost of its own, and the agent may need what was dropped.</td> </tr> </tbody>

Same log, same 20,000 tokens removed, three results: ten cents saved, nineteen cents lost, ten cents saved. So for any tool that shortens context, the first thing to ask is when it changes the text. A compression ratio does not contain the answer.

This tradeoff is known. Anthropic's documentation for clearing old tool results says that clearing invalidates the cached prefix, and offers a setting, clear_at_least, so that each clearing removes enough to be worth it. CADOC schedules its edits in batches by the same reasoning.

What the arithmetic leaves out

The inequality holds one thing fixed that is not fixed: what the agent does next.

An agent that reads a shortened log may be missing the line it needed. Then it reruns the test, opens the file again, or thinks for longer. Each of those means more requests and more output, at a hundred times the price of a read. Factory, writing about compaction, notes that details lost this way have to be fetched again, and that the fetching can cost more than the compression saved. It can also go the other way. A log with the noise taken out can lead the agent to the fix sooner. Either way, what the agent does next decides what it sends next, and that decides what the provider can reuse. The arithmetic above describes one trip around a loop.

So for any run there are four questions, and they have to be asked together.

  1. What did the agent send? The requests themselves, and the point at which a tool changed them.
  2. What could the provider reuse? The prefix that still matched, and whether its state was still alive.
  3. What did the provider charge? The receipt, with each kind of token at its own price.
  4. What did the agent do next? The rest of the run, and whether the task was solved.

A compression ratio answers part of the first question. Only a complete run answers all four.

Three more things sit outside the arithmetic, and each one matters when reading a reported saving. Agents such as Claude Code and Codex already manage their own context, in different ways and to different degrees, so an add-on only gets what the agent leaves. A provider's cache is shared within a workspace or an organization, so two runs that begin with the same prompt can warm it for each other. In Claude Code the prompt also carries the working directory and a snapshot of git status, so this only happens between runs that start in the same directory and the same git state. And the same agent on the same task does not take the same path twice, so a single run proves little.

None of this mechanism is new. Manus described the value of a stable, append-only prefix in 2025. Don't Break the Cache measured prompt caching for agents across three providers in early 2026. Token Reduction Is Not Cost Reduction measured what three ways of shortening context do to the bill in Claude Code. Studies of context compression in other agents report real savings, but ACON leaves input caching out of its cost estimates and The Complexity Trap accounts for it only on some models.

Conclusion

An agent resends almost all of its history on every request, so providers keep the work they did on it and sell its reuse at a twentieth of the input price. The state at a position depends on every token before it. That makes the prefix the key, turns an edit into a rewrite of everything after it, and puts two prices on the same token that differ by a factor of 25. That is what happened to the three requests at the start. The first was written, the second was read, and the third was written again from the deleted line onward.

The cost of an agent is therefore not a count of tokens. It is a count of tokens at each price, and a token's price is set by the text in front of it: whether that text has changed, and how recently the provider last saw it. A tool that makes prompts shorter should be judged the same way, by where and when it edits and by the bill for a complete run.

We ran that test on five such tools inside Claude Code and Codex. The results follow in the next post.

Related reading

Back to Blog