Architecture Intermediate
Caching Strategies — Where and How to Cache¶
CachingRedisPerformance 3 min read
Cache-aside, write-through, write-behind and cache invalidation. A complete guide.
Cache-Aside¶
async function getUser(id) {
let user = await redis.get(\`user:\${id}\`);
if (user) return JSON.parse(user); // Cache hit
user = await db.query('SELECT * FROM users WHERE id = $1', [id]);
await redis.setex(\`user:\${id}\`, 3600, JSON.stringify(user));
return user;
}
Strategies¶
- Cache-Aside (Lazy Loading) — read from cache, on miss load from DB
- Write-Through — write through cache to DB, cache always up to date
- Write-Behind — write to cache, async to DB (faster, riskier)
Invalidation¶
- TTL — cache expires after a set time
- Event-driven — publish an invalidation event when data changes
- Version-based — cache key contains a version
Summary¶
Cache-aside is the safest starting point. Always have an invalidation strategy. Cache is an optimization, not a data source.
Need Help with Implementation?¶
Our team has experience designing and implementing modern architectures. We’re happy to help.