Redis Caching Patterns Every Backend Engineer Should Know
Cache-aside, write-through, write-behind — different caching strategies have very different consistency guarantees. Know when to use each one.
Redis Caching Patterns Every Backend Engineer Should Know
Caching is the most powerful tool for reducing latency. But the wrong strategy causes stale data, cache stampedes, and subtle bugs. Here are the patterns you'll be asked about in system design interviews.
Pattern 1: Cache-Aside (Lazy Loading)
The application manages the cache directly.
public User getUser(String userId) {
// 1. Check cache
User cached = redis.get("user:" + userId);
if (cached != null) return cached;
// 2. Cache miss — fetch from DB
User user = db.findById(userId);
// 3. Populate cache
redis.setex("user:" + userId, 3600, user);
return user;
}
Trade-off: Simple, resilient to cache failure. But the first request after a cold start (or TTL expiry) is slow.
Pattern 2: Write-Through
Write to cache and DB simultaneously.
public User updateUser(User user) {
User saved = db.save(user);
redis.setex("user:" + user.getId(), 3600, saved); // update cache too
return saved;
}
Trade-off: Cache is always fresh. But writes are slower (two round trips). Cache may hold data that's never read again.
Pattern 3: Write-Behind (Write-Back)
Write to cache immediately; asynchronously flush to DB.
Trade-off: Fastest writes, but risk of data loss if the cache node crashes before flushing.
Pattern 4: Cache Stampede Prevention
When a popular cache entry expires, thousands of requests hit the DB simultaneously.
// Probabilistic early expiration — refresh cache before it expires
long ttl = redis.ttl(key);
if (ttl < 60 && Math.random() < 0.1) {
// 10% chance to refresh early when < 60s remaining
refreshCache(key);
}
Interview cheat sheet
| Pattern | Consistency | Write Speed | Complexity |
|---|---|---|---|
| Cache-Aside | Eventual | Fast | Low |
| Write-Through | Strong | Slow | Medium |
| Write-Behind | Eventual | Fastest | High |
Related Posts
How to Crack the System Design Interview
Most engineers fail system design interviews not because they lack knowledge, but because they lack a framework. Here's the repeatable 6-step approach that works.
SQL vs NoSQL: How to Choose the Right Database
Choosing between SQL and NoSQL is one of the most common system design questions. Here's a principled framework — not just "it depends".