async function getUser(id: string) {
const key = "user:" + id;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const user = await db.users.findById(id);
if (user) await redis.set(key, JSON.stringify(user), "EX", 300);
return user;
}
In cache-aside (also called lazy loading), the application code checks the cache and fills it. Redis does nothing on its own.
On a read:
- Check Redis first.
- On a hit (the key is in Redis), return the cached value.
- On a miss (the key is not there), load the data from the database.
- Write the result into Redis with a TTL (an expiry time), then return it.
On a write: update the database, then delete the cache key. The next read then loads fresh data.
Pros:
- Only data that is actually requested gets cached.
- If Redis goes down, the app can still read from the database.
Cons:
- The first read after a miss is slow.
- Data can be stale (out of date) until the TTL expires or the key is deleted.
- Every caller must follow the pattern.
It is the most common caching pattern in Node and NestJS services.
- On a read, check the cache first, and on a miss load from the DB and fill the cache.
- Always set a TTL on cached keys.
- On a write, update the DB, then delete the cache key.
- It caches only what is read, and the app still works if the cache is down.
- Misses are slow, and data can be briefly stale.
Read more