Sub topic 16
Common pitfalls and how to avoid them
This chapter collects the failures that show up most often once caching is in place. It assumes you know the basics of Spring Boot, dependency injection, and the annotations from earlier chapters: @Cacheable, @CachePut, @CacheEvict, and a provider such as Caffeine or Redis. Each section names the symptom, explains the mechanism, and gives a fix.
Pitfall 1: Annotations that silently do nothing
The most confusing cache bug is one where the code runs correctly and nothing is cached. Spring applies caching through a proxy, which is a wrapper object placed around your bean. Anything that skips the proxy skips the cache.
Common causes:
@EnableCachingis missing, so no proxy is created.- The method is called from another method of the same class (self-invocation).
- The method is
private,final, orstatic. Proxies cannot intercept these. - The class is not a Spring bean, because it was created with
new.
Self-invocation is the one people hit most:
@Service
public class ReportService {
public String latestDailyReport() {
// This call stays inside the object. The proxy never sees it,
// so the @Cacheable advice on load() is not applied.
return load("daily");
}
@Cacheable("reports")
public String load(String name) {
return "report:" + name;
}
}There are three ways to fix it. The simplest is to move load into a separate bean and inject that bean. You can also put the annotation on the public entry point that callers use. The third option is to switch to AspectJ weaving, which changes the bytecode instead of using proxies, but it adds build complexity and is rarely worth it for this alone.
Pitfall 2: Stale data
A cache returns a copy of the past. The longer an entry lives, the more likely it no longer matches the source of truth. Stale data comes from three places:
- Writes that bypass the cache. A scheduled job, a SQL script, or another service updates the database directly.
- Missing eviction. You annotated
findByIdbut forgotupdateordelete. - Several application instances with local caches. Caffeine lives inside one JVM. If instance A updates a product and evicts its own entry, instance B still holds the old value until it expires.
The defences, in order of strength:
- Always set a time-to-live, even when you also evict. It limits how long a missed eviction can hurt.
- Pair every write method with
@CachePutor@CacheEvicton the same cache and the same key. - Use a shared cache such as Redis when several instances must agree.
- Decide up front how much staleness a given piece of data can tolerate. A product description can be minutes old. A stock count or account balance often cannot be cached at all.
Pitfall 3: Mismatched keys between read and write
@CachePut and @CacheEvict only work if they compute the same key as @Cacheable. A mismatch gives no error. The old entry simply stays.
@Service
public class ProductService {
private final Map<Long, Product> store = new ConcurrentHashMap<>();
@Cacheable(cacheNames = "products", key = "#id", unless = "#result == null")
public Product findById(Long id) {
return store.get(id);
}
// Wrong: with no key attribute, the key is the whole Product object,
// not the id. The entry stored by findById is never refreshed.
@CachePut(cacheNames = "products")
public Product updateBroken(Product product) {
store.put(product.id(), product);
return product;
}
// Right: same cache name, same key type and value.
@CachePut(cacheNames = "products", key = "#product.id()")
public Product update(Product product) {
store.put(product.id(), product);
return product;
}
}Watch the key type too. A Long key 1 and an Integer key 1 are different keys. A key built with #name.toLowerCase() on read must be built the same way on eviction.
Also remember that @CacheEvict by key does not touch other caches that hold derived data. If productSearch contains lists of products, updating one product leaves those lists stale. Evict them too with @CacheEvict(cacheNames = "productSearch", allEntries = true), and accept that this clears every search result.
Pitfall 4: Mutable cached values
With Caffeine, the cache stores a reference to your object, not a copy. If a caller changes the returned object, the cached object changes with it, and every later caller sees the change.
public class Basket {
private final List<String> items = new ArrayList<>();
public List<String> getItems() { return items; }
}
// A caller does this:
Basket basket = service.loadBasket(42L);
basket.getItems().add("temporary promo item"); // now also in the cachePrefer immutable values: Java records, List.copyOf(...), and Collections.unmodifiableList(...). The Product record from earlier chapters is a good model, as long as its fields are immutable too. BigDecimal and String are.
Redis behaves differently. It serializes the value, so each read produces a new copy and caller changes do not leak back. That difference can hide a bug in development with Redis that appears in production with Caffeine, or the reverse. Treat cached values as read-only in both cases.
Pitfall 5: Null values and the cached "not found"
By default, Spring's ConcurrentMapCache and Caffeine integration accept null as a cached value. This produces two opposite problems.
- Caching a miss too long.
findById(99)returnsnullbefore the product exists. Thenullis cached. After the product is created, reads still returnnulluntil the entry expires or is evicted. - Cache penetration. If you refuse to cache nulls, repeated requests for ids that do not exist always reach the database. An attacker or a buggy client can use this to bypass the cache.
Choose deliberately. The usual approach is unless = "#result == null" for entities that are created often, so a new row becomes visible immediately. For data where lookups of missing keys are frequent, cache the null but give it a short TTL, or cache an explicit "empty" object.
Redis adds another rule. With spring.cache.redis.cache-null-values=false, an attempt to cache null throws an exception unless you also have unless = "#result == null" on the method. Keep the two settings consistent.
Pitfall 6: Serialization problems with Redis
Redis stores bytes. By default Spring uses JDK serialization, which has these consequences:
- Cached classes must implement
Serializable, or writes fail at runtime. - The stored bytes are tied to the class structure. After a deployment that changes a class, old entries can fail to deserialize and throw errors on reads.
- The data is unreadable in
redis-cli.
Switch to JSON serialization with a RedisCacheConfiguration bean, as shown in the Redis chapter:
@Configuration
public class CacheConfig {
@Bean
RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}
}JSON helps, but it has its own cost. Records and classes without default constructors need Jackson support, and type information stored in the JSON ties entries to class names. A short TTL, plus a version in the key prefix (for example shop-v2::), lets you roll out a changed class without reading old entries.
Pitfall 7: Unbounded caches and memory growth
A cache with no size limit is a memory leak with a nicer name. Spring's default in-memory cache, used when no provider is configured, has no maximum and no expiry. High-cardinality keys make this worse. Examples are search terms, user ids with filters, and timestamps.
- Set
maximumSizeandexpireAfterWritefor Caffeine. - Set a TTL for Redis, and watch Redis memory limits and its eviction policy.
- Avoid keys that include volatile values such as the current time, or entire large objects.
- Use the
conditionattribute to skip caching input that is rarely repeated, like the short search terms in the earlier example.
Pitfall 8: Transactions and ordering
Cache operations and database transactions are not coordinated by default. If a method updates the database and refreshes the cache, and the transaction then rolls back, the cache holds data that was never saved.
Two safer patterns:
- Evict instead of put. A missing entry is reloaded from the committed database, so a rollback cannot leave wrong data behind.
- For stricter behavior, wrap the cache manager in a transaction-aware decorator so that cache writes happen after commit. Set
transactionAware()on the cache manager builder, which delays puts and evictions until the transaction commits.
Eviction before the transaction commits has its own race. Another thread can read the old row, repopulate the cache, and then your commit lands. The result is stale data again. Short TTLs limit the damage.
Pitfall 9: Treating the cache as required
A cache should only make things faster. If your code breaks when the cache is empty, or when Redis is down, the cache has become a dependency.
- Test with the cache cleared and confirm results are identical.
- Do not store data in the cache that exists nowhere else.
- For Redis, decide how failures behave. By default a connection error propagates to the caller. A custom
CacheErrorHandlercan log the error and fall through to the real method instead.
A checklist before shipping
Summary of the pitfalls and fixes:
| Pitfall | Symptom | Fix |
|---|---|---|
| Proxy bypass | Method runs every time | Call through another bean, use public methods |
| Stale data | Old values after updates | TTL, matching evictions, shared cache |
| Key mismatch | Update has no effect | Same `key` expression everywhere |
| Mutable values | Callers corrupt the cache | Immutable types |
| Null handling | Missing items stay missing, or load spikes | `unless`, short TTL for nulls |
| Serialization | Errors after deploy | JSON, versioned prefix |
| Unbounded growth | Heap or Redis memory grows | Size limit and TTL |
| Transactions | Cache disagrees with database | Evict, or use transaction-aware caches |
Exercise
A service has @Cacheable(cacheNames = "products", key = "#id") Product findById(Long id) and @CacheEvict(cacheNames = "products") void delete(Long id). After delete(5L), findById(5L) still returns the product. Why, and how do you fix it?
Show answer
The @CacheEvict has no key attribute, so its key defaults to the method parameter, which is the Long value 5. That looks like a match, but only if the method has a single parameter and the default key generator is used. The likelier cause in practice is a mismatch such as a different parameter type or an extra parameter, or that delete is called from another method in the same class and bypasses the proxy. Fix both uncertainties by writing key = "#id" explicitly on the eviction, checking the parameter types, and calling delete through the injected bean rather than this.
Exercise
Your Caffeine-cached method returns a List<Product>, and a caller sorts the returned list in place. Other callers now see the sorted order, and sometimes get ConcurrentModificationException. What is happening, and what are two ways to prevent it?
Show answer
Caffeine stores a reference, so all callers share the same list and the in-place sort changes the cached object. Return an unmodifiable or copied list, for example List.copyOf(result) inside the cached method, so the cache holds an immutable list. Alternatively, have callers copy the list before sorting, with new ArrayList<>(list).
Exercise
You run three instances of an application, each with a Caffeine cache and @CacheEvict on update. Users report seeing old prices for up to ten minutes after an update. Why, and what are two options to reduce the problem?
Show answer
Each instance has its own cache, and the eviction only clears the entry in the instance that handled the update. The other two keep the old price until the 10 minute expiry. Options: switch to a shared cache such as Redis, or shorten the TTL. A third option is to broadcast evictions between instances, for example with a message topic, but that adds infrastructure.