Video in progress
You need to write a single caching standard for all services in the organization. Which of cache-aside, read-through, write-through and write-behind do you make the default?
The default is cache-aside, with invalidation by deleting the entry on write, and a TTL on every key. Write-through only when the cache and the database are managed inside one component, and write-behind only for cases that can tolerate data loss and have heavy writes, with separate approval.
📖 Answer
The goal of writing a standard is to make the safest path the easiest path. Most teams don't think hard about caching.
| Pattern | Who fills the cache | Main risk |
|---|---|---|
| Cache-aside | the application, on a miss | short staleness, stampede |
| Read-through | the cache library, through a loader | the same, but cleaner code |
| Write-through | the write goes from the cache to the DB synchronously | writing to two systems, partial success |
| Write-behind | the cache writes to the DB later | writes are lost if the cache goes down |
Why cache-aside is the default:
- the system works even if the cache doesn't (slower), so the cache becomes an optional dependency;
- every team can adopt it quickly with
@Cacheablethrough Spring Cache; - deleting the entry on write instead of updating it greatly reduces the race between two parallel writers.
The rules I put in the standard:
- No cache without a TTL. The default TTL and jitter live in the platform library.
- Key format:
service:entity:v{schema}:{id}, so the version and the owner are visible. - The cached object is a DTO, as JSON, not an entity.
- Invalidation after the commit.
- A cache error doesn't fail the request: a short Redis timeout (100-300 ms) and fallback to the DB on error (
CacheErrorHandler). - Metrics for hit ratio, latency and key count are mandatory.
@Bean
CacheErrorHandler cacheErrorHandler() {
return new SimpleCacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
log.warn("cache get failed {} {}", cache.getName(), key, e); // we fall through to the DB
}
};
}
About write-behind: it's good where the write stream is very large (for example, a view counter) and a few seconds of loss is acceptable. But if you hand it out as a general pattern, someone will definitely use it for orders. That's why in the standard it sits in the section "architecture review required".
Sign up to mark studied questions and save your progress.