Caching and latency budgets
Build LLM-backed product features end to end against a deterministic local mock: form well-formed chat requests, structure prompts and validated JSON outputs, stream and retry safely, ground answers in retrieved sources, call tools inside bounded agent loops, defend against prompt injection, and evaluate quality with reproducible checks instead of one-off demos. No API keys and no network calls are used anywhere in the course.
What you will be able to do
#- Implement a deterministic response cache with explicit keys and TTL expiry, and predict hit, expired and miss lookups.
- Explain which requests are safe to cache and why personalization, nondeterministic parameters and content freshness define the boundary.
- Place model calls inside latency budgets with time-to-first-token and total-time targets, and name the lever that fixes a breach.
Overview
#Latency is a product constraint
A model call is often the slowest step in a feature. Users perceive anything over roughly a second as slow, and a full generation can take several. Two numbers describe the experience: time to first token (TTFT), how long until the first piece of the reply arrives, and total generation time, how long until the reply is complete. Streaming (lesson ai-engineering-streaming-and-abort) improves perceived latency by delivering the first token early. Caching goes further: it removes the call entirely for repeated identical work.
The cache: key, value, expiry
A cache is a map from a key to a stored response with an expiry. The entire design lives in two decisions: what the key contains, and when entries expire.
The key must capture everything that determines the output: the model, the sampling parameters, and the full prompt, system message included. A stable way to build one is to serialize the tuple:
function cacheKey(model, params, messages) {
return JSON.stringify([model, params, messages]);
}
Because JSON.stringify is deterministic for the same data in the same order, equal requests produce equal keys, and any difference in the prompt produces a different key. That property is what makes a cache correct; everything else is bookkeeping.
Expiry is a time-to-live (TTL): a stored entry is valid for a window, then stale. The lookup separates three outcomes so callers can react to each:
function createCache() {
return new Map();
}
function storeInCache(cache, key, value, nowMs) {
cache.set(key, { value, storedAtMs: nowMs });
}
function lookupCache(cache, key, nowMs, ttlMs) {
const entry = cache.get(key);
if (entry === undefined) return { hit: false, reason: "miss" };
const ageMs = nowMs - entry.storedAtMs;
if (ageMs > ttlMs) return { hit: false, reason: "expired", ageMs };
return { hit: true, value: entry.value, ageMs };
}
Worked trace with a 3000 ms TTL:
| Step | Call | nowMs | Result |
|---|---|---|---|
| 1 | lookup k1 | 1000 | miss |
| 2 | store k1, value "A" | 1000 | stored |
| 3 | lookup k1 | 1500 | hit, ageMs 500 |
| 4 | lookup k1 | 5000 | expired, ageMs 4000 |
What is safe to cache
Caching a model response is safe when three conditions hold at once:
- Deterministic generation: temperature 0 (lesson ai-engineering-parameters-and-determinism), so a fresh call would return the same text anyway.
- Shared inputs: the prompt contains no per-user data, so one stored answer is correct for every caller.
- Bounded staleness: the answer stays correct for the TTL, and the key changes when the underlying content changes.
The third condition is where grounded features need care: include a corpus version or content hash in the key, so updating the knowledge base invalidates old answers instead of serving them. The capstone (lesson ai-engineering-production-capstone) builds exactly this key.
Unsafe by default: personalized prompts (the stored answer is correct only for one user), temperature 1.0 creative generation (a fresh call legitimately differs), fast-changing facts (staleness is a correctness bug), and anything where a wrong cached answer is worse than a slow fresh one.
Latency budgets
A latency budget is a per-feature numeric target, set as a product decision, that the pipeline is measured against:
| Target | Meaning | Typical lever when breached |
|---|---|---|
| TTFT under 800 ms | the first token arrives quickly | stream the reply, cache hot paths |
| Total under 3 s | the full reply arrives quickly | shorter maxOutputTokens (lesson 4), smaller tier (lesson 17) |
| p95 under 5 s | the tail is bounded | find tail causes with lesson 16's percentiles |
Budgets make the fix a choice instead of a panic: a breach is met with a named lever, and the lever's own risk, truncation or quality, is a known trade-off rather than a surprise.
Honest limits of the mock
The mock cache is a Map in one process. It has no eviction under memory pressure, no concurrent writers, no distributed invalidation, and no provider-side prompt caching. Production caches add size bounds, eviction policies, stampede protection (one regeneration instead of a thundering herd of identical misses), and hit-rate monitoring. A semantic cache, returning a cached answer for a merely similar question, trades cost for a correctness risk and must be eval-gated (lesson 13): near-duplicate questions can need different answers.
Continue with ai-engineering-observability-and-logging: cache hit rates and latency percentiles only exist if you instrument them.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement cacheKey(model, params, messages) so it returns JSON.stringify([model, params, messages]). Verify by logging the key for a mock-mini request with temperature 0 and one user message.
starter.javascriptfunction cacheKey(model, params, messages) { // Return JSON.stringify([model, params, messages]). } console.log(cacheKey("mock-mini", { temperature: 0 }, [ { role: "user", content: "Summarize the changelog." } ]));Reveal the reference answer
reference.javascriptfunction cacheKey(model, params, messages) { return JSON.stringify([model, params, messages]); } console.log(cacheKey("mock-mini", { temperature: 0 }, [ { role: "user", content: "Summarize the changelog." } ]));Authored expected output: ["mock-mini",{"temperature":0},[{"role":"user","content":"Summarize the changelog."}]]
Serializing the tuple model, params, messages gives a deterministic key: identical requests collide on purpose, and any change to the prompt, model or parameters produces a different key. That equality property is the correctness condition of the whole cache.
Exercise 2Implement
Implement lookupCache(cache, key, nowMs, ttlMs) with three outcomes: no entry returns { hit: false, reason: "miss" }; an entry older than ttlMs returns { hit: false, reason: "expired", ageMs }; otherwise { hit: true, value, ageMs }. Run the scripted lookups and predict nothing: the code decides.
starter.javascriptfunction createCache() { return new Map(); } function storeInCache(cache, key, value, nowMs) { cache.set(key, { value, storedAtMs: nowMs }); } function lookupCache(cache, key, nowMs, ttlMs) { // No entry -> { hit: false, reason: "miss" }. // Entry older than ttlMs -> { hit: false, reason: "expired", ageMs }. // Otherwise -> { hit: true, value, ageMs }. } const cache = createCache(); storeInCache(cache, "k1", "Invoice 1042 totals 120 USD.", 1000); console.log(JSON.stringify(lookupCache(cache, "k1", 1500, 3000))); console.log(JSON.stringify(lookupCache(cache, "k1", 5000, 3000))); console.log(JSON.stringify(lookupCache(cache, "nope", 5000, 3000)));Reveal the reference answer
reference.javascriptfunction createCache() { return new Map(); } function storeInCache(cache, key, value, nowMs) { cache.set(key, { value, storedAtMs: nowMs }); } function lookupCache(cache, key, nowMs, ttlMs) { const entry = cache.get(key); if (entry === undefined) return { hit: false, reason: "miss" }; const ageMs = nowMs - entry.storedAtMs; if (ageMs > ttlMs) return { hit: false, reason: "expired", ageMs }; return { hit: true, value: entry.value, ageMs }; } const cache = createCache(); storeInCache(cache, "k1", "Invoice 1042 totals 120 USD.", 1000); console.log(JSON.stringify(lookupCache(cache, "k1", 1500, 3000))); console.log(JSON.stringify(lookupCache(cache, "k1", 5000, 3000))); console.log(JSON.stringify(lookupCache(cache, "nope", 5000, 3000)));Authored expected output: {"hit":true,"value":"Invoice 1042 totals 120 USD.","ageMs":500} {"hit":false,"reason":"expired","ageMs":4000} {"hit":false,"reason":"miss"}
The entry stored at 1000 ms is 500 ms old at 1500 (hit), 4000 ms old at 5000 (expired, since 4000 exceeds the 3000 ms TTL), and the unknown key is a plain miss. Distinguishing expired from miss lets callers log the difference and tune the TTL with evidence.
Exercise 3Predict
serve(question, cache, nowMs) looks up a cacheKey built from the question; on a miss it generates the fixed answer, stores it, and reports source "model"; on a hit it reports source "cache". Predict both logged lines for two identical calls at 1000 ms and 2000 ms with a 10000 ms TTL.
starter.javascriptfunction cacheKey(model, params, messages) { return JSON.stringify([model, params, messages]); } function createCache() { return new Map(); } function storeInCache(cache, key, value, nowMs) { cache.set(key, { value, storedAtMs: nowMs }); } function lookupCache(cache, key, nowMs, ttlMs) { const entry = cache.get(key); if (entry === undefined) return { hit: false, reason: "miss" }; const ageMs = nowMs - entry.storedAtMs; if (ageMs > ttlMs) return { hit: false, reason: "expired", ageMs }; return { hit: true, value: entry.value, ageMs }; } function serve(question, cache, nowMs) { const key = cacheKey("mock-mini", { temperature: 0 }, [ { role: "user", content: question } ]); const found = lookupCache(cache, key, nowMs, 10000); if (found.hit) return { source: "cache", answer: found.value }; const answer = "Reset via Settings, then Security."; storeInCache(cache, key, answer, nowMs); return { source: "model", answer }; } const cache = createCache(); console.log(JSON.stringify(serve("How do I reset my password?", cache, 1000))); console.log(JSON.stringify(serve("How do I reset my password?", cache, 2000)));Reveal the reference answer
reference.javascript// Predicted output: // // {"source":"model","answer":"Reset via Settings, then Security."} // {"source":"cache","answer":"Reset via Settings, then Security."} // // Trace: the first call misses on the empty cache, stores the fixed // answer at 1000 ms, and reports source "model". The second call builds // the same key from the same question, finds the entry 1000 ms old,\// well inside the 10000 ms TTL, and reports the same answer with source // "cache". Identical text, different provenance, and the provenance is // what the UI must label.Authored expected output: {"source":"model","answer":"Reset via Settings, then Security."} {"source":"cache","answer":"Reset via Settings, then Security."}
Same question, same key, so the second call hits. The answers are identical because generation is deterministic; the difference is provenance, which is exactly what a UI must label when serving cached content.
Exercise 4Debug
brokenKey builds the cache key from only the model and the last message content, dropping the system message. Two requests differ only in the policy version inside the system message. Predict the two logged lines, identify what goes wrong for the second caller, and fix the key so each policy version gets its own entry.
starter.javascriptfunction createCache() { return new Map(); } function brokenKey(model, messages) { return JSON.stringify([model, messages[messages.length - 1].content]); } function lookupOrGenerate(cache, key, generate) { const found = cache.get(key); if (found !== undefined) return { source: "cache", answer: found }; const answer = generate(); cache.set(key, answer); return { source: "model", answer }; } const cache = createCache(); const messagesV1 = [ { role: "system", content: "Answer using policy version 1: refunds take 10 days." }, { role: "user", content: "How long do refunds take?" } ]; const messagesV2 = [ { role: "system", content: "Answer using policy version 2: refunds take 5 days." }, { role: "user", content: "How long do refunds take?" } ]; console.log(JSON.stringify(lookupOrGenerate(cache, brokenKey("mock-mini", messagesV1), () => "Refunds take 10 days."))); console.log(JSON.stringify(lookupOrGenerate(cache, brokenKey("mock-mini", messagesV2), () => "Refunds take 5 days.")));Reveal the reference answer
reference.javascriptfunction createCache() { return new Map(); } function fixedKey(model, messages) { return JSON.stringify([model, messages]); } function lookupOrGenerate(cache, key, generate) { const found = cache.get(key); if (found !== undefined) return { source: "cache", answer: found }; const answer = generate(); cache.set(key, answer); return { source: "model", answer }; } const cache = createCache(); const messagesV1 = [ { role: "system", content: "Answer using policy version 1: refunds take 10 days." }, { role: "user", content: "How long do refunds take?" } ]; const messagesV2 = [ { role: "system", content: "Answer using policy version 2: refunds take 5 days." }, { role: "user", content: "How long do refunds take?" } ]; console.log(JSON.stringify(lookupOrGenerate(cache, fixedKey("mock-mini", messagesV1), () => "Refunds take 10 days."))); console.log(JSON.stringify(lookupOrGenerate(cache, fixedKey("mock-mini", messagesV2), () => "Refunds take 5 days."))); // The original brokenKey dropped the system message, so both policy // versions collapsed to one key and the second caller received version 1's // stale answer from the cache. Serializing the full messages array in // fixedKey gives each version its own entry, so the second call misses and // generates "Refunds take 5 days." as expected.Authored expected output: {"source":"model","answer":"Refunds take 10 days."} {"source":"model","answer":"Refunds take 5 days."}
The defect is an under-specified key: anything that determines the output must be in the key, and the system message determines this output. The fix serializes the full messages array, which is the cacheKey rule from the lesson body; corpus versions generalize the same fix in the capstone.
Exercise 5Explain
Knowledge check: which request is safest to cache?
starter.text// Choose the correct option.Reveal the reference answer
reference.textA temperature 0 extraction over a fixed public document set, with a corpus version included in the key. Deterministic generation makes a fresh call redundant, shared inputs make one stored answer correct for every caller, and the corpus version in the key invalidates stored answers when the content changes.Authored expected output: Temperature 0 over fixed shared inputs, with a corpus version in the key
The other options embed personalization, nondeterminism or staleness hazards. The three safe-to-cache conditions from the body are the checklist to apply.
Common misconceptions
#- Myth: caching model responses is unsafe by default. Fact: with temperature 0, a full-prompt key and a TTL matched to content freshness, shared deterministic requests are cacheable; personalization and staleness define the boundary.
- Myth: a cache hit is always equivalent to a fresh call. Fact: it is equivalent only if the key captures everything that determines the output, including model, parameters and the exact prompt content.
- Myth: streaming makes generation faster. Fact: streaming improves perceived latency by delivering the first token early; total generation time is unchanged.
Follow-up practice
#- ai-engineering-observability-and-logging
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.