Sub topic 16
Common pitfalls and how to avoid them
This chapter assumes you can already use @Cacheable, @CachePut and @CacheEvict, and that you know a Spring bean is wrapped in a proxy. It covers the mistakes that most often turn a working cache into a source of wrong answers.
Stale data
A cache returns old data when the source changes and the entry does not. There are two common causes.
- Writes outside the annotated methods. A SQL script, another service, or a scheduled job changes the row. Spring never sees it. Set a time to live (TTL) so every entry expires eventually, even if nothing evicts it.
- Related entries. Updating a product refreshes
productsbut leaves cached search results inproductSearchunchanged.
Evict the related cache in the same operation:
@Caching(evict = {
@CacheEvict(cacheNames = "products", key = "#product.id()"),
@CacheEvict(cacheNames = "productSearch", allEntries = true)
})
public void replace(Product product) {
store.put(product.id(), product);
}allEntries = true is blunt but safe, because search keys cannot be derived from a product id.
Mutable cached values
With Caffeine, the cache holds a reference to the object, not a copy. If a caller changes the returned object, it changes the cached one for everyone.
@Cacheable("productSearch")
public List<Product> searchAll(String name) {
return List.copyOf(
store.values().stream()
.filter(p -> p.name().contains(name))
.toList());
}Prefer records and immutable collections. If you must return a mutable type, copy it before you return it. Redis avoids this problem because it stores serialized bytes, but it adds one of its own. Every cached type must serialize cleanly, and a class change can break entries written by the previous deployment. Clear the cache or change the key prefix when you deploy such a change.
Null values
Caching null means a missing record stays missing until the entry expires, even after someone creates it. The unless = "#result == null" attribute from earlier chapters avoids this. Redis with spring.cache.redis.cache-null-values=false goes further. If a method returns null and you forgot unless, Spring throws an IllegalArgumentException instead of caching it. Treat that exception as a reminder to add the unless attribute.
Key and proxy mistakes
- Key collisions. Two methods that share a cache name and use the default key can overwrite each other when their arguments are equal. Use separate cache names, or put a prefix in the key, for example
key = "'byName:' + #name". - Self-invocation. A call from one method to another on the same object skips the proxy, so no caching happens. Move the cached method to another bean, or inject the proxied bean.
- Wrong visibility. With the default proxy mode, cache annotations on
privatemethods are ignored. Put them onpublicmethods of Spring beans. - Annotations on the wrong level. Put the annotations on the concrete class, not an interface, and keep the style consistent across the project.
A quick checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| Method runs every time | Self-invocation, private method, or missing `@EnableCaching` | Call through another bean |
| Old data after an update | Related cache not evicted, or no TTL | `@Caching` evict, set a TTL |
| Data changes unexpectedly | Mutable cached object | Return immutable copies |
| Missing item never appears | `null` was cached | Add `unless` |
| Wrong value for a key | Key collision | Use distinct keys or cache names |
Exercise
A service caches findById in products and searchByName in productSearch. After update(product) runs with @CachePut on products, a search still returns the old price. Why, and what is the fix?
Show answer
@CachePut refreshes only the products entry for that id. The productSearch entries are keyed by search text and still hold the old product. Evict them in the same operation, for example with @CacheEvict(cacheNames = "productSearch", allEntries = true) inside @Caching, and keep a TTL as a safety net.