What Are Caching Strategies? Boost Application Performance
Are your users hammering the database on every request? Page load times too high? Caching stores frequently accessed data in faster layers, dramatically improving performance.
What Is Caching?
Caching is temporarily storing frequently accessed data in a faster layer to reduce access to slow sources (database, API, disk).
No cache: Request → Database (50ms) → Response
With cache: Request → Redis (0.5ms) → Response
Cache Layers
User → Browser Cache → CDN → App Cache → DB Cache → Database
(fastest) (slowest)
Caching Strategies
1. Cache-Aside (Lazy Loading)
async function getUser(userId: string) {
const cached = await redis.get(`user:${userId}`);
if (cached) return JSON.parse(cached);
const user = await db.users.findById(userId);
await redis.set(`user:${userId}`, JSON.stringify(user), 'EX', 3600);
return user;
}
2. Write-Through
Update cache on every write. Cache is always current.
3. Write-Behind
Write to cache first, then async to DB. Very fast writes, but risk of data loss.
4. Read-Through
Cache layer auto-fetches from DB on miss.
Cache Invalidation
TTL
await redis.set('user:42', data, 'EX', 3600); // Auto-delete after 1 hour
Event-Based
async function updateUser(userId: string, data: UserData) {
await db.users.update(userId, data);
await redis.del(`user:${userId}`);
}
CDN Caching
User (Istanbul) → CDN Edge (Istanbul) → Fast response
User (New York) → CDN Edge (New York) → Fast response
Cache-Control Headers
Cache-Control: public, max-age=31536000, immutable → Static files
Cache-Control: private, no-cache → User-specific
Cache-Control: no-store → Sensitive data
Common Problems
Thundering Herd
When TTL expires, thousands of requests hit DB simultaneously. Solution: mutex lock or stale-while-revalidate.
Stale Data
Cached data may be outdated. Use appropriate TTL and event-based invalidation.
Best Practices
- Choose proper TTL — Too short: no benefit, too long: stale data
- Cache key convention —
entity:id:fieldformat - Warm up — Pre-load critical data on application startup
- Monitor hit/miss ratio — Target 90%+ hit rate
- Set size limits — Configure eviction policy (LRU, LFU)
- Never cache sensitive data — Passwords, tokens must stay out
Conclusion
Caching is one of the most effective ways to boost performance. The right strategy with proper invalidation can yield 10x-100x speed improvements. But beware — cache invalidation is genuinely hard.
Learn caching strategies on LabLudus.