What are the common caching patterns with Redis (Cache-Aside, Write-Through, Write-Behind)?
1. Cache-Aside (Lazy Loading): The application first checks Redis. On cache hit, it returns the data. On cache miss, it reads from the primary database, writes the result to Redis with a TTL, and returns. Most popular pattern. 2. Write-Through: The application writes to the cache and the primary database synchronously. Guarantees cache consistency at the cost of higher write latency. 3. Write-Behind (Write-Back): The application writes directly to Redis, and an asynchronous worker process batches and writes updates to the database in the background. High write throughput, but risks data loss on sudden crashes.
async function getUserProfile(userId) {
const cacheKey = `user:${userId}`;
// 1. Check Redis cache
const cached = await redis.get(cacheKey);
if (cached) return JSON.parse(cached);
// 2. Fallback to SQL Database on cache miss
const user = await db.users.findById(userId);
// 3. Populate cache with 1-hour TTL
if (user) {
await redis.set(cacheKey, JSON.stringify(user), "EX", 3600);
}
return user;
}Cache-Aside ensures that only frequently accessed users occupy RAM. The 3600-second TTL prevents stale data from persisting indefinitely if updates happen outside the app.
Ready for Pub/Sub & Streams?
Take a quick test to evaluate yourself, or move straight to the next module.