Cache-aside and invalidation
Local baseline: Node.js 22.16.0. Dependency-free application model; no external service execution. No third-party packages or external connections.
Try the local example
const db=new Map([['b1','First']]);const cache=new Map();let reads=0;function read(id){if(cache.has(id))return cache.get(id);reads++;const value=db.get(id)??null;if(value!==null)cache.set(id,value);return value;}console.log(read('b1'));db.set('b1','Second');console.log(read('b1'));cache.delete('b1');console.log(read('b1'));console.log(reads);Run node main.mjs in a disposable directory with the files shown. Expected standard output:
FirstFirstSecond2How it works
In this model a map represents the database and another map the cache. A direct source write leaves the old cached value until deletion. In real systems a concurrent miss can fetch old data just before an update and populate the cache after invalidation. Use bounded TTL, versioned data or a coordinated invalidation strategy appropriate to the consistency requirement. Negative caching can reduce repeated misses but must expire and distinguish not found from an upstream failure. Redis failure should not trigger unlimited load on the source.
Integration example — staged
Static candidate only. Exact package and server versions, dependency/advisory review, integration and compilation NOT RUN. Use only a reviewed disposable fixture; no real connection settings.
// Partial cache-aside repository; authorized tenant and approved cache/db adapters.export async function readBook(cache,repo,tenant,id){ const key='bm:v6:book:'+JSON.stringify([tenant,id]); const cached=await cache.get(key); if(cached!==null)return JSON.parse(cached); const book=await repo.find(tenant,id); if(book!==null)await cache.set(key,JSON.stringify(book),{EX:30}); return book;}Minimal success-path illustration only; production needs cache-failure policy and stale-fill protection. NOT RUN.
Common mistake
Do not assume deletion makes a distributed cache immediately consistent. Invalidation must follow a committed change and account for races and failure.
Practice
Simulate two reads before and after a write. Count source reads and explain the stale result before invalidation.
Documentation: primary source. Candidate lookup: node-cache-aside-and-invalidation-lookup. Prerequisite: node-redis-keys-and-ttl (platform route unverified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cache-aside and invalidation — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
What is the authoritative value in this example?
When should invalidation follow a source write?
What can happen during a concurrent cache fill?