Caching Patterns
Understanding different caching strategies and when to use each
Why Caching Matters
Caching Patterns
Cache-Aside (Lazy Loading)
Application manages the cache - loads data on cache miss
Write-Through
Data written to cache and database simultaneously
Write-Behind (Write-Back)
Write to cache immediately, async write to database later
Read-Through
Cache automatically fetches from database on miss
Refresh-Ahead (Pre-fetching)
Proactively refresh cache before expiration
Cache-Aside in Detail
The most common caching pattern - walk through each step.
Cache-Aside Pattern Flow
Application Requests Data
User requests user profile for user_id=123
The application receives a request that needs data from the database.
Common entry point: API endpoint, service method.
Eviction Strategies
When cache is full, which items should be removed?
LRU (Least Recently Used)
Evict the item that has not been accessed for the longest time
LFU (Least Frequently Used)
Evict the item with the fewest accesses
FIFO (First In, First Out)
Evict the oldest item regardless of access pattern
TTL (Time To Live)
Evict when time expires, regardless of space
Random
Evict a random item
Common Caching Problems
Cache Stampede
Many requests hit an expired cache key simultaneously, all querying the database at once.
- - Lock/mutex on cache refresh
- - Staggered TTLs
- - Background refresh
Stale Data
Cache contains outdated data that does not reflect current database state.
- - Appropriate TTL values
- - Cache invalidation on writes
- - Write-through pattern
Cache Penetration
Requests for non-existent data bypass cache and always hit the database.
- - Cache negative results
- - Bloom filter for existence check
- - Input validation
Redis vs Memcached
| Feature | Redis | Memcached |
|---|---|---|
| Data Structures | Strings, Lists, Sets, Hashes, Sorted Sets | Strings only |
| Persistence | Yes (RDB, AOF) | No |
| Replication | Built-in | No |
| Pub/Sub | Yes | No |
| Lua Scripting | Yes | No |
| Memory Efficiency | Good | Better (simpler) |
| Best For | Feature-rich caching, sessions, queues | Simple, high-throughput key-value cache |