RAG · Lesson 95 of 120
Cost and Speed
Where time goes.
Before making RAG faster, measure where the time goes. Let's time each step. Loading, embedding the chunks, searching, and generating the answer.

- Measure first
- Time each step
- Then optimise
Timing each step
Timer wraps each step, and prints how long it took. We load and chunk, build the index, search, and generate. Run it. Search takes a few milliseconds. Building the index and generating the answer take far longer.
timing.pypython
import time
from rag_kit import load_docs, make_chunks, Index
from llm import answer
def timer(name, fn):
start = time.perf_counter(); result = fn()
print(f"{name:10} {(time.perf_counter() - start) * 1000:7.0f} ms")
return result
q = "How much is a Basic service?"
chunks = timer("chunking", lambda: make_chunks(load_docs()))
index = timer("indexing", lambda: Index(chunks))
hits = timer("search", lambda: [c for s, c in index.search(q)])
timer("answer", lambda: answer(q, hits))Output
chunking 1 ms indexing 135 ms search 7 ms answer 1559 ms
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses llm.py
from langchain.chat_models import init_chat_model
llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".
Context:
{context}
Question: {question}"""
def answer(question, chunks):
context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()Making it cheaper
Indexing happens once, so it rarely matters. Generation dominates every question. Use a small, fast model, send fewer chunks, cache common answers, and stream, so users see words sooner.
| key | value |
|---|---|
| Indexing | once, offline |
| Generation | the big cost |
| Fewer chunks | fewer tokens |
| Stream | feels faster |
Summary
Time each step before optimising. Generation usually dominates, so trim the prompt and choose a fast model. Next, keeping the index fresh.
Key takeaways- Time each step
- Generation dominates
- Trim the prompt
Next up: Keeping the Index Fresh — re-index what changed