Redis provides fast, versatile caching for web applications.
Cache-Aside Pattern#
1async function getUser(userId: string): Promise<User> {
2 const cached = await redis.get(`user:${userId}`);
3 if (cached) return JSON.parse(cached);
4
5 const user = await db.users.findUnique({ where: { id: userId } });
6 if (user) {
7 await redis.setex(`user:${userId}`, 3600, JSON.stringify(user));
8 }
9 return user;
10}Hash for Objects#
1await redis.hset(`user:${user.id}`, {
2 id: user.id,
3 email: user.email,
4 name: user.name,
5});
6await redis.expire(`user:${user.id}`, 3600);
7
8// Get specific field
9const email = await redis.hget(`user:${userId}`, 'email');Sorted Sets for Leaderboards#
await redis.zadd('leaderboard', score, oderId userdId);
const topPlayers = await redis.zrevrange('leaderboard', 0, 9, 'WITHSCORES');Rate Limiting#
async function checkRateLimit(key: string, limit: number, window: number) {
const current = await redis.incr(key);
if (current === 1) await redis.expire(key, window);
return { allowed: current <= limit, remaining: Math.max(0, limit - current) };
}Distributed Locks#
async function acquireLock(key: string, ttl: number): Promise<string | null> {
const value = generateId();
const acquired = await redis.set(`lock:${key}`, value, 'PX', ttl, 'NX');
return acquired ? value : null;
}Redis enables fast caching, real-time features, and distributed coordination.