5. Caching Strategies & Patterns
Building High-Performance Caching Layers
Caching is one of the most common and powerful Redis use cases. This module covers caching strategies, cache invalidation, and cache patterns. You'll learn to reduce database load, improve application performance, and build scalable systems with Redis caching.
The key to caching is deciding what to cache and when to invalidate. Cache-aside is the most common pattern — the application checks the cache first, then the database. Read-through and write-through provide automatic caching. Write-behind enables async writes. Cache invalidation is the hardest problem — use TTLs for automatic expiration, manual invalidation for immediate updates, or versioning for safe updates. Understanding caching patterns is essential for building high-performance applications.
Redis is ideal for caching because it's fast, supports TTL, and can be shared across multiple servers. Redis caching can reduce database load by 80-90% in many applications, dramatically improving response times. This module covers each caching pattern in depth with implementation examples and best practices.
Cache-Aside Pattern
Cache-aside is the most common caching pattern. The application checks the cache first. If data is found (cache hit), it's returned. If not (cache miss), the application fetches from the database and caches it. This pattern is simple and flexible. Use cache-aside for read-heavy workloads. Implement with a TTL to automatically expire data. Cache-aside reduces database load while maintaining data freshness.
The cache-aside pattern is also called lazy loading because data is loaded into the cache only when requested. This ensures that only frequently accessed data is cached, optimizing memory usage. However, cache-aside requires careful invalidation — when data is updated, the cache must be invalidated to prevent stale data. Implement invalidation on writes by deleting the cache key.
// Cache-aside pattern implementation async function getUser(userId) { const cacheKey = `user:${userId}`; // 1. Check cache const cached = await redis.get(cacheKey); if (cached) { return JSON.parse(cached); } // 2. Fetch from database (cache miss) const user = await db.users.findById(userId); if (!user) return null; // 3. Cache with TTL (1 hour) await redis.setex(cacheKey, 3600, JSON.stringify(user)); return user; } // Update with cache invalidation async function updateUser(userId, data) { const cacheKey = `user:${userId}`; // 1. Update database const user = await db.users.update(userId, data); // 2. Invalidate cache (delete the key) await redis.del(cacheKey); return user; }
Read-Through and Write-Through
Read-through caching automatically loads data into the cache when it's accessed. The cache library handles the database fetch on cache miss. Write-through caching writes data to both the cache and the database simultaneously. These patterns simplify application code but require more infrastructure. Use read-through for transparent caching. Use write-through for consistency.
Read-through is useful when you want to abstract caching from your application code. The cache library handles the complexity of fetching from the database and populating the cache. Write-through ensures cache and database stay in sync, but it adds latency to writes because both operations must complete.
// Read-through cache abstraction class ReadThroughCache { async get(key, fetchFn) { const cached = await redis.get(key); if (cached) return JSON.parse(cached); const data = await fetchFn(); await redis.setex(key, 3600, JSON.stringify(data)); return data; } } // Write-through cache class WriteThroughCache { async set(key, value, saveFn) { // Write to database first await saveFn(value); // Then write to cache await redis.setex(key, 3600, JSON.stringify(value)); } }
Cache Invalidation Strategies
Cache invalidation is the hardest part of caching — it's famously one of the two hard problems in computer science (along with naming things). Choose the right strategy for your use case. TTL provides automatic expiration and is simple to implement. Manual invalidation provides immediate consistency but requires careful code management. Versioning allows safe updates with cache version keys. Use cache stamps to prevent stampedes.
Consider your data's volatility when choosing a strategy. User profiles change infrequently, so a TTL of 1-24 hours is appropriate. Inventory data changes frequently, so a shorter TTL or manual invalidation is better. For critical data, use manual invalidation to ensure consistency. For less critical data, TTL is sufficient.
- TTL (Time-To-Live): Automatic expiration after a set time. Simple and reliable for most use cases.
- Manual Invalidation: Explicitly delete cached data on updates. Guarantees consistency but requires more code.
- Versioning: Use version keys to invalidate caches safely without deleting keys.
- Cache Stampede: Prevent multiple requests from regenerating cache simultaneously with locking.
- Lazy Invalidation: Invalidate cache only when data changes, not on every access.
Knowledge Check
Ready to test your understanding of 5. Caching Strategies & Patterns?