Video in progress
What happens when a @Cacheable method returns null, and when does that cause problems?
By default RedisCacheManager caches null using a special marker, so a "not found" answer gets cached too. With disableCachingNullValues(), null is not cached and every such request goes to the DB.
📖 Answer
Both options have their own risk.
Null is cached: a user asks for product 10, it doesn't exist yet, and the cache remembers "none". A minute later an admin adds the product, but until the TTL runs out everyone sees "not found", unless you put a @CacheEvict on the create method.
Null is not cached: if someone deliberately floods you with requests for nonexistent IDs, each one reaches the DB. This is called cache penetration.
The practical solution is to cache null, but with a short TTL, and add an evict to the create method. The code below does the opposite, it does not cache null:
@Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
public ProductDto find(long id) { ... }
The unless above says explicitly not to write null to the cache. If you need the opposite, work with a separate cache name that has a short TTL.
One more subtle point: if the method returns an Optional, Spring unwraps it and caches the value inside, or null.
Sign up to mark studied questions and save your progress.