Self-hosting, quantization and caching: three levers on three different layers, and the threshold that decides whether the cache saves you money
If you look up how to reduce the spend on a language model in production, you always find the same three answers: move it to a server of your own, compress its weights, put a cache in front of it. They are three real levers, but they act on different layers and answer three different questions, and confusing them leads to two frequent mistakes: expecting from a cache a saving that your traffic cannot give, or believing that a model on your own server has "zero cost per token". This article gives you a criterion for working out which lever touches which spend, and then goes deeper into the only one the series has not yet covered: the cache that compares the meaning of questions, with a listing in which the similarity threshold is the parameter that makes or loses money. Numbers and questions are invented and declared as such, and no model is called.
Three questions, three layers
Before choosing a lever, ask yourself what you are trying to change. Each of the three answers a single question.
- Where the model runs: on a pay-as-you-go API or on a server of your own. It changes the structure of the cost, from variable to fixed.
- How much memory and how much precision the weights need: quantization. It changes which hardware is enough.
- How many requests must reach the model: the cache. It changes the volume, not the price.
The three levers are therefore independent in mechanism and dependent in effect: a cache reduces the volume your server then has to handle, and a quantized model lowers that server's fixed cost. That is why they do not add up: each acts on what the others have left, as explained in the article on techniques by layer. The choice between your own server and an API depends on the shape of the traffic, and the break-even threshold is computed in the article comparing the two: here it is enough to know that "zero cost per token" is an accounting error, because the server is paid for even when it is not working, and that the cost per token is a fixed cost divided by the tokens actually served.
Two facts from the documentation, so as not to take for granted what is not. On an Ollama server the parallelism per model is, by default, 1, the queue accepts 512 requests before rejecting more, and the memory required grows with parallelism times context length: a server of your own does not serve more users in parallel without more memory. And quantization, according to the llama.cpp documentation, reduces the size of the model and can speed up inference, but it can introduce a loss of accuracy measured in perplexity or in Kullback-Leibler divergence: the loss exists, and it must be measured on your own task before accepting it, as in the non-inferiority test already seen in the series. The rest of this article is about the cache.
Exact, normalized, semantic cache: what each one finds
The piece on caching, compression and routing covers the providers' prompt cache, which reuses an identical prefix. The response cache is something else: it recognizes a question already seen and returns the response already generated, without calling the model. Three levels of recognition, from the most rigid to the widest: identical string, normalized string (lowercase, no punctuation), similarity of meaning. Redis, in the documentation of its LangCache service, describes the third form as a check on whether a semantically similar prompt has already been answered, with configurable similarity thresholds, TTL and eviction policies.
The listing that follows compares the three levels on 18 invented questions to an imaginary support assistant, divided into five intents plus two unrelated questions: the first sentence of each of the three intents already in the cache serves as the cache entry, and the other 13 (11 rephrasings and 2 unrelated) are the test. The semantic comparison uses a crude vector: the frequencies of character trigrams and the cosine. It is not an embedding model and does not replace one: it is there to see the behaviour of a threshold on data you can read. The cache contains only three intents already seen, and the test includes questions for which the right answer is "no hit": that is where a semantic cache goes wrong, because a question that is close in text is not always close in meaning. The questions are kept in Italian, as in the original example, because the character-trigram vector depends on the language and translating them would change every similarity in the output; where the text discusses a question, it carries an English gloss.
import math
import re
from collections import Counter
# INVENTED questions for an imaginary support assistant. Each intent has one cached answer
# (the first sentence) and other phrasings that arrive later.
INTENTI = {
"reset-password": [
"Come reimposto la password?",
"Come posso reimpostare la mia password",
"come si fa a reimpostare la password dell'account?",
"Ho dimenticato la password, come la reimposto?",
],
"cancel-subscription": [
"Come annullo l'abbonamento?",
"Voglio annullare il mio abbonamento, come faccio?",
"Come si annulla un abbonamento attivo?",
],
"download-invoice": [
"Dove scarico la fattura?",
"Come posso scaricare le fatture del mese scorso?",
"Dove trovo la fattura da scaricare?",
],
"create-account": [
"Come creo un account?",
"Come posso creare un nuovo account?",
"Come si crea un account aziendale?",
],
"delete-account": [
"Come cancello l'account?",
"Come posso cancellare il mio account?",
"Come si cancella un account aziendale?",
],
}
# Questions for which no cached answer is suitable.
ESTRANEE = [
"Quali sono gli orari del supporto telefonico?",
"Posso pagare con un bonifico?",
]
def normalizza(testo):
testo = re.sub(r"[^\w\s]", "", testo.lower())
return " ".join(testo.split())
in_cache_esatta = {frasi[0] for frasi in INTENTI.values()}
in_cache_norm = {normalizza(frasi[0]) for frasi in INTENTI.values()}
# Identical repetition of the same sentence, and a variant differing only in case and punctuation.
prove = [("identical", "Come reimposto la password?"),
("case and punctuation", "come reimposto la PASSWORD"),
("rephrased", "Come posso reimpostare la mia password")]
for etichetta, testo in prove:
esatta = testo in in_cache_esatta
norm = normalizza(testo) in in_cache_norm
print(f"{etichetta:<22} exact cache: {'hit' if esatta else 'miss'} normalized: {'hit' if norm else 'miss'}")
# On all the phrasings after the first:
successive = [t for frasi in INTENTI.values() for t in frasi[1:]]
hit = sum(normalizza(t) in in_cache_norm for t in successive)
print(f"later phrasings: {len(successive)}, hits with normalization alone: {hit}")
# Semantic cache with a crude "embedding": character-trigram frequencies, cosine similarity.
# It is not a real model: it is there to see how a THRESHOLD behaves on declared data.
def vettore(testo):
t = " " + re.sub(r"[^\w\s]", "", testo.lower()) + " "
return Counter(t[i:i + 3] for i in range(len(t) - 2))
def coseno(a, b):
num = sum(a[k] * b[k] for k in a if k in b)
den = math.sqrt(sum(v * v for v in a.values())) * math.sqrt(sum(v * v for v in b.values()))
return num / den if den else 0.0
# The cache contains only the intents already seen; for the others the right answer is "no hit".
IN_CACHE = ("reset-password", "cancel-subscription", "create-account")
cache = [(i, vettore(INTENTI[i][0])) for i in IN_CACHE]
prove = [(i if i in IN_CACHE else None, t) for i, frasi in INTENTI.items() for t in frasi[1:]]
prove += [(None, t) for t in ESTRANEE]
def migliore(testo):
v = vettore(testo)
return max(((coseno(v, vc), intento) for intento, vc in cache))
print(f"questions: {len(prove)}, of which {sum(1 for v, _ in prove if v is None)} with no answer in cache")
print("threshold correct hits wrong hits missed hits correct misses")
for soglia in (0.3, 0.4, 0.5, 0.6, 0.7):
giusti = sbagliati = persi = corretti = 0
for vero, testo in prove:
sim, trovato = migliore(testo)
if sim >= soglia:
if trovato == vero:
giusti += 1
else:
sbagliati += 1 # answer of another intent, or answer to a question with no answer
elif vero is None:
corretti += 1
else:
persi += 1 # the right answer was there, but the threshold discarded it
print(f"{soglia:>9} {giusti:>12} {sbagliati:>10} {persi:>11} {corretti:>14}")
# The questions with no answer in cache, with the similarity of the nearest neighbour.
for vero, testo in prove:
if vero is None:
sim, trovato = migliore(testo)
print(f"{sim:.2f} '{testo}' -> nearest: {trovato}")
# Output:
# identical exact cache: hit normalized: hit
# case and punctuation exact cache: miss normalized: hit
# rephrased exact cache: miss normalized: miss
# later phrasings: 11, hits with normalization alone: 0
# questions: 13, of which 6 with no answer in cache
# threshold correct hits wrong hits missed hits correct misses
# 0.3 7 2 0 4
# 0.4 7 2 0 4
# 0.5 7 1 0 5
# 0.6 5 0 2 6
# 0.7 2 0 5 6
# 0.13 'Come posso scaricare le fatture del mese scorso?' -> nearest: reset-password
# 0.10 'Dove trovo la fattura da scaricare?' -> nearest: reset-password
# 0.41 'Come posso cancellare il mio account?' -> nearest: create-account
# 0.51 'Come si cancella un account aziendale?' -> nearest: create-account
# 0.03 'Quali sono gli orari del supporto telefonico?' -> nearest: cancel-subscription
# 0.17 'Posso pagare con un bonifico?' -> nearest: create-account
Normalization recovers the variant that differs only in case and punctuation, but out of 11 true rephrasings it recovers 0: it helps little when people write in different ways. Similarity does better, and the table shows the trade-off that holds everything else up. At 0.3 and 0.4 the cache recovers 7 correct hits but also 2 wrong ones; at 0.5 the wrong ones drop to 1; at 0.6 they are 0 but 2 correct hits are lost; at 0.7 five are lost. The wrong hit is the one to look at: "Come si cancella un account aziendale?" ("How do you delete a business account?") is at 0.51 from the answer on how to create an account ("Come creo un account?", "How do I create an account?"). It shares almost all its words and wants the opposite operation. With a threshold of 0.5 that question receives the wrong answer, and nobody notices until someone complains.
For reference, the six questions with no answer in the cache, in the order of the output, are: how to download last month's invoices; where to find the invoice to download; how to delete my account; how to delete a business account; what the phone support opening hours are; and whether I can pay by bank transfer.
What a threshold is worth: right hits pay, wrong hits cost more
A right hit saves one call to the model. A wrong hit saves it just the same, but delivers an incorrect answer, and its cost is not in the price list: it is the time of whoever corrects, the ticket, the lost trust. This is the same reasoning as the cost of an error in the article on the trade-off between cost and quality. A third term must be added that nobody remembers: the cache check, that is, computing the embedding and doing the search, costs on every request, even when there is no hit.
# Net value of a threshold. The counts come from the output of the previous listing
# (13 questions); the costs are INVENTED.
COSTO_CHIAMATA = 0.004 # euro for an answer generated by the model
COSTO_LOOKUP = 0.0002 # euro to compute the embedding and search the cache, on EVERY request
DOMANDE = 13
# threshold: (correct hits, wrong hits)
CONTEGGI = {0.3: (7, 2), 0.4: (7, 2), 0.5: (7, 1), 0.6: (5, 0), 0.7: (2, 0)}
def netto_per_1000(giusti, sbagliati, costo_errore):
chiamate_evitate = giusti + sbagliati
euro = chiamate_evitate * COSTO_CHIAMATA - sbagliati * costo_errore - DOMANDE * COSTO_LOOKUP
return euro * 1000 / DOMANDE
for costo_errore in (0.01, 0.05):
print(f"cost of a wrong hit: {costo_errore:.2f} euro")
for soglia, (g, s) in CONTEGGI.items():
print(f" threshold {soglia}: net {netto_per_1000(g, s, costo_errore):>7.1f} euro per 1000 requests")
# Break-even of the error cost at threshold 0.5, and minimum hit share to repay the lookup.
g, s = CONTEGGI[0.5]
pareggio = ((g + s) * COSTO_CHIAMATA - DOMANDE * COSTO_LOOKUP) / s
print(f"threshold 0.5: the cache stops paying off above {pareggio:.4f} euro per wrong hit")
print(f"minimum hit share to repay the lookup: {COSTO_LOOKUP / COSTO_CHIAMATA:.1%}")
# Output:
# cost of a wrong hit: 0.01 euro
# threshold 0.3: net 1.0 euro per 1000 requests
# threshold 0.4: net 1.0 euro per 1000 requests
# threshold 0.5: net 1.5 euro per 1000 requests
# threshold 0.6: net 1.3 euro per 1000 requests
# threshold 0.7: net 0.4 euro per 1000 requests
# cost of a wrong hit: 0.05 euro
# threshold 0.3: net -5.1 euro per 1000 requests
# threshold 0.4: net -5.1 euro per 1000 requests
# threshold 0.5: net -1.6 euro per 1000 requests
# threshold 0.6: net 1.3 euro per 1000 requests
# threshold 0.7: net 0.4 euro per 1000 requests
# threshold 0.5: the cache stops paying off above 0.0294 euro per wrong hit
# minimum hit share to repay the lookup: 5.0%
With an error of 1 cent the best threshold is 0.5, with a gain of 1.5 euro per thousand requests: little, because in this example a call costs 0.4 cents. With an error of 5 cents the low thresholds go into loss (minus 5.1 euro per thousand) and the best is 0.6. The break-even at 0.5 is at about 2.9 cents per wrong hit: above that error cost the cache does not pay off at that threshold. Then there is the minimum hit share, 5%: if your traffic repeats fewer than 5% of the questions, the cache check costs more than it saves. The gain depends on the cost of the call you avoid: with a model much more expensive than the 0.4 cents of this example, the same behaviour yields much more, and the cost of the error becomes the dominant factor. The conclusion that holds even with different numbers is the method: calibrate the threshold on your own data, with a declared error cost, not with the default value.
A cache that cannot invalidate itself serves old answers
A cache exists to give the same answer, and the same answer stops being right when the content changes. The simplest remedy is time-based expiry (TTL), but a seven-day expiry means up to seven days of stale answers. The more precise remedy is to put in the key the version of the content the answer depends on: when the version changes, the key changes and the old answer is no longer found. The listing compares the two strategies over seven days, with a change of procedure on the third.
# Time-based expiry versus a key with the content version. INVENTED scenario:
# 7 days, 10 requests a day per intent, and on day 3 the "cancel-subscription" procedure changes.
GIORNI = 7
RICHIESTE_AL_GIORNO = 10
TTL_GIORNI = 7
GIORNO_MODIFICA = 3
INTENTI = ("reset-password", "cancel-subscription", "download-invoice")
def versione_corrente(intento, giorno):
return 2 if intento == "cancel-subscription" and giorno >= GIORNO_MODIFICA else 1
def simula(chiave_con_versione):
cache = {} # key -> (version it was generated with, day)
chiamate = vecchie = 0
for giorno in range(1, GIORNI + 1):
for intento in INTENTI:
v = versione_corrente(intento, giorno)
chiave = (intento, v) if chiave_con_versione else (intento,)
for _ in range(RICHIESTE_AL_GIORNO):
voce = cache.get(chiave)
if voce is None or giorno - voce[1] >= TTL_GIORNI:
cache[chiave] = (v, giorno) # generated by the model
chiamate += 1
elif voce[0] != v:
vecchie += 1 # answer of an outdated version
return chiamate, vecchie
for etichetta, flag in (("TTL only", False), ("key with version", True)):
chiamate, vecchie = simula(flag)
print(f"{etichetta:<20} model calls: {chiamate:>2} stale answers served: {vecchie}")
# Output:
# TTL only model calls: 3 stale answers served: 50
# key with version model calls: 4 stale answers served: 0
With time-based expiry alone, 50 stale answers are served (5 days times 10 requests), with 3 calls to the model. With the versioned key, no stale answer and only one more call (4 in all): the price of correctness is one regeneration for each version change. The limit is that someone has to declare the version: if the answer depends on a document, the version is the document's fingerprint; if it depends on personal data, the key must also include the user, otherwise a shared cache can hand one person the answer built with another person's data.
When the cache does not pay off
The response cache works where questions repeat and answers do not change from person to person: support, documentation, frequently asked questions. It does not pay off where every request carries its own context (the user's documents, personal data, long conversations), where traffic repeats fewer than 5% of the questions, or where a wrong answer costs far more than the saving. In those cases the useful levers are others: reuse of the prompt prefix, routing to a smaller model, batching for what can wait. I will not tell you which is worth more for you: it depends on how much traffic repeats, and that is a measurement made with the request log, not with intuition.
Frequently asked questions
Does self-hosting really cost zero per token?
No. The server is paid for even when it is idle: the cost per token is a fixed cost divided by the tokens actually served, and it falls only if the server is used. The break-even threshold against APIs is computed as in the dedicated article of the series.
What similarity threshold should I use?
There is no value that is valid everywhere: it depends on the embedding model and on your questions. Prepare a set of labelled questions, count right and wrong hits at different thresholds and choose the one that maximizes the net value with your error cost.
Does quantization make the answers worse?
It can: the llama.cpp documentation speaks of a possible loss of accuracy, measured in perplexity or Kullback-Leibler divergence. How much depends on the model and the format: verify it on your own task, with a non-inferiority test.
What you can do now
You can place the three levers on their layer and you know why they do not add up, you can tell the exact, normalized and semantic cache apart and you can measure the net value of a threshold by counting right hits, wrong hits and the cost of the check. You also know that a cache without invalidation serves outdated answers, and that a shared cache must include in the key everything the answer depends on. The data in the listings are invented: replace them with your own request log. To place this lever in a cycle of measuring and repeating, go back to the article that closes the series.
Sources
- Redis LangCache (Redis documentation) - semantic response cache, check of semantically similar prompts, configurable similarity thresholds, TTL and eviction policies; accessed 2026-11-13
- Ollama FAQ (documentation) - default parallelism per model 1, default queue of 512 requests, memory proportional to parallelism times context; accessed 2026-11-12
- llama.cpp: quantize (project README) - quantization reduces size and can speed things up, with possible loss of accuracy measured in perplexity or KL divergence; accessed 2026-11-13
- Runs executed locally:
python3 -Ion the three listings (standard library, Python 3.14.4), each twice with identical output; questions, counts and costs invented for the example. The trigram vector is not an embedding model. No model run, no Redis cache used

Commenti
Caricamento commenti...
Sign in to comment