Redis Caching - 70% Database Load Reduction in Production
Phạm Xuân Đạt
Full Stack Engineer
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: OrderRepositoryasync 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**Don't cache everything** - only cache frequently read data
- 2**Monitor cache hit rate** - if < 50%, review strategy
- 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.
Related Posts
Autocomplete - Classic Search System Challenge
Autocomplete is a critical feature for any search-enabled service. Learn how to build an autocomplete system using Trie and Suffix Tree data structures.
Logging, Metrics, Monitoring - Essential Production Tools
When working with large projects, logging, metrics, and monitoring are nearly ESSENTIAL tools. Let's explore them in detail.