Sub topic 7
Keeping the cache consistent with @CachePut and @CacheEvict
@Cacheable fills the cache, but it never notices when the underlying data changes. If a product's price is updated in the database, the cached copy stays wrong until it expires. This chapter covers the two annotations that keep a cache in step with writes, and the patterns that cover their gaps.
This chapter assumes you can already use @Cacheable with cacheNames and key. It also assumes you know basic SpEL expressions such as #id and #result, and that caching is enabled with @EnableCaching.
The consistency problem
A cache holds a copy of data. Whenever the source changes, you have three options:
- Wait for the entry to expire. This is simple, but readers see stale data until then.
- Replace the entry with the new value, using
@CachePut. - Remove the entry so the next read reloads it, using
@CacheEvict.
Expiration (covered in a later chapter) is a safety net. The two annotations here are the deliberate approach, and you will often use both.
@CachePut: always run, then store
@Cacheable skips the method on a cache hit. @CachePut never skips it. The method always runs, and its return value is written to the cache under the computed key. This suits write operations that already return the new state.
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
public record Product(Long id, String name, BigDecimal price) {}
@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);
}
@CachePut(cacheNames = "products", key = "#product.id()")
public Product update(Product product) {
store.put(product.id(), product);
return product;
}
@CacheEvict(cacheNames = "products", key = "#id")
public void delete(Long id) {
store.remove(id);
}
}Two rules make @CachePut work:
- The key must match the reader's key.
findByIdcaches under theLongid. The put therefore uses#product.id(), which produces the sameLong. If the put used a different key shape, such as the wholeProductobject, it would create a second entry that no reader ever finds. - The method must return the value you want cached. A
voidmethod would storenull. If the method returns something other than the cached value, such as a DTO or a status object,@CachePutis the wrong tool. Use@CacheEvictinstead.
When the key is easier to read from the result than from the arguments, use #result:
@CachePut(cacheNames = "products", key = "#result.id()")
public Product create(String name, BigDecimal price) {
Product saved = new Product(nextId(), name, price);
store.put(saved.id(), saved);
return saved;
}Here the id is generated inside the method, so it cannot appear in the key as an argument. #result is available in key for @CachePut and @CacheEvict. It is not available in @Cacheable's key, because that key is computed before the method runs.
@CacheEvict: remove the entry
@CacheEvict deletes entries instead of writing them. Use it when the method does not return the new state (for example delete), or when you would rather pay for one reload than risk caching a half-correct value.
| Attribute | Effect |
|---|---|
| `cacheNames` | The cache to remove from. |
| `key` | The single entry to remove. Defaults to the method arguments, as in `@Cacheable`. |
| `allEntries` | If `true`, clears the whole cache and ignores `key`. |
| `beforeInvocation` | If `true`, evicts before the method runs. The default is `false`, so eviction happens after the method returns. |
| `condition` | A SpEL expression. If it evaluates to `false`, nothing is evicted. |
Evicting everything
Single-key eviction is only possible when you can name the key. A search cache is the usual counter-example. Suppose searchByName("key") was cached under the key "key". When product 1 is renamed, you cannot tell which search terms now return different results. The safe response is to clear the whole cache:
@CacheEvict(cacheNames = "productSearch", allEntries = true)
public void rebuildSearchIndex() {
// reload data from the source
}allEntries = true is blunt. With a local Caffeine cache it is cheap. With Redis it deletes all keys under the cache's prefix, which can be expensive on a large cache and causes a wave of misses right afterwards.
When eviction happens
By default, eviction runs after the method returns successfully. If the method throws, the entry stays in the cache. That is usually right. A failed delete did not change the data, so the cached copy is still valid.
Setting beforeInvocation = true evicts first, whether or not the method later succeeds. Use it when a failure could leave the source in an unknown state, and you prefer the next read to go to the source.
@CacheEvict(cacheNames = "products", key = "#id", beforeInvocation = true)
public void forceRefresh(Long id) {
// may throw; the entry is already gone either way
}The same rule applies to @CachePut. If the method throws, nothing is written.
Combining operations with @Caching
One write often affects more than one cache. Updating a product should refresh products and invalidate productSearch. Java does not allow the same annotation twice on one method, so group the operations with @Caching:
@Caching(
put = @CachePut(cacheNames = "products", key = "#product.id()"),
evict = @CacheEvict(cacheNames = "productSearch", allEntries = true))
public Product updateAndInvalidateSearch(Product product) {
store.put(product.id(), product);
return product;
}@Caching also accepts a cacheable array. Avoid putting @Cacheable and @CachePut for the same key on one method. Their behaviors conflict, and the Spring documentation advises against it.
How a write flows through the proxy
Both annotations are applied by the same proxy as @Cacheable. The proxy intercepts the call, runs your method, and then touches the cache based on the outcome.
Because the proxy does the work, the self-invocation limit from the earlier chapter applies. If update calls this.delete(id), the eviction on delete is silently skipped.
Put or evict?
| Situation | Prefer | Reason |
|---|---|---|
| Method returns the exact object readers would get | `@CachePut` | The next read is a hit, with no extra load. |
| Method returns a different shape, or nothing | `@CacheEvict` | There is nothing correct to store. |
| Cached value is derived from several sources | `@CacheEvict` | A put could store a partial or wrong value. |
| Many keys are affected and you cannot list them | `@CacheEvict(allEntries = true)` | The only safe choice. |
| Update frequency is high and reads are rare | `@CacheEvict` | A put writes values nobody reads. |
Gaps that the annotations do not close
- Transactions. The cache operation runs when the method returns, which can be before the surrounding transaction commits. If the transaction later rolls back, the cache holds data that was never saved. Evicting is safer than putting here. If the transaction layer is outside the cached method, consider the
TransactionAwareCacheManagerProxyor evicting from an@TransactionalEventListener(phase = AFTER_COMMIT). - Multiple application instances. With Caffeine, each instance has its own cache. An eviction on instance A does not reach instance B. Use a shared cache such as Redis, or accept staleness bounded by a short
expireAfterWrite. - Changes outside your code. A SQL script or another service that updates the database never triggers your annotations. Only expiration protects you from those.
- Mutable cached values. A local cache stores references. If a caller modifies a cached object, the cache changes without any put. Prefer immutable values such as records.
Checking the behavior
Verify consistency through the CacheManager, as in the earlier testing example:
@SpringBootTest
class ProductConsistencyTest {
@Autowired ProductService service;
@Autowired CacheManager cacheManager;
@Test
void deleteRemovesEntry() {
service.update(new Product(7L, "Mouse", new java.math.BigDecimal("19.90")));
service.findById(7L);
assertThat(cacheManager.getCache("products").get(7L)).isNotNull();
service.delete(7L);
assertThat(cacheManager.getCache("products").get(7L)).isNull();
}
}The test calls the service through the injected proxy, so the annotations apply. If you construct new ProductService() yourself, there is no proxy and the test proves nothing.
Exercise
A service has @Cacheable(cacheNames = "products", key = "#id") Product findById(Long id) and @CachePut(cacheNames = "products") Product update(Product product). After update(new Product(1L, "Pen", ...)), findById(1L) still returns the old product. Why, and how do you fix it?
Show answer
The @CachePut has no key, so it uses the default key built from the method arguments. That default is the whole Product object, not the id 1L. The put creates an entry that findById never reads, and the old entry under 1L stays. Fix it by setting key = "#product.id()" so the put writes to the same key the reader uses.
Exercise
delete(Long id) is annotated with @CacheEvict(cacheNames = "products", key = "#id") and throws an exception because the row is locked. Is the cache entry still present afterwards? How would you change that behavior?
Show answer
Yes, the entry is still present. By default eviction runs after the method returns normally, and an exception skips it. Setting beforeInvocation = true evicts the entry before the method runs, so it is removed even when the method fails.