Video in progress

What mistakes are there in this combination of `@CacheEvict` and `@CachePut`, and how do you fix them?

@Transactional
@CachePut(cacheNames = "product", key = "#result.id")
@CacheEvict(cacheNames = "productList", allEntries = true)
public Product update(long id, ProductForm form) {
    Product p = repo.findById(id).orElseThrow();
    p.apply(form);
    return p;
}

The cache writes happen before the transaction commits, a managed JPA entity ends up in the cache, and allEntries = true scans and deletes the whole prefix in Redis, which is expensive on a big cache. You need to make the cache manager transaction-aware and cache DTOs.

📖 Answer

There are several subtle problems in this code.

  1. Ordering and the transaction: when one method has @Transactional and the cache annotations, two proxies/advisors run. By default the cache interceptor runs inside the transaction: the cache is updated, and then if the commit fails, the cache is left with a state that isn't in the DB. To update after the commit, make RedisCacheManager transactionAware() (a TransactionAwareCacheDecorator), which does the put/evict after the commit.
RedisCacheManager.builder(cf)
        .cacheDefaults(config)
        .transactionAware()
        .build();
  1. The entity inside #result: the returned Product is a managed JPA entity and may hold lazy collections. During serialization you get a LazyInitializationException, or the whole graph ends up in the cache. You should put a DTO in the cache, not an entity.

  2. allEntries = true: in Redis this means finding and deleting the keys by prefix. By default Spring Data Redis still uses KEYS; you can switch to SCAN with BatchStrategies.scan(n), and on a big cache you should:

RedisCacheWriter writer = RedisCacheWriter.nonLockingRedisCacheWriter(cf, BatchStrategies.scan(1000));

Clearing the whole list cache on every product update is expensive in itself. Sometimes it's better to keep the list caches on a short TTL and drop the evict entirely.

  1. Key types: with @Cacheable(key = "#id") the key is a long, and with @CachePut(key = "#result.id") it's a Long. In Redis both become product::42, so there's no problem here. But if the key expressions are written differently in different methods (for example, one #id, another #p.id + ''), it's worth writing an integration test to check that they match.