Back to Tutorials
LLM Application Development
Beginner

Caching Embeddings: Never Pay for the Same Chunk Twice

Replay two years of real edits to a FAQ through a hash cache, find the chunking that makes a small edit cost one chunk, and see what happens when the model changes but the key doesn’t.

9 minInteractive: drag, click and try things as you read


A search system turns every chunk of your documents into an embedding, and documents keep changing. Re-embed everything on every edit and you pay for the same text again and again, in money with an API and in time with a local model. The fix is a cache: store each vector under a key made from its text, and only embed what the cache hasn’t seen. Here you’ll replay two years of real edits to a real FAQ through one, and break it by changing models. A cache only saves what stays exactly the same, so how you cut the text matters as much as the cache.

A key made from the text#

An embedding model is deterministic: the same model given the same text gives the same vector. So you can keep every vector you’ve made, filed under a key, and look it up before asking the model. The key is usually a hash of the text, such as SHA-256: a 64-character fingerprint that’s quick to compute, the same every time for the same text, and completely different if a single character changes. That last part is what makes it safe: a key match means the text is identical, so the stored vector is exactly the one the model would give you.

Before embedding, documents are cut into chunks, and the cache works chunk by chunk. When a document changes, the chunks that came out the same are hits, already in the cache, and the rest are misses that go to the model. Which chunks come out the same depends on where you cut.

Real edits, two ways to cut#

Ollama’s FAQ, on GitHub, is a good stand-in for a help centre. Between August 2023 and August 2025 it went through 67 versions, from a few lines to 17,197 characters: new questions, rewritten answers, small fixes and a revert. The figure indexes every version in turn with a cache, cutting each one two ways: every 400 characters, wherever that falls, or at its Markdown headings, one chunk per question and answer, with any section over 1,000 characters split between paragraphs.

Predict first

Version 61 was a 14-character fix (“make context length faq readable”). Cutting every 400 characters, how many of its 39 chunks miss the cache?

Try it
Every version of docs/faq.md from github.com/ollama/ollama (MIT licence), rebuilt from its git history. Your browser cuts each version into chunks, hashes every chunk with SHA-256 and checks it against a cache holding every chunk of every earlier version. Nothing is embedded here: the figure counts what would be. In “Your edit”, the cache holds all 67 versions.

Cutting by position is the problem. Add or remove a single character and everything after it shifts, so every later 400-character chunk is new text: in six of the last ten versions, more than half the 400-character chunks missed the cache. Cutting at headings ties each chunk to the content itself, so an edit only changes the section it’s in. Over the whole history, re-embedding everything every time would send 580,835 characters to the model. With the cache, cutting every 400 characters still sends 280,601 (48%); cutting at headings sends 65,501 (11%). And look at version 63, a revert: nothing at all to embed, because the cache still holds the text from before. Try “Your edit” too: change one word near the top and compare the two cuts. Cut at boundaries in the content, such as headings or paragraphs, so an edit only touches its own chunk.

What goes in the key#

The text alone doesn’t decide the vector; the model does too. Here’s what happens when a team improves its search by switching model with a cache keyed on the text alone. The articles are the 50 help-centre articles from the RAG explainer, and the 20 test questions each have a known right article. The old model, all-MiniLM-L6-v2, finds it first for 15 questions; the new one, bge-small-en-v1.5, for 17. Both give 384 numbers per text, so nothing complains when you mix them. After the switch, questions are embedded with the new model. Articles that haven’t changed since come back from the cache, made by the old model; only articles edited since the switch miss the cache and get new vectors.

Predict first

One article has been edited since the switch, so the index holds 1 new-model vector and 49 old ones. How many of the 20 questions find the right article?

Try it
Real vectors from both models for the same 50 articles and 20 questions, stored at 8-bit precision. Your browser builds the index each way and searches it. Which articles count as edited follows a fixed random order.

With nothing re-embedded, the mix still gets 10 of 20 right: the two models happen to line up a little, so old vectors aren’t pure noise to new questions, which is exactly what makes this mistake easy to miss. As articles get edited, the new-model vectors crowd the top of every result list; only with all 50 re-embedded is the search back to 17. Put the model’s name in the key and the problem disappears: the first indexing run after the switch misses on every article and rebuilds the whole index with the new model. Put everything that changes the vector in the key, the model first of all, and never mix models in one index.

