Video in progress

Strong Middle 🌱 Spring

What problems do you run into with @Cacheable around key choice, TTL and cache refresh?

Mainly these: a wrong key (collisions, or the cache never hits), no TTL (the cache grows forever and goes stale), local caches on several instances drifting apart, and someone mutating an object that sits in the cache.

📖 Answer

Start with the key. The default key is all the arguments. If several methods use the same cacheNames, their keys can collide. Write the key explicitly:

@Cacheable(cacheNames = "product", key = "#id")
public ProductDto product(long id, Locale locale) // locale is not in the key: wrong-language response!

The correct version: key = "#id + ':' + #locale.language".

TTL: the simple cache has none. In Caffeine it's expireAfterWrite, in Redis RedisCacheConfiguration.entryTtl(...). TTL is really a business question: how stale can the data get?

Multiple instances: three pods means three local Caffeine caches. @CacheEvict works on only one of them, and the other two keep showing the old price. A shared cache (Redis), a short TTL, or evicting on every instance via an event helps.

Caffeine stores the object itself. If the caller mutates it, the value in the cache changes too, so put immutable DTOs (records) in the cache.

There's a subtle point with transactions too: @CacheEvict may fire even if the transaction rolls back; conversely, if you evict before the commit, another thread can read the old value from the database and put it back in the cache. TransactionAwareCacheManagerProxy defers the evict until after the commit.