Node.js › Caching
What are the main cache invalidation strategies (TTL, write-through, cache-aside), and when is each appropriate?
AdvancedAnswer
Time-to-live (TTL) expiration simply lets cached entries expire automatically after a fixed duration -- simple, but can serve stale data until expiration. Cache-aside (lazy loading) has the application check the cache first, falling back to the source and populating the cache on a miss -- flexible, but the first request after a miss pays the full latency cost. Write-through updates the cache synchronously every time the underlying data is written, keeping the cache always consistent at the cost of added write latency and complexity.
// Cache-aside pattern
async function getProduct(id) {
let product = await redis.get(`product:${id}`);
if (!product) {
product = await db.products.findById(id);
await redis.set(`product:${id}`, JSON.stringify(product), { EX: 600 });
}
return typeof product === 'string' ? JSON.parse(product) : product;
}
// Write-through: update cache and DB together on every write
async function updateProduct(id, data) {
await db.products.update(id, data);
await redis.set(`product:${id}`, JSON.stringify(data), { EX: 600 });
}Real-world example A pricing service uses write-through caching specifically for currency exchange rates (needing immediate consistency everywhere), but uses simple cache-aside with a short TTL for less critical, less frequently accessed product descriptions.