Where the tokens of a request go and which lever acts on which part
A request to a language model is paid in three pieces: a prefix that stays the same on every call (instructions, examples, reference documents), a variable part (the user's question, the retrieved passages) and the answer. The three techniques in this article each act on a different piece. Prompt caching lowers the price of the prefix when you resend it identical before it expires. Compression reduces the tokens of the variable part. Routing changes the price per token by choosing a cheaper model for the requests that do not need the most powerful one. Each has a case in which it costs more than it saves, and a way of degrading quality without any counter showing it: the article shows both with code that was run.
A rule about numbers: provider prices change, so there are no price lists here. The listings use invented prices and fake scripted models, declared as such: no model was called, no key used. I read the cache billing rules in the official documentation (sources at the bottom, consulted on 2026-11-12) and reproduced them in the simulator. This is the second article of the series: in the first you find the map of the cost items, and in the third the comparison between APIs and your own models. For agents, where the history grows at every step, see also FinOps for agents.
Prompt caching: paying less for the prefix that repeats
The cache does not save the answer: it saves the work already done on the prefix of the request, so that the next call with the same prefix reuses it. According to Anthropic's documentation, the cache covers the full prefix in the order tools, system instructions, messages, up to the block marked with cache_control. The default lifetime is five minutes and it is renewed, at no extra cost, on every use; it is measured from the start of the request, not from the end of the answer. Writing to the cache costs more than normal input (1.25 times for the five-minute lifetime), reading it costs much less, with a multiplier that the pricing page lists model by model. Below a minimum length, which depends on the model, the request is processed without the cache and without an error.
From these rules follows a calculation worth doing before touching the code. The simulator below uses a fake clock, a prefix of 8,000 tokens, 200 variable tokens and 300 output tokens, twenty requests, with invented prices. The lines that matter are mult = READ_MULT if t <= expiry else WRITE_MULT, which decides whether the request reads or writes, and expiry = t + TTL_S, which renews the expiry on every use.
# Prompt cache simulation with a fake clock. INVENTED prices (EUR per million tokens).
# The model follows the rules read in the documentation: write at 1.25x, read at 0.10x,
# a 5-minute lifetime renewed on every use, no cache below a minimum length.
PRICE_IN, PRICE_OUT = 3.00, 15.00
WRITE_MULT, READ_MULT = 1.25, 0.10
TTL_S, MINIMUM = 300, 1024 # the real minimum depends on the model: here it is illustrative
VARIABLE, OUTPUT, REQUESTS = 200, 300, 20
def series_cost(prefix, interval_s, with_cache):
expiry, total = -1, 0.0
for i in range(REQUESTS):
t = i * interval_s
if with_cache and prefix >= MINIMUM:
mult = READ_MULT if t <= expiry else WRITE_MULT
expiry = t + TTL_S # every use renews the expiry
else:
mult = 1.0
total += (prefix * mult + VARIABLE) * PRICE_IN + OUTPUT * PRICE_OUT
return total / 1_000_000
for prefix, interval in ((8000, 60), (8000, 290), (8000, 310), (8000, 900), (800, 60)):
without = series_cost(prefix, interval, False)
with_c = series_cost(prefix, interval, True)
print(f"prefix {prefix:5d} tok, one request every {interval:3d} s: "
f"without {without:.4f} with {with_c:.4f} ratio {with_c / without:.2f}")
# Output:
# prefix 8000 tok, one request every 60 s: without 0.5820 with 0.1776 ratio 0.31
# prefix 8000 tok, one request every 290 s: without 0.5820 with 0.1776 ratio 0.31
# prefix 8000 tok, one request every 310 s: without 0.5820 with 0.7020 ratio 1.21
# prefix 8000 tok, one request every 900 s: without 0.5820 with 0.7020 ratio 1.21
# prefix 800 tok, one request every 60 s: without 0.1500 with 0.1500 ratio 1.00
With one request every 60 or every 290 seconds the cache holds and the series costs 31% of the one without the cache. With one request every 310 seconds the expiry has always passed, every call writes and the series costs 121%: the cache increases the spend by a fifth. The last row shows the other case, a prefix below the minimum: the ratio is 1.00, no effect. The practical point is that the cache pays off with continuous traffic on the same prefix, and that before enabling it you must know the typical interval between two requests. With sparse traffic there is the one-hour lifetime, at 2 times the write price according to the pricing page: do the calculation with your own frequencies.
A frequent mistake makes the cache useless without warning: putting at the beginning of the prompt something that changes (today's date, the user's name, a session identifier). The prefix is no longer identical, the cache never triggers, and you get no error. The check is in the usage fields of the response, which the second listing reads.
# How to read the cost from the usage fields, and what the request with the cache point looks like.
# The dictionaries below mimic the fields in the documentation; no network call.
import json
PRICE_IN, PRICE_OUT = 3.00, 15.00 # INVENTED, EUR per million tokens
WRITE_MULT, READ_MULT = 1.25, 0.10
request = { # shape of the request body (not sent)
"model": "<model-of-your-choice>",
"max_tokens": 300,
"system": [
{"type": "text", "text": "<long instructions, identical on every call>",
"cache_control": {"type": "ephemeral"}},
],
"messages": [{"role": "user", "content": "<question that changes every time>"}],
}
print(json.dumps(request["system"][0]["cache_control"]))
def cost(usage):
written = usage["cache_creation_input_tokens"]
read = usage["cache_read_input_tokens"]
after_point = usage["input_tokens"] # only the tokens AFTER the last cache point
total_input = written + read + after_point
eur = (written * WRITE_MULT + read * READ_MULT + after_point) * PRICE_IN
eur += usage["output_tokens"] * PRICE_OUT
return total_input, eur / 1_000_000
first = {"cache_creation_input_tokens": 8000, "cache_read_input_tokens": 0,
"input_tokens": 200, "output_tokens": 300}
second = {"cache_creation_input_tokens": 0, "cache_read_input_tokens": 8000,
"input_tokens": 200, "output_tokens": 300}
no_cache = {"cache_creation_input_tokens": 0, "cache_read_input_tokens": 0,
"input_tokens": 8200, "output_tokens": 300}
for name, usage in (("first call", first), ("second call", second), ("no cache", no_cache)):
total_input, eur = cost(usage)
print(f"{name:12s} total input {total_input} tokens, cost {eur:.5f}")
# Output:
# {"type": "ephemeral"}
# first call total input 8200 tokens, cost 0.03510
# second call total input 8200 tokens, cost 0.00750
# no cache total input 8200 tokens, cost 0.02910
The block only builds the request dictionary (the cache_control point on the last stable block of the instructions) and computes the cost from three usage fields. The documentation specifies that input_tokens counts only the tokens after the last cache point, and that the total input is the sum of cache_read_input_tokens, cache_creation_input_tokens and input_tokens: if you read only the first field, you believe you are spending very little. In the example the first call costs more than a call without the cache (0.03510 against 0.02910, writing is more expensive) and the second costs less than a quarter (0.00750). If cache_creation_input_tokens and cache_read_input_tokens are both zero, the prompt was not cached, probably because it is below the minimum. I ran no real calls: the dictionary must be adapted to your model and your SDK.
OpenAI's caching works differently: it is enabled by default on the supported models, with no code changes, with a discount on re-read tokens that the documentation gives as «up to 95%», where the percentage depends on the model. Reuse requires an identical prefix; the reported cached_tokens field is rounded down to a multiple of 128; entries typically stay active for five to ten minutes of inactivity, up to an hour, and for some models an extended retention of 24 hours exists. The comparison «Anthropic 90%, OpenAI 50%» that you read around is therefore meaningless by now: the percentages depend on the model and change. Compare the read prices of the model you use, not the labels.
Context compression: fewer tokens, but you can lose the answer
The cache does not help with the variable part: a document retrieved for that question changes with every request. This is where compression comes in. The reference work is LLMLingua (EMNLP 2023): a method that, according to the abstract, achieves up to 20 times compression with little loss of performance on four datasets (GSM8K, BBH, ShareGPT, Arxiv-March23); LLMLingua-2 recasts the problem as token classification. I did not run these tools, which require a model: the percentage refers to those benchmarks and does not transfer to your text. To see the mechanism and the risk I wrote the simplest possible version, which keeps the sentences that share the most words with the question. The token counter is the word, declared, not the one of a model.
The document, the questions and the list of stop words are Italian data of the experiment, and I left them untouched so that the figures stay the same as in the Italian edition. A gloss for the two lines that matter: the sentence «Lo scambio tra colleghi e' ammesso se entrambi firmano il modulo S2» means «Swapping between colleagues is allowed if both sign form S2», and the second question, «Posso cambiare turno con un collega?», means «Can I change shift with a colleague?».
# Sentence-level context compression: keep the k sentences sharing the most words with the question.
# This is NOT LLMLingua (that needs a model): it is the simplest version, to see the trade-off.
# The "token" here is a word: a declared counter, not the one of a real model.
# The document, the questions and the stop words are Italian DATA of the experiment, left as they are.
import re
STOP = {"il","lo","la","i","gli","le","un","una","di","da","in","con","per","a","e","che","si","va","e'","del","dei","della","delle","al","alla","posso","quanti","quante","come"}
DOCUMENT = [
"Il regolamento dei turni vale per tutto il personale di sportello.",
"Ogni turno dura otto ore e include una pausa di mezz'ora.",
"La richiesta di modifica del turno va presentata almeno cinque giorni lavorativi prima.",
"Lo scambio tra colleghi e' ammesso se entrambi firmano il modulo S2.",
"Le ferie si prenotano a gennaio per l'anno in corso.",
"In caso di malattia il certificato va inviato entro il giorno successivo.",
"I permessi brevi non superano le quattro ore.",
"Il responsabile approva le richieste entro due giorni.",
]
QUESTIONS = [
("Quanti giorni di preavviso servono per la modifica del turno?", "cinque giorni"),
("Posso cambiare turno con un collega?", "modulo S2"),
]
def words(text):
return {w for w in re.findall(r"[a-z']+", text.lower()) if w not in STOP}
def compress(sentences, question, k):
q = words(question)
order = sorted(range(len(sentences)), key=lambda i: (-len(q & words(sentences[i])), i))
kept = sorted(order[:k])
return " ".join(sentences[i] for i in kept)
original = sum(len(s.split()) for s in DOCUMENT)
for question, answer in QUESTIONS:
print(question)
for k in (8, 4, 2, 1):
text = compress(DOCUMENT, question, k)
n = len(text.split())
print(f" k={k}: {n:3d}/{original} words ({n / original:4.0%}), answer present: {answer in text}")
# Output:
# Quanti giorni di preavviso servono per la modifica del turno?
# k=8: 85/85 words (100%), answer present: True
# k=4: 43/85 words ( 51%), answer present: True
# k=2: 24/85 words ( 28%), answer present: True
# k=1: 13/85 words ( 15%), answer present: True
# Posso cambiare turno con un collega?
# k=8: 85/85 words (100%), answer present: True
# k=4: 47/85 words ( 55%), answer present: True
# k=2: 24/85 words ( 28%), answer present: False
# k=1: 11/85 words ( 13%), answer present: False
The listing sorts the sentences by overlap with the question (sorted(... key=...)), keeps the first k and puts them back in the original order. For the first question («How many days of notice are needed to change the shift?») the right sentence contains words of the question («giorni», «turno»), so it survives down to k=1, with 15% of the words. For the second the answer sits in a sentence that talks about a «swap between colleagues» and shares no words with «change shift with a colleague»: at k=2 the text drops to 28% and the answer disappears, with no errors and no warnings. A real model reads the meaning and not just the words, but the risk is the same: compression loses information where the question and the answer use different words, and what it loses is exactly what you did not know you had to keep.
Two practical consequences. First: compression has a cost, because the compressor is itself a model that runs, so it adds latency and computation, and it pays off mostly on long contexts. Second: if you compress a context that changes with every request, you cannot cache it; if instead you compress a stable document once and reuse the result, you compress and cache together. Evaluate every compression level on real questions with known answers, as in the listing, before trusting the percentage.
Routing: the small model where it is enough, and the cost of mistakes
The idea is to send easy requests to a cheap model and hard ones to a powerful one. RouteLLM (arXiv, June 2024) trains routers on preference data and reports in the abstract cost reductions of more than two times «in certain cases», without compromising quality: the sentence is conditioned on the benchmarks and the models of that work. The listing below uses no trained router: it is a hand-written rule (a long request or a trigger word) and two fake models, of which the small one answers well only the easy requests, by script. Twenty requests labeled easy or hard, with invented prices per request. The requests are Italian customer-support messages, again data of the experiment left as they are; the ones that matter are glossed in the text that follows.
# Routing between two FAKE scripted models. INVENTED per-request prices (EUR).
# The small model answers well only the easy requests; the large one answers all: that is the script.
# The requests are Italian customer-support texts: DATA of the experiment, left as they are.
SMALL, LARGE = 0.0004, 0.0100
REQUESTS = [ # (text, true difficulty)
("Ciao", "easy"), ("Qual e' l'orario di apertura?", "easy"), ("Grazie, tutto chiaro", "easy"),
("Dove trovo la fattura di marzo?", "easy"), ("Si', confermo", "easy"),
("Salve, vorrei sapere se posso modificare l'indirizzo di consegna dopo aver completato l'ordine", "easy"),
("Come reimposto la password?", "easy"), ("Il mio ordine e' arrivato?", "easy"),
("Qual e' la sede piu' vicina a Lecce?", "easy"), ("Grazie e buona giornata", "easy"),
("Analizza questa clausola e dimmi se e' vessatoria", "hard"),
("Confronta il piano annuale con quello mensile per tre utenti", "hard"),
("Perche' il pagamento e' stato rifiutato?", "hard"),
("Scrivi una query SQL che unisca ordini, clienti e resi per trimestre", "hard"),
("Spiega la differenza tra recesso e risoluzione nel mio contratto", "hard"),
("Riassumi i miei ultimi cinque ticket e proponi una priorita'", "hard"),
("Posso pagare in due rate se ho gia' una fattura scaduta?", "hard"),
("Calcola il costo totale con sconto e spedizione per l'ordine 4411", "hard"),
("Quale piano mi conviene se cambio spesso numero di utenti?", "hard"),
("Dimmi se la mia segnalazione rientra nella garanzia", "hard"),
]
TRIGGER_WORDS = ("analizza", "confronta", "scrivi", "spiega", "calcola", "riassumi")
def classify(text):
t = text.lower()
return "hard" if len(t.split()) > 12 or any(w in t for w in TRIGGER_WORDS) else "easy"
def evaluate(choose):
cost = errors = 0
for text, true in REQUESTS:
model = choose(text)
cost += LARGE if model == "large" else SMALL
errors += model == "small" and true == "hard"
return cost, errors
outcomes = {
"all large": evaluate(lambda t: "large"),
"all small": evaluate(lambda t: "small"),
"routed": evaluate(lambda t: "large" if classify(t) == "hard" else "small"),
}
base = outcomes["all large"][0]
for name, (cost, errors) in outcomes.items():
print(f"{name:10s} cost {cost:.4f} ({cost / base:5.1%} of large) wrong answers: {errors}")
for text, true in REQUESTS:
if classify(text) != true:
print(f"misclassified ({true}): {text}")
# Output:
# all large cost 0.2000 (100.0% of large) wrong answers: 0
# all small cost 0.0080 ( 4.0% of large) wrong answers: 10
# routed cost 0.0752 (37.6% of large) wrong answers: 4
# misclassified (easy): Salve, vorrei sapere se posso modificare l'indirizzo di consegna dopo aver completato l'ordine
# misclassified (hard): Perche' il pagamento e' stato rifiutato?
# misclassified (hard): Posso pagare in due rate se ho gia' una fattura scaduta?
# misclassified (hard): Quale piano mi conviene se cambio spesso numero di utenti?
# misclassified (hard): Dimmi se la mia segnalazione rientra nella garanzia
Sending everything to the small model costs 4% and produces ten wrong answers; everything to the large one costs 100% and no errors. Routing sits in between: 37.6% of the cost, but four hard requests end up at the small model, because they are short and have no trigger word («Why was the payment declined?» looks like an easy question and is not). An easy but long request, on the other hand, goes to the large model and wastes money: the opposite error costs money, not quality. The two errors do not weigh the same, and that is the point of the comparison: a router must be tuned by looking first of all at how much a wrong answer costs in your product.
Before enabling a router in production, prepare these four measurements on the same sample of real requests.
- A set of requests with a known correct answer, large enough to contain the rare cases.
- The percentage of requests that the small model gets wrong on that set, broken down by type of request.
- The percentage of requests that the router sends to the small model even though they are hard.
- The cost of a wrong answer in your case (a refund, an extra ticket, a lost user).
The first two tell you how much the small model is worth, the third how much the router is worth, the fourth turns the errors into euros so you can compare them with the saving. Without the fourth you cannot decide: a 62% saving with four errors out of twenty can be a good deal for a timetable assistant and a very bad deal for a service that handles contracts.
Combining the three levers: they do not add up and they are not independent
Each lever acts on a different part of the cost, and this explains why the combined result is not the sum. The simulator below fixes a prefix of 5,000 tokens, 800 variable tokens, 300 output tokens, 1,000 requests, and invented prices for a large and a small model. It assumes the best condition for the cache (the prefix is always read), compression that halves the variable part and 70% of the requests routed to the small model.
# How cache, compression and routing combine. INVENTED prices (EUR per million tokens).
LARGE = (3.00, 15.00) # (input, output)
SMALL = (0.25, 1.25)
PREFIX, VARIABLE, OUTPUT, N = 5000, 800, 300, 1000
READ = 0.10 # best case: the prefix is always read from the cache
def request_cost(prices, prefix_mult=1.0, variable=VARIABLE):
inp, out = prices
return (PREFIX * prefix_mult * inp + variable * inp + OUTPUT * out) / 1_000_000
def series(cache=False, compression=False, routing=False):
mult = READ if cache else 1.0
var = VARIABLE // 2 if compression else VARIABLE
large = request_cost(LARGE, mult, var)
small = request_cost(SMALL, mult, var)
small_share = 0.7 if routing else 0.0
return N * (small_share * small + (1 - small_share) * large)
base = series()
for name, kw in (("base", {}), ("cache only", {"cache": True}),
("compression only", {"compression": True}),
("routing only", {"routing": True}),
("all three", {"cache": True, "compression": True, "routing": True})):
c = series(**kw)
print(f"{name:17s} {c:7.2f} EUR per {N} requests ({1 - c / base:5.1%} less)")
# Output:
# base 21.90 EUR per 1000 requests ( 0.0% less)
# cache only 8.40 EUR per 1000 requests (61.6% less)
# compression only 20.70 EUR per 1000 requests ( 5.5% less)
# routing only 7.85 EUR per 1000 requests (64.2% less)
# all three 2.58 EUR per 1000 requests (88.2% less)
With these parameters the cache alone removes 61.6%, routing 64.2%, compression only 5.5%, and the three together 88.2%. The sum of the individual ones exceeds 100%, so they cannot be added: each lever reduces the base on which the others work. Compression weighs little because in this example the variable part is small compared with the prefix, and the prefix has already been discounted by the cache. This result belongs to my invented parameters and is not a forecast for your system; what is worth something to you is the method, that is, repeating this calculation with your own proportions between prefix, variable part and output. If your variable part is long and your prefix is short, the order of convenience reverses.
Validating the saving without fooling yourself about quality
An A/B test between the control variant and the optimized one measures cost and quality. Cost is easy: you read it from the usage fields. Quality is the weak point, because a test with few requests does not see a real degradation. The listing simulates this case with a fixed seed: the optimized variant answers correctly 86% of the time against 90% for the control, a true degradation of 4%, and counts in how many experiments a two-proportion test flags it at the 0.05 threshold.
# How reliable is an A/B test on quality? Simulation with a fixed seed.
# Illustrative true degradation: the optimized variant answers well in 86% of cases, the control in 90%.
import math, random
def p_two_proportions(s1, n1, s2, n2):
p = (s1 + s2) / (n1 + n2)
error = math.sqrt(p * (1 - p) * (1 / n1 + 1 / n2))
if error == 0:
return 1.0
z = (s1 / n1 - s2 / n2) / error
return math.erfc(abs(z) / math.sqrt(2)) # two-sided
def power(n, experiments=1000, true_control=0.90, true_optimized=0.86, alpha=0.05, seed=11):
rng = random.Random(seed)
detected = 0
for _ in range(experiments):
s1 = sum(rng.random() < true_control for _ in range(n))
s2 = sum(rng.random() < true_optimized for _ in range(n))
detected += p_two_proportions(s1, n, s2, n) < alpha
return detected / experiments
for n in (200, 1000, 3000):
print(f"{n:5d} requests per variant: the 4% degradation is flagged in {power(n):.0%} of experiments")
# Output:
# 200 requests per variant: the 4% degradation is flagged in 23% of experiments
# 1000 requests per variant: the 4% degradation is flagged in 79% of experiments
# 3000 requests per variant: the 4% degradation is flagged in 100% of experiments
With 200 requests per variant the test flags the degradation in 23% of the experiments; with a thousand in 79%; with three thousand in 100%. A «not significant» result with 200 requests does not prove that quality is unchanged: it says that the sample was not enough to see it change. That is why an A/B test that «finds no differences» must never be read as a green light. Fix first the minimum difference that matters to you and compute the sample size needed to detect it, then launch the experiment. The listing uses a z-test with a normal approximation: for small proportions or tiny samples you need exact tests.
Frequently asked questions
Does prompt caching always pay off?
No. In the simulator, with one request every 310 seconds and a five-minute expiry, the cache costs 121% of the series without the cache, because every call writes and none reads. It pays off with continuous traffic on the same prefix, above the model's minimum length.
Can I add up the savings of cache, compression and routing?
No, because each one reduces the base on which the others work. In the article's invented example the single levers are worth 61.6%, 5.5% and 64.2%, and the three together 88.2%. Repeat the calculation with the proportions between prefix, variable part and output of your own system.
Does an A/B test with no significant difference prove that quality has not changed?
No. With 200 requests per variant, in the simulation, a true degradation of 4% is flagged in 23% of the experiments. Decide in advance the minimum difference you care about and size the sample to detect it.
What you can do now
You can say which part of the request each lever acts on and compute, with your own prices, whether the cache pays off by looking at the interval between requests and the expiry. You can read from the usage fields whether the cache triggered and rebuild the real cost. You can evaluate a compression on questions with a known answer, knowing that it may lose exactly the sentence you need. You can tune a router by weighing the cost of errors and not only the saving, and you can size an A/B test so that its lack of significant differences means something. All the figures in the listings are examples: replace them with your own measurements. The next step is to decide whether to keep these models on APIs or to run them yourself, in article 3; for the other levers (batch, model choice, request grouping) there is the article on techniques per layer.
The response cache, which reuses a whole answer and not the prefix of the prompt, is a different thing: you will find it in Optimizing LLM costs in production.
Sources
- Prompt caching (Anthropic) - prefix order, five-minute lifetime renewed on every use, usage fields and the total input formula, minimum length per model; consulted on 2026-11-12
- Pricing (Anthropic) - write multipliers (1.25x at five minutes, 2x at one hour) and read multipliers, which vary by model; consulted on 2026-11-12
- Prompt caching (OpenAI) - caching enabled by default, discount on re-read tokens up to 95%, identical prefix,
cached_tokensrounded to 128, in-memory and 24-hour retention; consulted on 2026-11-12 - LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models (arXiv:2310.05736) - up to 20x compression with little loss on the four datasets of the abstract; abstract read on 2026-11-12
- LLMLingua-2: Data Distillation for Efficient and Faithful Task-Agnostic Prompt Compression (arXiv:2403.12968) - compression formulated as token classification; abstract read on 2026-11-12
- RouteLLM: Learning to Route LLMs with Preference Data (arXiv:2406.18665) - routers between a strong and a weak model, costs reduced by over two times in certain cases according to the abstract; abstract read on 2026-11-12
- Tests run locally:
python3 -Ion the six listings (standard library), each one twice with identical output; prices, volumes and fake models invented for the example

Commenti
Caricamento commenti...
Sign in to comment