Caching patterns
Cache aside vs Read through
- Cache aside: app checks cache and fetches from DB on miss then updates cache
- Read through: app checks cache, the cache will automatically fetch from the DB if missing
The difference between the 2 above, is what is fetching from the DB on cache miss. Either the app or the cache system itself, but the principle is the same.
Benefit of readthrough is that the app code only needs to fetch from the cache and the cache logic manages what happens on miss.
If you need to invalidate the cache, you can manually remove the key.
If consistency matters, you can invalidate on DB write so that the next read triggers a refresh from DB.
Write through vs Write back
- Write through: app writes to the cache and then to the DB
- Write behind (or back): app writes to the cache and queues an update to the DB for later
The main difference is the data consistency. Write behind is eventually consistent, but faster.
Key Takeaways & Trade-offs
- Application vs. Cache Responsibility: Cache-Aside requires you to write the fallback logic inside your application code. Read-Through abstracts this away, moving the database fetching responsibility entirely to the caching infrastructure.
- The Write Speed vs. Data Safety Dilemma: Write-Through guarantees strong consistency and zero data loss, but it penalizes application write performance with dual network round-trips. Write-Behind provides maximum speed by writing to memory first, but you risk losing data if the cache crashes before syncing to the database.
- Memory Optimization: Patterns like Cache-Aside and Read-Through only load data on demand, keeping memory costs low. Write-intensive patterns can cause cache churn by filling memory with data that may never be read again.