Before replacing a slow RAG assistant’s model, measure where it waits and what you actually pay for. Slow retrieval, reranking, oversized inputs and slow generation require different interventions. Caching can remove some work, but a poorly designed cache can also return an outdated rule or an answer intended for someone else.
This workflow is for the owner of a running assistant and its developers. It includes a small, actually executed local demonstration of a timeline, cache invalidation and a lost exception. It uses synthetic documents and ordinary text operations. It is not a language-model benchmark or a case study of client savings.
Measure ingestion, retrieval, reranking and generation separately
Ingestion means acquiring and processing documents: downloading, conversion, chunking, possibly creating embeddings and storing an index. It usually happens outside an individual query. But if a user uploads a new PDF and immediately waits for an answer, that work is part of their waiting time. For a continuously updated knowledge base, track not just import cost but also the delay between a source change and its appearance in answers.
Retrieval finds candidate passages. Reranking then reorders them and may use another model call. Context is then assembled, possibly shortened, and only afterward does the answering model generate text. Include the processing queue, network, retries, output review and delivery to the interface. Recording only the duration of the final API call does not describe the entire path.
Assign each request one identifier and child spans with start, end and result. Record counts of retrieved and forwarded passages, actual tokens reported by the provider, the model used and configuration version. Do not log complete confidential queries unnecessarily. If two retrievers run concurrently, you cannot simply add their times: the user waits for the critical path and the relevant delays between steps.
Our demonstration created 1,200 hypothetical documents and a local word index. The query found one passage, results were ordered by a simple score and the answer was assembled from its text. We use no embeddings, learned reranker or LLM. Import has its own time origin; the waterfall below begins only when the query is received. Gaps between bars remain visible because measurement overhead is not work performed by individual components.

