Video in progress
You put a caching decorator on top of a repository. What can go wrong in production, and how do you prevent it?
The main risks: a stale value staying in the cache because of a transaction rollback or a read before the commit, hundreds of requests hitting the database at once when a popular key expires (a stampede), and a caller mutating a mutable object held in the cache. The fixes are evicting after commit, a single loader, and caching immutable DTOs.
📖 Answer
The decorator itself is simple: CachingProductRepository wraps the real repository, checks the cache on reads, and removes the key on writes. The problems are in the details.
A race with the transaction. The writer evicts the key inside its transaction but hasn't committed yet. Meanwhile another request sees a cache miss, reads the old value from the database and puts it in the cache. After the commit, the stale value sits in the cache until the TTL runs out. On rollback it's the reverse: a value that never committed may have been written to the cache. The fix is to move evict and put to after the commit: in Spring, TransactionAwareCacheDecorator or the Redis cache manager's transactionAware() setting does exactly that. In critical places I also evict after the commit and set a short TTL.
A stampede. In a price cache a popular key expired and 500 parallel requests went to the database at once. Within a single instance, @Cacheable(sync = true) or Caffeine's LoadingCache guarantees one loader per key. In a cluster each pod loads on its own; there, random jitter on the TTL and refreshing in the background before expiry (refresh-ahead) help.
A mutable object. A local cache (Caffeine) holds a reference to the object. If the caller calls setPrice() on the entity it got back, the value in the cache changes too. Caching a Hibernate entity is even worse: a detached object, and a LazyInitializationException on a lazy field. Put only immutable DTOs or records in the cache.
A missing value. If requests for non-existent ids aren't cached, each one goes to the database. You may need negative caching (storing "not found" with a short TTL).
Measure: hit ratio, load time and eviction count should be in your metrics. If the hit ratio is 30%, the decorator may be adding nothing but complexity.
Sign up to mark studied questions and save your progress.