Redis caching — stores data in memory for fast access.
1const redis = require("redis");2const client = redis.createClient();34// Cache-aside pattern5async function getUser(id) {6 const key = `user:${id}`;78 // Try cache first9 let user = await client.get(key);10 if (user) return JSON.parse(user);1112 // Cache miss — fetch from DB13 user = await db.getUser(id);14 await client.setEx(key, 3600, JSON.stringify(user));15 return user;16}1718// Cache invalidation19async function updateUser(id, data) {20 const user = await db.updateUser(id, data);21 await client.del(`user:${id}`);22 return user;23}2425// Cache with stampede protection26async function getWithLock(key, fetchFn, ttl = 3600) {27 let data = await client.get(key);28 if (data) return JSON.parse(data);2930 const lockKey = `lock:${key}`;31 const locked = await client.set(lockKey, "1", { NX: true, EX: 10 });3233 if (!locked) {34 await new Promise(r => setTimeout(r, 100));35 return getWithLock(key, fetchFn, ttl);36 }3738 data = await fetchFn();39 await client.setEx(key, ttl, JSON.stringify(data));40 await client.del(lockKey);41 return data;42}
Patterns: