Caching Patterns
Cache-aside, write-through, and read-through
Skills taught: redis.caching
Cache-Aside (Lazy Loading)
The most common pattern. The application is responsible for populating the cache: check Redis first, fetch from the DB on a miss, and store the result in Redis for future requests.
async function getUser(id) {
const key = `user:${id}`;
// 1. Check cache
const cached = await redis.get(key);
if (cached) {
return JSON.parse(cached); // cache HIT
}
// 2. Cache MISS — load from database
const user = await db.users.findById(id);
if (!user) return null;
// 3. Populate cache with TTL
await redis.set(key, JSON.stringify(user), 'EX', 300); // 5 minutes
return user;
}
- Cache Miss
- When the requested data is not in the cache and must be fetched from the original source (database, API, or computed). A miss triggers cache population.
Write-Through
Every write to the database also writes to the cache synchronously. The cache is always up to date, but writes are slower (two writes instead of one).
async function updateUser(id, data) {
// 1. Write to database (source of truth)
const updated = await db.users.update(id, data);
// 2. Write to cache simultaneously
await redis.set(`user:${id}`, JSON.stringify(updated), 'EX', 300);
return updated;
}
Cache Invalidation
Instead of write-through, some patterns simply invalidate (delete) the cached entry on update. The next read will trigger a fresh cache-aside fetch.
async function updateUser(id, data) {
// Update DB
const updated = await db.users.update(id, data);
// Invalidate cache — next read will be a miss and re-populate
await redis.del(`user:${id}`);
return updated;
}
// For related cache entries, use a pattern
async function invalidateUserCaches(id) {
// Pipeline multiple deletes
const pipeline = redis.pipeline();
pipeline.del(`user:${id}`);
pipeline.del(`user:${id}:profile`);
pipeline.del(`user:${id}:permissions`);
await pipeline.exec();
}
Cache Stampede Prevention
When a popular cache entry expires, hundreds of requests simultaneously miss and all hit the database at once. This is a cache stampede (thundering herd). Prevent it with a distributed lock.
async function getWithLock(key, ttl, fetchFn) {
// Check cache
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
// Try to acquire lock
const lockKey = `lock:${key}`;
const acquired = await redis.set(lockKey, '1', 'NX', 'EX', 10);
if (!acquired) {
// Another worker is recomputing — wait and retry
await new Promise(r => setTimeout(r, 100));
return getWithLock(key, ttl, fetchFn);
}
try {
// Recheck cache after acquiring lock
const rechecked = await redis.get(key);
if (rechecked) return JSON.parse(rechecked);
const value = await fetchFn();
await redis.set(key, JSON.stringify(value), 'EX', ttl);
return value;
} finally {
await redis.del(lockKey);
}
}
Cache-Aside vs Write-Through
- Cache-Aside: App populates cache on miss
- Write-Through: Cache updated on every write
Tip: Always set a TTL on cached values. Without a TTL, stale data lives forever and memory fills up. A TTL of 5 minutes is a safe default for most application caches.
Frequently Asked Questions
What is cache stampede?
When many requests all miss the cache simultaneously and all hit the database at once. Prevent with a distributed mutex (SETNX), probabilistic early expiry, or background refresh.
How do I handle cache aside when the DB query is expensive?
Use a distributed lock (SETNX) so only one request recomputes while others wait. This is the 'read-through with locking' pattern.
Should I cache null values?
Yes — cache a sentinel value (e.g. empty string or 'NULL') with a short TTL to prevent repeated DB hits for non-existent entities. This is called 'negative caching'.