Chapter 10: Caching Strategies
Chapter 10 of 15
Chapter 10: Caching Strategies
10.1 Redis Caching
Redis is an in-memory data store used for caching, session storage, and real-time analytics.
const redis = require('redis');
const client = redis.createClient();
await client.connect();
// Set cache
await client.set('user:1', JSON.stringify(userData), {
EX: 3600 // Expire after 1 hour
});
// Get cache
const cached = await client.get('user:1');
if (cached) {
return JSON.parse(cached);
}
// Cache with fallback
async function getCachedUser(userId) {
const cacheKey = `user:${userId}`;
const cached = await client.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
const user = await db.getUser(userId);
await client.setEx(cacheKey, 3600, JSON.stringify(user));
return user;
}
10.2 Cache Patterns
Cache-Aside (Lazy Loading):
// Application checks cache first
async function getData(key) {
let data = await cache.get(key);
if (!data) {
data = await database.get(key);
await cache.set(key, data);
}
return data;
}
Write-Through:
// Write to cache and database simultaneously
async function updateData(key, value) {
await database.set(key, value);
await cache.set(key, value);
}
10.3 Cache Invalidation
// Invalidate on update
async function updateUser(userId, data) {
await db.updateUser(userId, data);
await cache.del(`user:${userId}`);
// Or update cache
await cache.set(`user:${userId}`, data);
}