Skip to content
AgenticAIWiki
  1. Learn
  2. Part 13
  3. 70. Caching layers and multi-region
  4. 70.2

Lesson 70.2 · 2 of 5 · 4 min read · Reviewed 24 Nov 2026

Cache keys, TTLs and invalidation

By the end, you can

  • Design cache keys and expiry.
  • Invalidate caches when inputs change.

Most cache bugs come from a key that leaves something out.

Build the key

key = hash(
  model_id,
  prompt_version,
  effort, max_tokens, tool_set_version,
  tenant_id or user_id (if private),
  source_data_version,
  normalised_input
)

Leave out the prompt version and a prompt fix won’t reach users. Leave out the tenant and one customer may see another’s answer.

Normalising input

Trimming whitespace and lowercasing raises hit ratesHit rate@k: The share of test questions with at least one relevant chunk in the top k results. for response caches. Don’t normalise away meaning: “refund order 1001” and “refund order 1010” must not collide.

TTLs

Content Example TTL
Public FAQ answer Hours to a day
Answer based on account data Minutes, or don’t cache
Embedding of a static document Until the document changes
Prompt cache (provider side) Set by the provider; minutes

Invalidation

Tie entries to versions. When the prompt, model or source data changes, bump the version so old keys stop matching. That is simpler and safer than finding and deleting entries.

Prompt cache keys are positional

Provider prompt caches match an exact prefix. Put stable content first (tools, system promptSystem prompt: Instructions passed in the top-level system field that set the model’s role, rules and context for the whole conversation., documents) and changing content last (the user’s question). A timestamp at the top of the system prompt breaks every cache hitCache hit: A request whose prompt prefix was found in the cache, so it is read cheaply instead of processed again..

Key points

  • A cache key must include everything that changes the answer: model, prompt version, settings, user scope, data version.
  • Set a time to live (TTL) that matches how fast the underlying facts change.
  • Invalidate on change: when the prompt, model or source data updates, old entries must stop being served.
Hands-on labRuns in the Playground

Design a cache key that cannot leak

Build a response cache key and TTL that hit on harmless differences and miss on real ones.

You will have: A cache_key() function and a TTL cache that pass five checks.

Steps

  1. Run the starter and read which checks fail.
  2. Add prompt version, data version, tenant and settings to the key.
  3. Normalise the question so case and spacing don't matter.
  4. Make get() ignore entries older than the TTL.
  5. Add a sixth check of your own, such as a different model id.

Done when

  • 5 of 5 checks passed is printed.
  • A different tenant or prompt version produces a different key.
  • Entries are served at 100 seconds and not at 400 seconds with a 300-second TTL.

Open in the Playground No API key needed.

Starter code (Python)
# Design a cache key that includes everything that changes the answer, plus a TTL.
import hashlib
import json


def cache_key(model, prompt_version, data_version, tenant, settings, question):
    # TODO: include model, prompt_version, data_version, tenant and settings (json, sorted keys),
    # and normalise the question (lower case, collapse spaces).
    parts = [model, question]
    return hashlib.sha256("|".join(parts).encode()).hexdigest()[:16]


class Cache:
    def __init__(self, ttl):
        self.ttl, self.items = ttl, {}

    def get(self, key, now):
        hit = self.items.get(key)
        # TODO: only return the value if it is younger than self.ttl
        return hit[0] if hit else None

    def put(self, key, value, now):
        self.items[key] = (value, now)


BASE = dict(model="model-x-2026-01", prompt_version="v14", data_version="d7", tenant="acme", settings={"temperature": 0}, question="Where is my order?")
k = lambda **change: cache_key(**{**BASE, **change})
cache = Cache(ttl=300)
cache.put(k(), "It ships Friday.", now=0)

checks = [
    ("same question, different case and spacing hits", k(question="  where IS my   order? ") == k()),
    ("new prompt version misses", k(prompt_version="v15") != k()),
    ("another tenant misses", k(tenant="globex") != k()),
    ("new data version misses", k(data_version="d8") != k()),
    ("entry expires after its TTL", cache.get(k(), now=100) is not None and cache.get(k(), now=400) is None),
]
for name, ok in checks:
    print(("PASS " if ok else "FAIL ") + name)
print(f"{sum(ok for _, ok in checks)} of {len(checks)} checks passed")
Show a solution
# Design a cache key that includes everything that changes the answer, plus a TTL.
import hashlib
import json


def cache_key(model, prompt_version, data_version, tenant, settings, question):
    parts = [model, prompt_version, data_version, tenant, json.dumps(settings, sort_keys=True),
             " ".join(question.lower().split())]
    return hashlib.sha256("|".join(parts).encode()).hexdigest()[:16]


class Cache:
    def __init__(self, ttl):
        self.ttl, self.items = ttl, {}

    def get(self, key, now):
        hit = self.items.get(key)
        if hit and now - hit[1] < self.ttl:
            return hit[0]
        return None

    def put(self, key, value, now):
        self.items[key] = (value, now)


BASE = dict(model="model-x-2026-01", prompt_version="v14", data_version="d7", tenant="acme", settings={"temperature": 0}, question="Where is my order?")
k = lambda **change: cache_key(**{**BASE, **change})
cache = Cache(ttl=300)
cache.put(k(), "It ships Friday.", now=0)

checks = [
    ("same question, different case and spacing hits", k(question="  where IS my   order? ") == k()),
    ("new prompt version misses", k(prompt_version="v15") != k()),
    ("another tenant misses", k(tenant="globex") != k()),
    ("new data version misses", k(data_version="d8") != k()),
    ("entry expires after its TTL", cache.get(k(), now=100) is not None and cache.get(k(), now=400) is None),
]
for name, ok in checks:
    print(("PASS " if ok else "FAIL ") + name)
print(f"{sum(ok for _, ok in checks)} of {len(checks)} checks passed")
Quick checkYou updated the system prompt, but users still get answers in the old style. Why?
How sure are you?
Pick an answer and how sure you are