Caching PatternsLesson 3.1
Cache-aside pattern: how to implement read-through caching in Node.js
cache-aside pattern, cache miss, cache hit, read-through vs write-through, TTL strategy, cache stampede risk, stale data tradeoff
Cache-aside (lazy loading)
Cache-aside is the most common caching pattern. Your application code manages the cache manually: check Redis first, fetch from the database on a miss, then populate Redis.
Implementation in Node.js
const redis = require('redis');
const client = redis.createClient();
async function getUser(userId) {
const cacheKey = `user:${userId}`;
// 1. Check cache
const cached = await client.get(cacheKey);
if (cached) return JSON.parse(cached); // cache hit
// 2. Cache miss — fetch from DB
const user = await db.query('SELECT * FROM users WHERE id=$1', [userId]);
// 3. Populate cache with TTL
await client.setEx(cacheKey, 300, JSON.stringify(user));
return user;
}Tradeoffs
Cache-aside is simple and only caches what is actually requested. The downside is the first request after a cache miss is slow. Under high traffic, many concurrent misses for the same key can hammer the database simultaneously — this is called a cache stampede. Mitigate it with a mutex lock (covered in Module 5) or probabilistic early expiration.
Always set a TTL. A cache without TTLs will eventually serve stale data indefinitely.
