AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 62

    Caching Strategies for AI and Full-Stack Systems

    After the ledger in LLM Cost, Latency and Performance Engineering started telling the truth, Northwind's glossary line was still the loud one.

    Course progress0%
    Focus
    16 guided sections
    Practice signal
    Concept-first lesson
    Career prep
    Foundation builder

    AI-Powered Full Stack Development · Lesson 62 · Production AI Products, Capstones and Career Readiness

    Lesson Overview

    After the ledger in LLM Cost, Latency and Performance Engineering started telling the truth, Northwind's glossary line was still the loud one. Two hundred learners asked "what is a primary key" in a week. Each click selected draft-small, streamed a fresh completion, and added units. The bytes of the course article had not changed. The prompt version had not changed. The answer did not depend on Priya's progress. The same week, the embed_document job from Background Jobs, Queues and Event-Driven AI Processing recomputed a vector for a chunk whose text was identical to the previous attempt, because a retry looked like new work to the embedding client. A third cache, added on the CDN to "make the tutor fast," keyed only on the lesson URL. Omar received Priya's explanation. A Contoso learner, on a shared cache box someone had stood up in front of both tenants, received a Northwind sentence.

    Caching here is three stores with three keys, plus one place you do not cache. A result cache stores a model completion for a canonical glossary or catalog question, scoped to one organization, one prompt version, and one profile. An embedding cache stores a vector for a content hash and an embedding model, scoped to the catalog when the chunk is public course text and scoped to the organization when the chunk is a private note. A progress cache is a short private hint for a learner's own row. The CDN continues to store hashed player assets only, which is the rule from Cloud Deployment, Serverless and Managed Runtime Choices. Personalized tutor drafts, and anything that includes a learner's progress or a private note, are private, no-store.

    A cache hit is a skipped provider call. It is also a stale answer if the prompt version moved, and a tenant leak if the key forgot organizationId. The key is a hash of the canonical input, not the raw question, so the cache store is not a second transcript log.

    Planning assumptions:

    • Glossary and other catalog answers may be shared among learners inside one organization. They may not be shared across Northwind and Contoso, even when the question text matches. A future explicit catalog scope for results is a reviewed flag, not the default.
    • Personalized answers include the learner id in the key. A personalized flag with no learner id is rejected.
    • Prompt-version mismatch is a miss. Time-to-live is 24 hours for glossary results in the lab and 60 seconds for progress hints. Embeddings live until the content hash or the embedding model id changes.
    • The lab store is a Map. Production may be Redis or a Postgres table. The key function does not change when the store does.
    • Stampede protection is a single-flight lock per key. Waiters do not each call the model.
    • No provider key is stored as a value. No raw prompt is stored as a key. Tests use hashes that look like q_primary_key and chk_window_v3, not a learner email.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Name the result cache, the embedding cache, the progress hint, and the CDN asset cache as different decisions.
    2. Build a result key from kind, organization, prompt version, profile, learner-or-dash, and a content hash.
    3. Reject a key whose hash still looks like a raw prompt or an email.
    4. Reject a personalized result that has no learner id.
    5. Keep a Northwind glossary hit from satisfying a Contoso lookup.
    6. Share a catalog embedding across tenants only when the scope is catalog, and keep private notes on tenant scope.
    7. Treat a prompt-version change as a miss even when the clock has not expired.
    8. Apply a TTL so a progress hint cannot outlive a completion write by more than a minute.
    9. Collapse a stampede so one filler calls the model and the rest wait.
    10. Send private, no-store for tutor and progress responses, and a long immutable cache header for hashed assets only.
    11. Invalidate by version and by content hash, and sweep old versions off the request path.
    12. Record a cache hit on the lesson 59 span as a boolean, without logging the question.
    13. Skip recordCharge on a hit, and still charge a miss once.
    14. Explain why a CDN cache of personalized tutor output is a tenant incident even when the API authorization is correct.

    Prerequisites

    Detailed Core Concepts

    Four places, four lifetimes

    StoreHoldsKey includesLifetimeMust not hold
    Result cacheGlossary or catalog completionOrganization, prompt version, profile, content hash, learner if personalizedTTL plus versionAnother tenant's answer, a provider key
    Embedding cacheVector for bytes you already embeddedScope, embedding model, content hashUntil hash or model changesA private note under catalog
    Progress hintA learner's completion rowOrganization, learner, resourceTens of secondsA shared CDN entry
    CDNHashed JS, CSS, imagesContent hash in the URLImmutable until the next digestTutor drafts, progress JSON, sessions

    The result cache cuts tokens. The embedding cache cuts a job that is pure computation over unchanged bytes. The progress hint cuts a hot Postgres read. The CDN cuts origin reads for files that are the same for every tenant. Mixing those jobs in one box is how Omar saw Priya's draft.

    The result key is a contract

    Canonical form, joined with :, is:

    text
    result:{organizationId}:{promptVersion}:{profile}:{learnerId|-}:{contentHash}

    contentHash is a hash of the normalized question plus the ids of the retrieved chunks the model is allowed to see. The raw question is not in the key. Normalization is your function: trim, collapse whitespace, and one case rule. Two learners who differ by a trailing space should hit. Two learners who retrieved different chunk ids should miss, because the grounded answer is not the same answer. Put the chunk ids inside the hash. Do not append the chunk text to the key.

    learnerId is - when personalized is false. Glossary keys inside Northwind then match for Priya and Omar. The organization is still in the key, so Contoso's identical question is a different entry. When personalized is true, the learner id is required. A missing learner id returns personalized_without_learner rather than building a key that every personalized caller would share.

    A hash that contains @ or whitespace, or is shorter than 8 characters, is rejected as raw_prompt. That check is a tripwire for a caller that passed the question through. It is not a privacy proof by itself. A short question run through a fast hash can still be guessed. Do not log the preimage next to the key. The operational span stores cacheHit and questionChars, which lesson 59 already allowed as a length.

    Embeddings: catalog versus tenant

    Public course chunks are identical for every customer. Caching them once under catalog is an honest optimization. The key is:

    text
    embedding:catalog:{embeddingModel}:{contentHash}

    Northwind's private instructor note is not catalog text, even when the sentence resembles a course sentence. Its key is:

    text
    embedding:tenant:{organizationId}:{embeddingModel}:{contentHash}

    readCache returns a value only when the key's scope matches the caller's right to see it. A catalog key may be read by any organization. A tenant key may be read only when the key contains that organization. A Northwind caller who presents a Contoso tenant key gets a miss even if the map holds the value. The caller computes nothing from the other tenant's vector and learns nothing about it.

    Changing the embedding model id changes the key. Vectors from model A must not be served as model B. A content edit changes the hash. The old vector expires by disuse. You may delete by prefix when a tenant is purged. Lesson 52's purge includes this store. A cache that ignores the purge keeps a private note after the product row is gone.

    Freshness

    isFresh fails when promptVersion differs, and fails when nowMs - storedAtMs is past ttlMs. Embeddings pass a very large TTL in the lab and rely on the hash. Progress hints use 60 seconds so a completion write is visible on the next navigation even if an explicit delete was missed. Explicit delete on write is still required. TTL is the backstop.

    A prompt-version bump is the invalidation to prefer for result caches. The version sits inside the key, so old entries stop being read. A weekly sweep deletes unread versions off the request path. Deleting every key for an organization on each small edit is correct and expensive. Deleting nothing is how tutor-answer-v3 and tutor-answer-v4 alternate and a learner quotes the old policy.

    Stampede

    When a glossary question is cold, two hundred parallel misses will each call the model and write the same value. You paid the bill the cache was supposed to remove, once per waiter. claimFill inserts the key into a lock set. The first caller receives fill and calls the model. Others receive wait and must not call the model. They retry the read after the filler publishes. This lab does not fall through to the provider on wait.

    Release the lock in a finally, including when the provider returns unavailable. A lock that sticks until process restart turns a short outage into a permanent miss that also never refills. Production uses a store lock with a TTL, the same shape as the job lease, so a dead filler does not hold the key forever.

    HTTP cache headers are part of the design

    cacheControl returns:

    • public, max-age=31536000, immutable for asset
    • private, no-store for progress and tutor

    Assets are safe to mark immutable because the URL includes the digest. A tutor URL does not. no-store keeps a shared computer and an intermediate cache from replaying a draft. Lesson 58 already kept personalized drafts off the CDN. This function is the header a test can see.

    Architecture and Request Flow

    flowchart TB
      subgraph edge [Edge]
        Browser[Browser]
        CDN[CDN hashed assets]
      end
    
      subgraph api [API]
        Key[cacheKey]
        Read[readCache with org fence]
        Lock[claimFill]
        Model[Model or embedder on miss]
      end
    
      subgraph store [Cache store]
        Results[(Result entries)]
        Vectors[(Embedding entries)]
      end
    
      Browser --> CDN
      Browser -->|session, no-store on tutor| Key
      Key --> Read
      Read -->|hit| Browser
      Read -->|miss| Lock
      Lock -->|wait| Read
      Lock -->|fill| Model
      Model --> Results
      Model --> Vectors
    text
    Omar asks the glossary question Priya asked
    -> key result:northwind:tutor-answer-v3:draft-small:-:q_primary_key
    -> hit: return the cached completion, cacheHit true, no recordCharge
    Priya's first ask of the day
    -> miss
    -> claimFill returns fill
    -> one model call, one charge, store the value with prompt version and time
    -> waiters read the value and do not call the model
    Contoso asks the same question
    -> key contains contoso
    -> Northwind's entry is not a hit
    Private note embed
    -> embedding:tenant:northwind:{model}:{hash}
    -> catalog scope is rejected for that chunk
    Personalized tutor with progress
    -> personalized true requires lrn_priya on the key
    -> response header private, no-store
    -> CDN is not on this path

    Trust boundary: the cache store sits with private data. It is not the CDN. The server builds the key from the session organization, the server-side prompt version, and the server-side hash. The browser does not submit a key.

    Failure point: a read API that accepts a raw key from the client. That is a cross-tenant read with extra steps.

    Step-by-step Implementation

    Package: packages/cache/. Pure key and freshness functions. The map stands in for Redis or a table.

    Step 1: Key parts

    packages/cache/src/types.ts

    typescript
    export interface ResultCacheInput {
    organizationId: string;
    promptVersion: string;
    profile: string;
    /** Hash of the normalized question and allowed chunk ids. Not the question text. */
    contentHash: string;
    personalized: boolean;
    learnerId: string | null;
    }
    export interface EmbeddingCacheInput {
    scope: { type: "catalog" } | { type: "tenant"; organizationId: string };
    embeddingModel: string;
    contentHash: string;
    }
    export interface StoredResult {
    text: string;
    promptVersion: string;
    storedAtMs: number;
    }
    export type KeyFailure = "raw_prompt" | "personalized_without_learner" | "missing_tenant";

    text is the completion you are willing to show every learner who shares that key. For a Northwind glossary entry, that is a catalog sentence. Do not put a provider key, an email, or another learner's progress in text. If the draft contains those, it was personalized and it used the wrong key.

    Step 2: Build a key and read through the fence

    packages/cache/src/key.ts

    typescript
    import type { EmbeddingCacheInput, KeyFailure, ResultCacheInput } from "./types.js";
    function hashLooksRaw(hash: string): boolean {
    return hash.length < 8 || hash.includes("@") || /\s/.test(hash);
    }
    export function resultKey(input: ResultCacheInput): string | { code: KeyFailure } {
    if (hashLooksRaw(input.contentHash)) return { code: "raw_prompt" };
    if (input.organizationId.length === 0 || input.organizationId === "public") {
    return { code: "missing_tenant" };
    }
    if (input.personalized && (input.learnerId === null || input.learnerId.length === 0)) {
    return { code: "personalized_without_learner" };
    }
    const learner = input.personalized ? input.learnerId : "-";
    return ["result", input.organizationId, input.promptVersion, input.profile, learner, input.contentHash].join(
    ":",
    );
    }
    export function embeddingKey(input: EmbeddingCacheInput): string | { code: KeyFailure } {
    if (hashLooksRaw(input.contentHash)) return { code: "raw_prompt" };
    if (input.scope.type === "catalog") {
    return ["embedding", "catalog", input.embeddingModel, input.contentHash].join(":");
    }
    if (input.scope.organizationId.length === 0) return { code: "missing_tenant" };
    return ["embedding", "tenant", input.scope.organizationId, input.embeddingModel, input.contentHash].join(":");
    }
    export function progressKey(
    organizationId: string,
    learnerId: string,
    resourceId: string,
    ): string | { code: KeyFailure } {
    if (organizationId.length === 0 || learnerId.length === 0) return { code: "missing_tenant" };
    if (resourceId.includes("@")) return { code: "raw_prompt" };
    return ["progress", organizationId, learnerId, resourceId].join(":");
    }
    /**
    * Catalog embeddings are shared. Every other key must belong to organizationId.
    * A foreign key is a miss even when the map contains the value.
    */
    export function readCache<T>(store: Map<string, T>, key: string, organizationId: string): T | undefined {
    const catalog = key.startsWith("embedding:catalog:");
    const owns =
    key.startsWith(`result:${organizationId}:`) ||
    key.startsWith(`embedding:tenant:${organizationId}:`) ||
    key.startsWith(`progress:${organizationId}:`);
    if (!catalog && !owns) return undefined;
    return store.get(key);
    }

    Result hashes use the strict hashLooksRaw rule. Progress resource ids may be short (les_keys). An email in that field still fails.

    Step 3: Freshness, single flight, and headers

    packages/cache/src/fresh.ts

    typescript
    import type { StoredResult } from "./types.js";
    export function isFresh(
    entry: Pick<StoredResult, "promptVersion" | "storedAtMs">,
    current: { promptVersion: string; nowMs: number; ttlMs: number },
    ): boolean {
    if (entry.promptVersion !== current.promptVersion) return false;
    return current.nowMs - entry.storedAtMs < current.ttlMs;
    }
    export function claimFill(locks: Set<string>, key: string): "fill" | "wait" {
    if (locks.has(key)) return "wait";
    locks.add(key);
    return "fill";
    }
    export function releaseFill(locks: Set<string>, key: string): void {
    locks.delete(key);
    }
    export function cacheControl(kind: "asset" | "progress" | "tutor"): string {
    if (kind === "asset") return "public, max-age=31536000, immutable";
    return "private, no-store";
    }

    Glossary TTL in the lab is 86_400_000 milliseconds. Progress TTL is 60_000. Pass them from the caller so the helper has no hidden clock. On a hit that isFresh rejects, delete the entry and take the miss path.

    The handler's miss path:

    text
    claimFill
    fill -> call provider or embedder -> store -> releaseFill in finally
    wait -> do not call the provider -> read again
    hit and fresh -> return, set cacheHit, skip recordCharge

    A wait that still finds nothing, because the filler failed, returns the typed unavailable. It does not become a second filler unless it wins a new claimFill after releaseFill.

    Step 4: Run

    bash
    node --test packages/cache/src/key.test.ts packages/cache/src/fresh.test.ts

    No cache server is required. A later preview environment that creates one uses fixture text, stays private to that environment, and is deleted the same day. Production purge on tenant deletion includes this store.

    Security

    • Authentication. Cache reads happen after the session is resolved. No public endpoint accepts a key.
    • Authorization. readCache checks the organization embedded in the key against the session organization. Catalog embeddings are the shared exception, and only for chunks the ingestion pipeline marked public.
    • Least privilege. The API role can read and write keys for its organization. A purge job can delete a tenant prefix. The CDN role can read the asset bucket and cannot read the result cache.
    • Input validation. Raw prompts and emails are rejected as hashes. Personalized results require a learner id. organizationId of public is rejected for results so a shared glossary cannot appear by accident.
    • Secrets. Values are completions and vectors. Storing TEST_ONLY_MODEL_TOKEN or tlp_live_ in text fails review. Run the lesson 59 redactor on errors beside a miss. Do not attach those errors to the cached success value.
    • Tenant isolation. Northwind cannot read result:contoso:... or embedding:tenant:contoso:.... Identical question text does not collapse those keys.
    • Personalized data. A tutor draft that used Priya's progress is keyed by lrn_priya and sent no-store. It is not placed on the glossary key Omar shares.
    • Injection. Cached text is data you generated under the existing guards. Serving it does not re-open a tool. Do not store a tool call beside a glossary sentence. A poisoned chunk still passes the retrieval fence before its hash enters a key.

    Prompt version and profile are server-side. A client that sends promptVersion=tutor-answer-v1 to fetch an older policy is ignored. The server's current version is the only one that can hit.

    Error Handling

    EventLearner or worker seesSystem does
    Glossary hit, freshThe cached sentencecacheHit: true, no provider call, no charge
    Hit, old prompt versionNo stale sentenceDelete and miss
    Miss, lock wonOne stored answerCharge once, then publish
    Miss, lock lostThe published answer, or unavailable if the filler failedNo second provider call
    Personalized without learner idNo cache writepersonalized_without_learner. The lab refuses the key
    Raw question passed as the hashNo cache writeraw_prompt
    Contoso key read as NorthwindA missThe value stays. The caller does not receive it
    Private note marked catalog by mistakeNo catalog writeScope comes from ingestion. The call uses tenant scope
    Provider down during fillTyped unavailablereleaseFill so a later click can try
    CDN request for a tutor URLThe API, not a cached bodyprivate, no-store. The CDN caches assets only
    Tenant purgeProduct rows goneThe same job deletes the tenant prefixes in this store

    When the cache store is down, fall through to the model only if the ceiling and the allowance from lesson 60 still admit the call. If you cannot tell whether a hit exists, take a miss you can afford. Do not substitute another organization's entry. If the allowance is exhausted, return over_allowance.

    Testing

    packages/cache/src/key.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { embeddingKey, readCache, resultKey } from "./key.js";
    const glossary = {
    organizationId: "northwind",
    promptVersion: "tutor-answer-v3",
    profile: "draft-small",
    contentHash: "q_primary_key",
    personalized: false,
    learnerId: null,
    };
    test("shares a glossary key inside Northwind and not with Contoso", () => {
    const north = resultKey(glossary);
    const contoso = resultKey({ ...glossary, organizationId: "contoso" });
    assert.equal(typeof north, "string");
    assert.equal(typeof contoso, "string");
    assert.notEqual(north, contoso);
    if (typeof north !== "string" || typeof contoso !== "string") return;
    const store = new Map<string, string>([[north, "A primary key identifies a row."]]);
    assert.equal(readCache(store, north, "northwind"), "A primary key identifies a row.");
    assert.equal(readCache(store, north, "contoso"), undefined);
    assert.equal(readCache(store, contoso, "northwind"), undefined);
    });
    test("rejects a raw question and a personalized key with no learner", () => {
    assert.deepEqual(resultKey({ ...glossary, contentHash: "what is a primary key" }), {
    code: "raw_prompt",
    });
    assert.deepEqual(resultKey({ ...glossary, personalized: true, learnerId: null }), {
    code: "personalized_without_learner",
    });
    });
    test("keeps a private embedding off the catalog key", () => {
    const tenant = embeddingKey({
    scope: { type: "tenant", organizationId: "northwind" },
    embeddingModel: "embed-lab",
    contentHash: "chk_note_priya",
    });
    const catalog = embeddingKey({
    scope: { type: "catalog" },
    embeddingModel: "embed-lab",
    contentHash: "chk_window_v3",
    });
    assert.equal(typeof tenant, "string");
    assert.equal(typeof catalog, "string");
    if (typeof tenant !== "string" || typeof catalog !== "string") return;
    assert.equal(tenant.startsWith("embedding:tenant:northwind:"), true);
    const store = new Map<string, number[]>([
    [tenant, [0.1, 0.2]],
    [catalog, [0.3, 0.4]],
    ]);
    assert.equal(readCache(store, tenant, "contoso"), undefined);
    assert.deepEqual(readCache(store, catalog, "contoso"), [0.3, 0.4]);
    });

    packages/cache/src/fresh.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { cacheControl, claimFill, isFresh, releaseFill } from "./fresh.js";
    test("a new prompt version is a miss inside the TTL", () => {
    const fresh = isFresh(
    { promptVersion: "tutor-answer-v3", storedAtMs: 0 },
    { promptVersion: "tutor-answer-v4", nowMs: 1_000, ttlMs: 86_400_000 },
    );
    assert.equal(fresh, false);
    });
    test("a progress hint expires at 60 seconds", () => {
    const fresh = isFresh(
    { promptVersion: "progress", storedAtMs: 0 },
    { promptVersion: "progress", nowMs: 60_000, ttlMs: 60_000 },
    );
    assert.equal(fresh, false);
    });
    test("only the first caller fills", () => {
    const locks = new Set<string>();
    const key = "result:northwind:tutor-answer-v3:draft-small:-:q_primary_key";
    assert.equal(claimFill(locks, key), "fill");
    assert.equal(claimFill(locks, key), "wait");
    releaseFill(locks, key);
    assert.equal(claimFill(locks, key), "fill");
    });
    test("tutor responses are not CDN-cacheable", () => {
    assert.equal(cacheControl("asset").includes("immutable"), true);
    assert.equal(cacheControl("tutor"), "private, no-store");
    assert.equal(cacheControl("progress"), "private, no-store");
    });

    Add a test that a personalized key for lrn_priya differs from lrn_omar and from the shared glossary key. Add a test that resultKey rejects organizationId: "public".

    Performance and Cost

    • A glossary hit skips unitsForCall. Two hundred identical Northwind asks become one charge plus a hash compare each. That is the unit cut lesson 60 deferred to this lesson.
    • Hash the normalized text. Do not embed the question in order to form the cache key. Embedding on the key path spends the work the cache exists to avoid. Embed on miss only.
    • Single flight is the cost control on a cold key. Without it, the first minute after a deploy restamps the bill at the full miss rate. Run claimFill before the provider call.
    • Progress hints at 60 seconds remove repeated reads while a learner sits on a lesson. They are not the source of truth. The completion write deletes the hint. TTL covers a missed delete.
    • Embedding hits on the worker shorten the job and the lease. They do not replace applyEffect. A retry skips the side effect, and it also skips the embedder when the hash hits.
    • Glossary values stay inside the output cap. Caching a full transcript stores personal data and large rows. Refuse to cache a completion over the cap.
    • Evict by version sweep and by tenant purge. Set a max entry count per organization in production and drop the least recently used glossary key. Do not drop catalog embeddings because one tenant is idle. They are shared.
    • Measure hit ratio with labels kind and profile. Leave tenant id and the hash off the metric. A falling glossary hit ratio after a prompt bump is expected for a day. A falling ratio with no version change means the key is unstable. Inspect normalization.
    • The CDN remains the right cache for the player bundle and the wrong cache for /tutor. Keep the header test in the API contract so a refactor cannot mark tutor JSON public.

    Illustrative ratio, not a quote: one glossary completion cached for a day inside Northwind replaces every later identical ask that week. An unchanged course chunk is embedded once per model id, not once per upload retry. Neither saving appears if the key omits the version or the log stores the raw question beside the hash.

    Knowledge Check

    1. What problem does this caching design solve?

    It removes repeated provider calls for the same Northwind glossary answer and repeated vectors for the same bytes, without serving that answer to Contoso or serving Priya's personalized draft to Omar. The CDN keeps assets. Tutor and progress responses are no-store. A prompt bump becomes a miss. A stampede becomes one fill.

    2. What alternatives exist, and when would you choose each?

    No cache fits low traffic and any answer whose inputs you cannot put in the key. A per-learner key fits personalized tutors. A per-organization glossary key fits catalog questions. A catalog embedding key fits public course chunks. A tenant embedding key fits private notes. A browser or CDN cache fits hashed assets. A CDN for API JSON fits a public document that is identical for everyone and does not fit this tutor. A provider-side prompt cache, if you enable one later, has its own retention rules and does not replace the tenant key in your store.

    3. Which data, identity, and trust boundaries matter?

    The session organization is part of every private key. The server builds the key. Catalog scope is an ingestion decision. Personalized results require a learner id. Values contain no secrets. The CDN never sees tutor bodies. A purge deletes the tenant prefix. Spans record cacheHit, not the question.

    4. What can fail, and how should the system respond?

    A stale prompt version misses. A raw prompt hash is rejected. A personalized key without a learner is rejected. A cross-tenant read misses. A filler failure releases the lock and returns unavailable. A down cache falls through only if the allowance and the ceiling allow a provider call. A tutor response sends no-store. A private note uses the tenant embedding key.

    5. How would you test quality, security, performance, and cost?

    Unit tests cover the Northwind and Contoso split, the read fence, raw hashes, personalized keys, embedding scope, TTL, prompt version, single flight, and cache headers. Security review checks that the client cannot submit a key and that purge deletes the prefix. Performance review checks single flight under parallel misses. Cost review confirms hits do not call recordCharge and misses charge once.

    Hands-on Assignment

    Lab note. Use the hash tokens in the tests. Do not put a question corpus, an email, or a provider key in the cache package.

    Problem. Serve Omar's repeat of Priya's glossary question from Northwind's result cache, refuse that entry for Contoso, and keep a private note's vector off the catalog.

    Tasks.

    1. Draw the four stores and which request may touch each.
    2. Implement resultKey, embeddingKey, readCache, isFresh, claimFill, and cacheControl with the tests in this lesson, plus the two extra tests named above.
    3. On a hit, set cacheHit on the span and skip recordCharge. On a miss that wins the lock, charge once.
    4. Delete a progress hint when a completion is written. Show the 60-second TTL as the backstop.
    5. State the header for an asset, a progress read, and a tutor response.
    6. Document tenant purge: delete result:{org}:, embedding:tenant:{org}:, and progress:{org}: with the product rows. Catalog embeddings stay.
    7. List what you will not cache: personalized drafts on the CDN, secrets, and raw prompts as keys.

    Deliverable. Diagram, source with no secrets, test output, the header table, and a trade-off note on per-organization glossary entries versus one global catalog entry for public course text.

    Challenge. Launch week sends the same glossary question from both tenants, and a prompt bump ships at noon. Explain hit ratio, single flight, and why Contoso still misses after Northwind has filled. A private Northwind note shares several words with a catalog chunk. Explain why the embedding keys still differ. A request to cache Priya's full tutor thread on the CDN for speed is refused. Name the header and the key rule that make the refusal hold.

    Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security, privacy, and responsible AI 20%. Testing, reliability, and observability 20%. Documentation and decision rationale 15%.

    Common Mistakes

    1. Keying the CDN on the lesson URL. Symptom: Omar sees Priya's draft, or Contoso sees a Northwind sentence. Cause: a shared cache in front of a personalized response. Fix: CDN for hashed assets. Tutor sends private, no-store.
    2. Omitting the organization on a result key. Symptom: identical questions cross tenants. Cause: the key was the question hash alone. Fix: organizationId in the key, and readCache checks it again.
    3. Caching a personalized draft under the glossary key. Symptom: one learner's progress appears in another learner's explanation. Cause: personalized was ignored. Fix: require learnerId, and keep those entries off the shared - key.
    4. Using the raw question as the key. Symptom: the cache store is a transcript index. Cause: concatenation felt easier than hashing. Fix: raw_prompt rejection. Hash the normalized text plus chunk ids. Log cacheHit and length.
    5. Serving across a prompt bump. Symptom: the new template is deployed and learners still read the old policy. Cause: TTL was the only invalidation. Fix: version inside the key and inside isFresh.
    6. Marking a private note as catalog. Symptom: a Northwind note's vector is readable as a public embedding. Cause: scope was inferred from similar words. Fix: scope comes from ingestion. Tenant notes stay on embedding:tenant:{org}.
    7. A stampede on a cold key. Symptom: the bill for a popular question equals the miss count. Cause: every waiter called the model. Fix: claimFill, and releaseFill in finally.
    8. A lock that is never released. Symptom: the question stays a miss until restart. Cause: the provider threw before release. Fix: finally, plus a lock TTL in the shared store.
    9. Reading another tenant when the cache is down. Symptom: a neighbor answer crosses organizations. Cause: the fallback skipped the fence. Fix: miss to the model under the caller's allowance, or fail the request.
    10. Forgetting the cache on purge. Symptom: a deleted learner's draft or note vector remains. Cause: purge updated Postgres and skipped the cache prefix. Fix: delete the three tenant prefixes in the lesson 52 job.

    Summary

    Caching is a set of keys with a tenant fence. TechLearningPro stores a Northwind glossary completion under organization, prompt version, profile, and a content hash, and will not return that entry to Contoso. Personalized drafts add the learner id and ship no-store. Public course embeddings may use catalog scope. Private notes stay on the tenant key. A prompt bump and a TTL keep entries fresh. Single flight keeps a cold key from calling the model once per waiter. Hits skip the ledger. The CDN still serves the player, not the tutor. Scaling and production readiness, next, asks these controls to hold together when launch traffic arrives.

    Next Lesson Preview

    Scaling, Resilience and Production Readiness puts the ceiling, the cache, the queue, and the model cap under one spike. You will decide how Northwind degrades when admission is busy, the glossary key is hot, and the worker lease is full, without moving Contoso's data or spending the allowance on a stampede.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.