Caching with Redis
Caching reduces latency and database load by storing frequently accessed data in a fast key-value store. Redis is commonly used for application caching, distributed locks, counters, sessions, rate limiting, and ephemeral data.
A cache strategy must define expiration, invalidation, consistency expectations, and behavior when the cache is unavailable.
Cache-Aside Pattern
const cached = await redis.get(`user:${id}`);
if (cached) {
return JSON.parse(cached);
}
const user = await User.findById(id).lean();
await redis.set(`user:${id}`, JSON.stringify(user), { EX: 300 });
return user;The application first checks the cache and queries the database only when the value is missing.
Key Takeaways
Caching is a trade-off between performance and consistency.
Every cache should have an invalidation or expiration strategy.
The application should define what happens when the cache is unavailable.
Knowledge Check
What is the cache-aside pattern?