Caching Strategies
The fastest database query is the one you don't make. Learn when and how to cache.
1The Kitchen Analogy
2Why Cache?
Without Cache
With Cache
Typical Latency Comparison
3Caching Patterns
There are several ways to implement caching. Each pattern suits different use cases:
1. Cache-Aside (Lazy Loading)
Application checks cache first. On miss, load from DB and populate cache.
def get_user(user_id):
# 1. Try cache first
user = cache.get(f"user:{user_id}")
if user:
return user
# 2. Cache miss - load from DB
user = db.query("SELECT * FROM users WHERE id = ?", user_id)
# 3. Store in cache for next time
cache.set(f"user:{user_id}", user, ttl=300) # 5 min TTL
return user2. Write-Through
Writes go through cache to database. Cache always has latest data.
3. Write-Behind (Write-Back)
Writes to cache immediately, DB updated asynchronously later.
4. Read-Through
Cache sits in front of DB. App only talks to cache. Cache loads from DB on miss.
4Pattern Comparison
| Pattern | Read Perf | Write Perf | Consistency | Best For |
|---|---|---|---|---|
| Cache-Aside | Fast (after warm) | Normal | Eventual | Read-heavy, tolerate stale |
| Write-Through | Fast | Slower | Strong | Need consistency |
| Write-Behind | Fast | Very Fast | Eventual | Write-heavy, can lose data |
| Read-Through | Fast (after warm) | Normal | Eventual | Simpler code |
5What to Cache
Good Candidates
Avoid Caching
6Cache Invalidation
TTL (Time-To-Live)
Data expires after set time. Simplest approach.
cache.set('user:123', data, ttl=300) # Expires in 5 minsEvent-Based Invalidation
Delete cache when data changes. Most accurate.
on_user_update(user): cache.delete(f'user:{user.id}')Version/Tag-Based
Include version in key. Change version to invalidate all.
cache.get(f'user:{user_id}:v2') # Bump v2 to v3 to invalidate all7Key Takeaways
8Interview Follow-up Questions
Interview Follow-up Questions
Common follow-up questions interviewers ask
9Test Your Understanding
Test Your Understanding
5 questions
In cache-aside pattern, when is data loaded into the cache?
What is the main advantage of write-through caching?
A good cache hit rate target is typically:
What causes a cache stampede?
Which data is NOT a good candidate for caching?