Code Lab / Challenge 16

Semantic Cache with TTL, LRU and Tag Invalidation

MediumExact and semantic cache tiers, TTL, LRU, tag invalidation

The problem, as an interviewer would set it

Model calls are slow and metered, and query traffic for support or FAQ-style
products is often heavy-tailed, with a head of near-identical questions. That
makes a cache in front of the model one of the cheapest wins available. A
*semantic* cache goes further than a hash map: it serves a stored response
when a new query is close enough to one already answered. Implement:

    SemanticCache(embedder, threshold=0.92, capacity=128, ttl=None,
                  clock=time.monotonic)

        get(query) -> str | None
            L1 exact hit on the canonical key (lowercased, punctuation
            stripped, whitespace collapsed), then L2 cosine nearest neighbour
            over the stored query vectors, which hits only when the best score
            >= threshold. Records exactly one exact_hit, semantic_hit or miss
            per call and marks whichever entry it served as most recently used.

        put(query, response, tags=()) -> None
            Insert or refresh. Over capacity, evict the least recently USED
            entry. With ttl set, an entry dies ttl seconds after the write
            that created or refreshed it, measured with clock().

        invalidate(tag) -> int
            Drop every entry carrying that tag, from both tiers, and return
            how many went: the document-version hook, since when doc 42 is
            re-indexed every cached answer derived from it has to die.

        stats -> CacheStats(exact_hits, semantic_hits, misses, hit_rate)
        len(cache) -> number of live (unexpired) entries

numpy and the standard library only, with the clock injected so TTL behaviour
is testable without sleeping. The embedder is the hashed character n-gram one
from challenge 08: it scores surface overlap rather than meaning, so the test
pairs below are crafted as lexical near-twins.
What interviewers look for

Threshold as a precision/recall business decision, why cache keys must include prompt and model version

A strong solution demonstrates:
- The threshold is a business decision. A miss costs one model call; a false
  hit serves a confidently wrong answer. Support deflection with a feedback
  escape can run loose; billing or legal answers run tight or are not cached
  semantically at all. Set it by measuring false-hit rate per threshold on
  labelled query pairs against an error budget, and re-tune whenever the
  encoder changes: cosine scales differ between embedding models.
- Both tiers must share one store. Deleting from the exact map while leaving
  the vector in the search index is how expired and invalidated answers keep
  getting served, the classic bug in naive semantic caches for RAG. The TTL
  and invalidation tests probe with a paraphrase for exactly that reason.
- Knowing what this is NOT. Provider prompt caching reuses the KV cache of a
  repeated prompt prefix: it cuts input cost and time to first token but
  still decodes a fresh answer, drawn from the same distribution an uncached
  call would use. A response cache skips the model entirely and can be wrong.
  Most stacks want both.
- Eviction by recency of *use*, not of insertion: an OrderedDict plus
  move_to_end on every hit and every write is the whole trick.
- Never cache across tenants, or across system-prompt and model versions.
  Keying on query text alone serves tenant A's answer to tenant B, a data leak
  rather than a cache bug, and an entry that outlives a prompt change serves
  the old behaviour while your rollout metrics measure nothing. So the key is
  hash(model id + decoding params + prompt template version + tool schema
  version + tenant + canonical query): whatever can change the output goes in
  it, whatever cannot stays out or the hit rate collapses. One namespace per
  (model, prompt version, tenant) makes a version bump a namespace drop.
Common mistakes: unbounded growth; expiry checked only on the exact path;
caching a streamed response before the stream completes; caching errors and
refusals; serving a cached answer where the product promises variety, such as
a regenerate button; caching answers that depend on per-user context or live
tool results; embedding before the exact tier is checked, which bills an
embedding on every request; a threshold copied from a blog post.
Follow-ups: in-process L1 plus shared Redis L2 and the coherence problem
between them; writing the new query in as an alias of the entry that served
it; negative caching; an ANN index sharded by namespace; reporting money saved
and false hits rather than hit rate alone.

Write your own version first. The reference solution and its tests are one click away when you are ready.

Next challenge