The model isn’t the only thing that changes a vector. Include anything that does:

  • The model and its version. A provider’s model name usually pins one version, but a local model you update in place can change under the same name.
  • Settings. Some APIs let you choose the number of dimensions, and some models expect a prefix such as “query:” or “passage:” in front of the text.
  • Any clean-up before embedding, such as lowercasing or cutting long text to a limit. Either put the settings in the key, or hash the text after the clean-up, exactly as it’s sent.

In practice#

  • Store the hash with the vector. Most vector databases let you keep extra fields with each vector. Keep the chunk’s hash there and re-indexing becomes: cut, hash, embed only the hashes you don’t have, delete the ones that disappeared.
  • Switch models into a new index. Build it alongside the old one, test it on your questions, then switch searches over in one go.
  • Any store will do. A SQLite file is plenty for one machine; Redis or your database when several servers share the cache.

In code#

A cache in SQLite, keyed by SHA-256 of the model name and the text, run on the two versions of the FAQ either side of the 14-character fix, cut both ways. Free and local (pip install sentence-transformers):

import hashlib, re, sqlite3, urllib.request
import numpy as np
from sentence_transformers import SentenceTransformer

MODEL = "sentence-transformers/all-MiniLM-L6-v2"
model = SentenceTransformer(MODEL)
db = sqlite3.connect("embeddings.db")
db.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, vector BLOB)")

def key(text):
    # everything that changes the vector goes in the key: the model and the exact text
    return hashlib.sha256(f"{MODEL}\n{text}".encode()).hexdigest()

def embed(chunks):
    """Embed only the chunks the cache hasn't seen; return a vector for every chunk."""
    keys = [key(c) for c in chunks]
    found = {k: v for k, v in db.execute(f"SELECT key, vector FROM cache WHERE key IN ({','.join('?' * len(keys))})", keys)}
    todo = list({k: c for k, c in zip(keys, chunks) if k not in found}.items())
    if todo:
        vectors = model.encode([c for _, c in todo], normalize_embeddings=True)
        for (k, _), v in zip(todo, vectors):
            found[k] = v.astype(np.float32).tobytes()
            db.execute("INSERT INTO cache VALUES (?, ?)", (k, found[k]))
        db.commit()
    print(f"{len(chunks)} chunks: {len(chunks) - len(todo)} from the cache, {len(todo)} embedded")
    return [np.frombuffer(found[k], dtype=np.float32) for k in keys]

def at_headings(text):
    return [c for c in re.split(r"\n(?=#{1,6} )", text) if c.strip()]

def every(text, size=400):
    return [text[i:i + size] for i in range(0, len(text), size)]

# two versions of Ollama's FAQ, before and after a 14-character fix
url = "https://raw.githubusercontent.com/ollama/ollama/{}/docs/faq.md"
before, after = (urllib.request.urlopen(url.format(c)).read().decode() for c in ("74b44fdf8fa6", "b816ff86c923"))
for chunker in (every, at_headings):
    print(chunker.__name__)
    embed(chunker(before))
    embed(chunker(after))
# every
# 39 chunks: 0 from the cache, 39 embedded
# 39 chunks: 1 from the cache, 38 embedded
# at_headings
# 31 chunks: 0 from the cache, 31 embedded
# 31 chunks: 30 from the cache, 1 embedded

This splitter cuts at every heading and never splits a long section, so it makes 31 chunks where the figure makes 36; the result is the same. Run it twice and the second run embeds nothing: the vectors are in the file.

What to remember

  • An embedding cache stores each vector under a hash of its text, so unchanged chunks are never embedded twice.
  • How you cut decides what survives an edit: over 67 real versions of a FAQ, 400-character chunks still sent 48% of the text to the model, chunks cut at headings 11%.
  • Put the model and anything else that changes the vector in the key; a cache keyed on text alone quietly mixes models and wrecks search.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.