Sub topic 12
Expiration and eviction policies
This chapter assumes you can already annotate a method with @Cacheable, and that you know what a CacheManager is and how Spring Boot picks a provider. Here you will learn how entries leave a cache: by time (expiration) or by pressure (eviction). You will also see how to configure both for Caffeine and Redis.
Expiration versus eviction
The two words describe different reasons for removing an entry.
- Expiration removes an entry because it has become too old. It limits how stale cached data can be.
- Eviction removes an entry because the cache is full. It limits how much memory the cache uses.
- Explicit invalidation removes an entry because your code says so.
@CacheEvictdoes this, and the previous chapter covered it.
Spring's Cache interface has no time-to-live (TTL) setting and no size limit. Expiration and eviction belong to the provider, so you configure them in the provider's own settings. The built-in ConcurrentMapCache (used when no provider is found) never expires and never evicts. In production it grows until the JVM runs out of memory.
After any of these exits, the next call is a miss. The method runs again and the result is cached again.
Expiration in Caffeine
Caffeine offers two time policies.
| Policy | Clock starts | Typical use |
|---|---|---|
| `expireAfterWrite` | When the entry is created or replaced | Data with a known staleness tolerance |
| `expireAfterAccess` | At each read or write | Rarely used items you want to drop when idle |
Use expireAfterWrite as the default choice. It gives a hard upper bound on staleness. With expireAfterAccess, a frequently read entry never expires, so it can stay stale indefinitely.
The spring.cache.caffeine.spec property from the earlier chapter applies one policy to every cache. When caches need different limits, build the CaffeineCacheManager yourself and register each cache:
import com.github.benmanes.caffeine.cache.Caffeine;
import java.time.Duration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CaffeineConfig {
@Bean
CacheManager cacheManager() {
CaffeineCacheManager manager = new CaffeineCacheManager();
manager.registerCustomCache("products",
Caffeine.newBuilder()
.maximumSize(500)
.expireAfterWrite(Duration.ofMinutes(10))
.recordStats()
.build());
manager.registerCustomCache("productSearch",
Caffeine.newBuilder()
.maximumSize(2_000)
.expireAfterWrite(Duration.ofMinutes(1))
.recordStats()
.build());
return manager;
}
}Defining a CacheManager bean makes Boot's auto-configured one back off. Keep recordStats() on each cache, or the Actuator hit and miss counters from the observability chapter will stay at zero for Caffeine.
Size limits and eviction
maximumSize(500) caps the number of entries. When the cache goes over the limit, Caffeine chooses entries to evict using its Window TinyLFU policy. It favors entries that were used recently and often, so a one-time scan of many keys does not push out your hot entries. You do not choose the policy, and you do not get an LRU or FIFO switch.
Two details cause confusion:
- Caffeine does not remove entries at the exact moment they expire or exceed the limit. It does the cleanup in small batches during later reads and writes.
cache.estimatedSize()can briefly report more entries than the limit. - If your values vary a lot in size, count entries by weight instead. Use
maximumWeight(...)together with aweigher(...). You cannot combine it withmaximumSize.
Expiration in Redis
Redis stores a TTL on each key. Spring Data Redis sets that TTL when it writes the entry. The default for RedisCacheManager is no TTL at all, so keys stay forever unless you set one. The spring.cache.redis.time-to-live property from the earlier chapter sets one TTL for all caches.
For per-cache TTLs, register a customizer. The example below builds each configuration from one helper, so every cache keeps the JSON serializer and null handling you chose:
import java.time.Duration;
import org.springframework.boot.autoconfigure.cache.RedisCacheManagerBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
@Configuration
public class RedisTtlConfig {
private RedisCacheConfiguration withTtl(Duration ttl) {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(ttl)
.prefixCacheNameWith("shop::")
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));
}
@Bean
RedisCacheManagerBuilderCustomizer ttlCustomizer() {
return builder -> builder
.withCacheConfiguration("products", withTtl(Duration.ofMinutes(10)))
.withCacheConfiguration("productSearch", withTtl(Duration.ofMinutes(1)));
}
}Caches without an entry in the customizer fall back to the default configuration. This code uses the Spring Boot 3 package for the customizer. The class has moved in later major versions, so check your version if the import fails.
Redis eviction is a separate setting
The TTL above is expiration. Eviction in Redis is controlled on the server by maxmemory and maxmemory-policy, not by Spring. Two policies matter for caching:
allkeys-lruevicts the least recently used key when memory is full. This suits a Redis instance dedicated to caching.volatile-lruevicts only keys that have a TTL. If some of your keys have no TTL, they stay, and memory can still fill up.
The default policy, noeviction, rejects writes when memory is full. A cache write failure then surfaces as an exception in your service call, because Spring does not swallow cache errors by default.
Choosing a time limit
A TTL is a statement about how wrong your data is allowed to be. Work it out from the data, not from habit.
- Find the longest staleness the business accepts. A product description can be an hour old. A stock count may tolerate seconds.
- Check who else changes the data. If only your application writes it,
@CachePutand@CacheEvictkeep the cache current, and the TTL is a safety net. If another system writes to the database directly, the TTL is the only thing that bounds staleness. - Remember Caffeine is per instance. With three application instances, each holds its own copy, and an evict on one instance does not reach the others. Short TTLs are a more important safeguard there, or you can move to Redis.
Common errors
- No limits configured. A cache with no TTL and no size cap is a memory leak. Set at least one of the two, and preferably both.
- Everything expires together. If you warm 10,000 entries at startup with the same TTL, they all expire in the same second. The database then takes a burst of misses. Spread the load by using shorter TTLs on cheap data or by adding random jitter to your warm-up. Concurrent misses on a single key are a separate problem, covered in the chapter on
sync=true. - TTL too short to help. If entries expire before they are read twice, the hit rate stays near zero and you pay for caching without benefit. Check the hit and miss counters before and after changing a TTL.
- Expecting
@CacheEvictto follow the TTL. Eviction by annotation and expiration by time are independent. An entry that was explicitly evicted can be reloaded and then gets a fresh TTL. - Changing TTLs without clearing Redis. Existing keys keep the TTL they were written with. A new setting applies only to entries written afterward.
Exercise
A shop runs three instances of a Spring Boot service. Product prices are updated hourly by a separate batch job that writes straight to the database. The business accepts prices up to 5 minutes out of date. Which provider and expiration setting would you choose for the prices cache, and why does @CacheEvict not solve the problem?
Show answer
Use expireAfterWrite of 5 minutes (Caffeine) or entryTtl(Duration.ofMinutes(5)) (Redis), plus a size cap for Caffeine or allkeys-lru for Redis. The batch job bypasses the service, so no @CacheEvict or @CachePut call ever runs for its updates. The TTL is then the only mechanism that limits staleness. With Caffeine, each of the three instances keeps its own copy and the worst case is still 5 minutes, so it is acceptable here. Redis would give one shared copy, which makes the expiry moment consistent across instances.