HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 62“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
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:
Name the result cache, the embedding cache, the progress hint, and the CDN asset cache as different decisions.
Build a result key from kind, organization, prompt version, profile, learner-or-dash, and a content hash.
Reject a key whose hash still looks like a raw prompt or an email.
Reject a personalized result that has no learner id.
Keep a Northwind glossary hit from satisfying a Contoso lookup.
Share a catalog embedding across tenants only when the scope is catalog, and keep private notes on tenant scope.
Treat a prompt-version change as a miss even when the clock has not expired.
Apply a TTL so a progress hint cannot outlive a completion write by more than a minute.
Collapse a stampede so one filler calls the model and the rest wait.
Send private, no-store for tutor and progress responses, and a long immutable cache header for hashed assets only.
Invalidate by version and by content hash, and sweep old versions off the request path.
Record a cache hit on the lesson 59 span as a boolean, without logging the question.
Skip recordCharge on a hit, and still charge a miss once.
Explain why a CDN cache of personalized tutor output is a tenant incident even when the API authorization is correct.
Node.js 20 or newer and node:test. No Redis account and no provider key.
Detailed Core Concepts
Four places, four lifetimes
Store
Holds
Key includes
Lifetime
Must not hold
Result cache
Glossary or catalog completion
Organization, prompt version, profile, content hash, learner if personalized
TTL plus version
Another tenant's answer, a provider key
Embedding cache
Vector for bytes you already embedded
Scope, embedding model, content hash
Until hash or model changes
A private note under catalog
Progress hint
A learner's completion row
Organization, learner, resource
Tens of seconds
A shared CDN entry
CDN
Hashed JS, CSS, images
Content hash in the URL
Immutable until the next digest
Tutor 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.
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:
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
-> 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
exportinterfaceResultCacheInput{
organizationId:string;
promptVersion:string;
profile:string;
/** Hash of the normalized question and allowed chunk ids. Not the question text. */
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.
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.
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
Event
Learner or worker sees
System does
Glossary hit, fresh
The cached sentence
cacheHit: true, no provider call, no charge
Hit, old prompt version
No stale sentence
Delete and miss
Miss, lock won
One stored answer
Charge once, then publish
Miss, lock lost
The published answer, or unavailable if the filler failed
No second provider call
Personalized without learner id
No cache write
personalized_without_learner. The lab refuses the key
Raw question passed as the hash
No cache write
raw_prompt
Contoso key read as Northwind
A miss
The value stays. The caller does not receive it
Private note marked catalog by mistake
No catalog write
Scope comes from ingestion. The call uses tenant scope
Provider down during fill
Typed unavailable
releaseFill so a later click can try
CDN request for a tutor URL
The API, not a cached body
private, no-store. The CDN caches assets only
Tenant purge
Product rows gone
The 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.
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.
Draw the four stores and which request may touch each.
Implement resultKey, embeddingKey, readCache, isFresh, claimFill, and cacheControl with the tests in this lesson, plus the two extra tests named above.
On a hit, set cacheHit on the span and skip recordCharge. On a miss that wins the lock, charge once.
Delete a progress hint when a completion is written. Show the 60-second TTL as the backstop.
State the header for an asset, a progress read, and a tutor response.
Document tenant purge: delete result:{org}:, embedding:tenant:{org}:, and progress:{org}: with the product rows. Catalog embeddings stay.
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
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.
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.
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.
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.
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.
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}.
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.
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.
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.
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.