In this lesson, you will learn how to implement a tiered caching strategy using Redis to minimize direct database hits and significantly scale your application's read performance.
The Tiered Caching Approach
When your application receives a request for data, querying a database (like MongoDB or PostgreSQL) is expensive in terms of time and resources. Instead of hitting the database every time, we use a tiered strategy: check a high-speed cache (Redis) first, and only query the database if the cache is empty (a "cache miss").
Implementing the Pattern
Think of Redis as your "front desk" and your database as the "back office archive." If the answer is at the front desk, you never need to walk to the back office.
Here is how you structure this logic in a Node.js service:
async function getUserProfile(userId) {
// Tier 1: Check Redis
const cachedData = await redis.get(`user:${userId}`);
if (cachedData) {
return JSON.parse(cachedData);
}
// Tier 2: Database query (only on cache miss)
const user = await db.users.findById(userId);
// Backfill: Save to Redis for next time (with an expiration)
if (user) {
await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
}
return user;
}
Why This Scales
- Reduced Latency: Reading from memory (Redis) takes microseconds, whereas database queries take milliseconds.
- Database Offloading: By serving the majority of requests from Redis, your database is freed up to handle complex writes and critical updates, rather than redundant reads.
- TTL (Time to Live): Notice the
3600insetex. This sets an expiration of one hour. This ensures that if the underlying database record changes, the cache eventually expires, preventing stale data from living indefinitely.
By placing Redis in front of your persistence layer, you create a "read-through" effect. The application no longer bears the full weight of every user request, allowing your database to maintain high performance under heavy read traffic.
Key Takeaway: By checking Redis before the database and backfilling the cache on misses, you effectively offload your database and drastically reduce read latency.