Node.js › Caching
How would you cache the result of a database query in Node.js while ensuring the cache is properly invalidated when the underlying data changes?
IntermediateAnswer
The cache-aside pattern is combined with an explicit invalidation step triggered by any write to the same data -- whenever a record is updated or deleted, the corresponding cache key(s) are deleted immediately rather than waiting for TTL expiration, so the next read repopulates the cache with fresh data.
async function updateUser(id, data) {
await db.users.update(id, data);
await redis.del(`user:${id}`);
}
async function getUser(id) {
const cached = await redis.get(`user:${id}`);
if (cached) return JSON.parse(cached);
const user = await db.users.findById(id);
await redis.set(`user:${id}`, JSON.stringify(user), { EX: 3600 });
return user;
}Real-world example A user-profile service deletes a user's cache entry every time their profile is updated, ensuring subsequent reads always reflect the latest data immediately rather than serving a stale cached profile for up to an hour.