backendredisperformance

Redis Caching - 70% Database Load Reduction in Production

Phạm Xuân Đạt

Phạm Xuân Đạt

Full Stack Engineer

January 5, 20265 min read

Redis Caching - 70% Database Load Reduction in Production

Real-World Problem

At Bao Den Logistics, we faced issues with API response times reaching 3+ minutes for some endpoints. After analysis, the main cause was heavy database queries.

Solution: Redis Caching Layer

Caching strategy: 1. **Cache-aside pattern**: Read from cache first, on miss read from DB 2. **Appropriate TTL**: 5 minutes for frequently changing data, 1 hour for rarely changing data 3. **Cache invalidation**: Clear cache when data is updated

Code example with NestJS:

@Injectable()
export class OrderService {
  constructor(
    private redis: RedisService,
    private orderRepo: OrderRepository

async getOrder(id: string) { const cacheKey = `order:${id}`; // Try cache first const cached = await this.redis.get(cacheKey); if (cached) return JSON.parse(cached); // Cache miss - query DB const order = await this.orderRepo.findById(id); await this.redis.set(cacheKey, JSON.stringify(order), 'EX', 300); return order; } } ```

Results Achieved

| Metric | Before | After | |--------|--------|-------| | Response Time | 3+ min | < 10s | | Database Load | 100% | 30% | | Cache Hit Rate | 0% | 85% |

Lessons Learned

  1. 1**Don't cache everything** - only cache frequently read data
  2. 2**Monitor cache hit rate** - if < 50%, review strategy
  3. 3**Be careful with stale data** - invalidation must happen at the right time

Redis is a powerful tool, but it needs to be used correctly.

Share this article