On a narrow display, scroll the table horizontally; after focusing the region with Tab, use the arrow keys.
| Phase | Step | Duration (µs) |
|---|---|---|
| Preparation outside query | Document creation | 1648.845 |
| Preparation outside query | Local word index | 3303.788 |
| Query | Retrieval | 223.816 |
| Query | Score-based sorting | 3.345 |
| Query | Context preservation | 1.552 |
| Query | Template output | 10.576 |
One such run does not establish a server’s stable speed. For operating decisions, collect comparable requests under normal and peak load, separate cold starts from warm operation and track timing distributions, errors and incomplete attempts. The median can look good even when some people wait unacceptably long. Always accompany the chosen percentile with the measurement count and task mix.
Calculate the cost of an accepted answer
Split the budget into data import and updates, retrieval infrastructure, individual model calls and human review. Include failed attempts and retries in the cost of a usable answer. Cheaper generation that causes more corrections may not reduce the cost of finished work. The basics of distinguishing operational metrics from business outcomes are discussed in data in content marketing; here you also need a cost record for each pass through the application.
Illustrative calculation, not an executed API call: OpenAI pricing checked on November 18, 2026 lists GPT-4.1 mini in Standard mode at USD 0.40 per million input tokens, USD 0.10 per million cached input tokens and USD 1.60 per million output tokens. With an assumed 10,000 input and 1,000 output tokens, the model call alone costs USD 0.0056. If 8,000 tokens of that same input are actually reported as cached and the remaining 2,000 are not, the cost is USD 0.0032. Output is billed in both cases. We exclude tax, additional tools, retrieval, a summarization model and human work; token counts are hypothetical assumptions.
Check the current rate and mode in the primary pricing source. This calculation is neither a promise of a cache hit nor evidence of savings in your system. Other models may also charge for writing a prefix to cache; do not extend one family’s rule to the entire catalog.
Separate the first token from the complete answer
TTFT, time to first token, is the time until the model’s first output token. But you must specify where measurement starts: when the model request is sent or when the user asks the question in the application. The latter also includes earlier retrieval and other steps. “Searching sources…” is an interface status, not the answering model’s first token.
Alongside TTFT, record time to the complete answer and, where useful, to the first useful information. Those are not synonyms either. A model may quickly begin with an empty introduction and leave the decisive condition until the end. For a model with hidden reasoning, the first internal computation may not equal the first content available to the user. Tie the definition to the actual interface and recorded events.
Streaming sends content progressively. It can help users follow progress, but does not itself prove a shorter time to a finished answer or a lower cost. For a draft that still needs review, also consider whether unverified portions may be shown progressively. Quickly displaying incorrect advice is not a successful optimization.
Our fixture returns ordinary string chunks. Its output therefore explicitly leaves LLM TTFT and complete-model-answer latency unmeasured. The measured time to the first template chunk must not be labeled TTFT. This checks instrumentation; it does not replace actual inference.
Test for lost meaning during compression
Context can be shortened by removing duplicates, selecting passages or summarizing. Each option needs its own fidelity check. An additional summarization model also takes time and costs money; a smaller final-model input alone does not establish savings. Conditions, negatives, units and exceptions should be part of the test reference, not the first things omitted.
Our hypothetical passage reads: “Standard delivery takes two business days. For made-to-order goods, the delivery date is agreed individually.” An intentionally faulty compressor keeps only the first sentence. A query about made-to-order goods then lacks the decisive exception. The test detects that loss; the control version preserves the entire text. This is not a measured LLM summarization error rate: the faulty intervention is a predefined rule and the check looks for known expressions.
In a real regression suite, have the responsible subject expert assess meaning, not just word presence. An exception can formally remain in a summary yet become attached to the wrong product. Keep the original passage, compressed version, final input and answer. If the error already appears in the summary, do not address it merely by using a larger final model.
Bind the cache key to role and version
First distinguish what you store. A retrieval-result cache retains selected sources. A finished-answer cache may also skip assembling them again. A provider’s prompt cache, by contrast, reuses a processed identical input prefix; it is not a library of previous answers to similar questions. These layers may differ in retention, permissions and invalidation.
OpenAI’s documentation describes prefix matching and model-specific conditions. Claude’s documentation also uses prefixes and distinguishes cache writes from reads. Neither mechanism establishes that finished answers can safely be shared between users merely because their questions have a high similarity score. That score is not a universal percentage of semantic equivalence either.
For an application-level answer cache, include the tenant, authorized user or precisely defined security scope, permissions version, source-data version, the question’s temporal context and answering-configuration version. A generic role alone may be too coarse: two salespeople may not have access to the same customers. A sensitive key need not contain readable personal data, but it must unambiguously separate permitted scopes.
The key does not replace fresh authorization. Once access is revoked, an old hit must not bypass the current decision. When a document changes, update its version or invalidate every dependent answer. A source may cease to be effective before the configured TTL, or cache lifetime. A historical question about October is also not the same as a question about today’s rule.
On a narrow display, scroll the table horizontally; after focusing the region with Tab, use the arrow keys.
| Change | Expected | Result |
|---|---|---|
| Same key, time 11 | hit | PASS |
| Different role / user / tenant | miss | PASS |
| New permissions, data or configuration version | miss | PASS |
| Access now revoked | no cached answer | PASS |
| TTL: before boundary 29, boundary 30 | hit / miss | PASS |
| Validity: before boundary 24, boundary 25 | hit / miss | PASS |
| Explicit invalidation | miss | PASS |
The 19 executed checks cover not only a hit but also changes to identity, role, versions and date, a different query, currently revoked access, exact time boundaries, explicit invalidation and both compression variants. All passed. This establishes the behavior of this small implementation, not zero risk of production leakage. Detailed management of effective dates and owners is covered in company knowledge for AI; the goal here is to prevent optimization from bypassing those rules.
An executable local Python demonstration
Copy the complete code into ukazka.py and run python3 ukazka.py. It requires only Python 3.10+ and the standard library, with no network access or file writes. Timings will change on another run; the 19 checks verify known synthetic conditions. Longer lines scroll horizontally.
"""Python 3.10+, standard library. Synthetic local pipeline, NOT LLM inference.
No network, sleeps, provider calls or CMS writes. Results are written to stdout only.
"""
import copy, hashlib, json, re, time, platform
from dataclasses import dataclass, replace
TEXT = 'Standardní doručení trvá dva pracovní dny. U zboží na zakázku se termín sjednává individuálně.'
@dataclass(frozen=True)
class Context:
tenant: str = 'demo'
user: str = 'u1'
role: str = 'podpora'
acl_version: int = 1
corpus_version: int = 1
model_version: str = 'template-v1'
prompt_version: str = 'p1'
compressor_version: str = 'full-v1'
as_of: int = 50
def key(c, query):
return (c.tenant,c.user,c.role,c.acl_version,c.corpus_version,
c.model_version,c.prompt_version,c.compressor_version,c.as_of,query)
class Cache:
def __init__(self): self.data = {}
def put(self,c,q,value,now,ttl,valid_to):
self.data[key(c,q)] = (value, min(now+ttl,valid_to))
def get(self,c,q,now,authorized):
# Authorization from the current caller, not a cached permission decision.
if not authorized: return None
item=self.data.get(key(c,q))
return item[0] if item and now < item[1] else None
def invalidate(self): self.data.clear()
def compress(text, mode):
if mode=='bad': return text.split('. ')[0]+'.'
return text
def preserves_exception(text):
return 'zboží na zakázku' in text and 'individuálně' in text
def trace_run():
# Deterministic documents; timing is measured, not deterministic.
spans=[]
def stage(name,fn,base):
start=time.perf_counter_ns();result=fn();end=time.perf_counter_ns()
spans.append({'stage':name,'start_us':(start-base)/1000,
'end_us':(end-base)/1000,'duration_us':(end-start)/1000})
return result
ingest_base=time.perf_counter_ns()
docs=stage('ingestion',lambda:[{'id':str(i),'text':TEXT if i==777 else
'Skladová informace '+str(i),'roles':['podpora','vedouci'],
'version':1,'from':0,'to':100} for i in range(1200)],ingest_base)
index=stage('index_local_words',lambda:[(d,set(re.findall(r'\w+',d['text'].lower())))
for d in docs],ingest_base)
ingestion=list(spans);spans=[]
base=time.perf_counter_ns();query='zboží na zakázku';words=set(query.split())
hits=stage('retrieval',lambda:[(d,len(ws&words)) for d,ws in index
if 'podpora' in d['roles'] and d['from']<=50<d['to'] and ws&words],base)
ranked=stage('rerank_local_score',lambda:sorted(hits,key=lambda x:(-x[1],x[0]['id'])),base)
context=stage('compression_preserve_full',lambda:compress(ranked[0][0]['text'],'full'),base)
parts=[];first_at=None
# Ordinary string chunks are NOT model tokens. Do not label this metric TTFT.
start=time.perf_counter_ns()
for chunk in context.split(' '):
parts.append(chunk)
if first_at is None:first_at=time.perf_counter_ns()
end=time.perf_counter_ns()
spans.append({'stage':'template_output','start_us':(start-base)/1000,
'end_us':(end-base)/1000,'duration_us':(end-start)/1000})
assert ' '.join(parts)==TEXT and preserves_exception(context)
return {'ingestion_spans':ingestion,'query_spans':spans,
'first_local_text_chunk_us':(first_at-base)/1000,
'complete_local_text_us':(end-base)/1000,'TTFT_llm_ms':None,
'llm_output_latency_ms':None,'production_cost':None,
'output':context,'document_count':len(docs),'hits':len(hits),
'scope':'synthetic lexical lookup, local sort, identity compression and string output; no embeddings/reranker model/LLM'}
def tests():
c=Context();q='doručení';cache=Cache();checks=[]
cache.put(c,q,TEXT,now=10,ttl=20,valid_to=100)
def check(name,condition):
assert condition,name
checks.append({'id':name,'pass':True})
check('same_key_hit',cache.get(c,q,11,True)==TEXT)
for field,value in [('tenant','other'),('user','u2'),('role','externi'),
('acl_version',2),('corpus_version',2),('model_version','template-v2'),
('prompt_version','p2'),('compressor_version','short-v2'),('as_of',49)]:
check(field+'_miss',cache.get(replace(c,**{field:value}),q,11,True) is None)
check('new_query_miss',cache.get(c,'jiný dotaz',11,True) is None)
check('revoked_authorization',cache.get(c,q,11,False) is None)
check('ttl_before_boundary',cache.get(c,q,29,True)==TEXT)
check('ttl_exact_expiry',cache.get(c,q,30,True) is None)
cache.put(c,q,TEXT,now=10,ttl=90,valid_to=25)
check('validity_before_boundary',cache.get(c,q,24,True)==TEXT)
check('validity_exact_boundary',cache.get(c,q,25,True) is None)
cache.invalidate()
check('explicit_invalidation',cache.get(c,q,11,True) is None)
check('bad_compression_caught',not preserves_exception(compress(TEXT,'bad')))
check('full_compression_preserves_exception',preserves_exception(compress(TEXT,'full')))
return checks
def main():
return {'python':platform.python_version(),'system':platform.platform(),
'run_at_unix':time.time(),'checks':tests(),'trace':trace_run(),
'bad_summary':compress(TEXT,'bad'),'source':TEXT}
if __name__=='__main__':print(json.dumps(main(),ensure_ascii=False,indent=2))
Verify a model change with a regression suite
Assess a model replacement against the same questions, sources, permissions and expected exceptions. Separate simple queries from long analyses and unanswerable cases. Record refusals, incomplete outputs and retry costs, too. A cheaper model may suit part of the work, but the classifier deciding its routing also needs verification.
Do not accept a new option merely because its median fell. It must preserve the agreed correctness and data-protection conditions. If you add a compressor, different reranker and new model simultaneously, you can compare the overall solution but cannot attribute the change to one intervention without further runs. For the mechanics of combining results, see the explanation of RRF; faster ranking alone does not verify source truthfulness.
A practical first deliverable is one traceable request trace, a distribution of actual operating times and the cost per accepted answer. Only then choose an intervention, its owner and a rollback condition. This article did not measure production latency, inference cost or savings. It demonstrated an executable way to keep the layers distinct and detect specific defects in a small demonstration.
Want to find where your AI assistant loses time and budget?
I can help define the problem, prepare a measurement brief and agree acceptance criteria with your technical team. Tell me which tasks currently make your assistant slow work down. We will confirm the diagnostic and implementation scope in advance; specific savings need verification first. Do not send confidential logs or documents through the form.









