Skip to contentPedro Farbo
Lesson 16 / 2550 min

Redis Cache

Redis Cache

Improve performance with Redis caching.

Installation

bash
npm install ioredis

Configuration

typescript
// src/config/redis.tsimport Redis from 'ioredis'; const redis = new Redis({  host: process.env.REDIS_HOST || 'localhost',  port: Number(process.env.REDIS_PORT) || 6379,  password: process.env.REDIS_PASSWORD,}); redis.on('error', (err) => console.error('Redis error:', err));redis.on('connect', () => console.log('📦 Redis connected')); export default redis;

Cache Service

typescript
// src/services/cache.service.tsimport redis from '../config/redis'; export class CacheService {  private prefix = 'ecommerce:';   async get<T>(key: string): Promise<T | null> {    const data = await redis.get(this.prefix + key);    return data ? JSON.parse(data) : null;  }   async set(key: string, value: any, ttl?: number): Promise<void> {    const data = JSON.stringify(value);    if (ttl) {      await redis.setex(this.prefix + key, ttl, data);    } else {      await redis.set(this.prefix + key, data);    }  }   async delete(key: string): Promise<void> {    await redis.del(this.prefix + key);  }   async getOrSet<T>(key: string, fn: () => Promise<T>, ttl: number): Promise<T> {    const cached = await this.get<T>(key);    if (cached) return cached;     const data = await fn();    await this.set(key, data, ttl);    return data;  }}

Usage in Services

typescript
const cache = new CacheService(); async findById(id: string) {  return cache.getOrSet(`product:${id}`, async () => {    return prisma.product.findUnique({ where: { id } });  }, 600); // 10 minutes} async update(id: string, data: any) {  const product = await prisma.product.update({ where: { id }, data });  await cache.delete(`product:${id}`);  return product;}

Rate Limiting with Redis

typescript
export const rateLimiter = async (req: Request, res: Response, next: NextFunction) => {  const ip = req.ip;  const key = `ratelimit:${ip}`;   const current = await redis.incr(key);  if (current === 1) await redis.expire(key, 60);   if (current > 100) {    return res.status(429).json({ error: 'Too many requests' });  }   next();};

Summary

  • ✅ Redis connection
  • ✅ Generic cache service
  • ✅ Cache invalidation
  • ✅ Rate limiting

Next lesson: Unit Testing! 🚀

Enjoyed the content? Your contribution helps keep everything online and free!

PIX:0737160d-e98f-4a65-8392-5dba70e7ff3e