Sub topic 12
Expiration and eviction policies
This chapter assumes you can already annotate methods with @Cacheable, @CachePut and @CacheEvict, and that you have picked Caffeine or Redis as a provider. Here you will decide how long entries live and what happens when a cache grows too large.
Expiration versus eviction
Two different mechanisms remove entries, and people often confuse them.
- Expiration removes an entry because of time. A time-to-live (TTL) says how long the entry is considered valid.
- Eviction removes an entry because of space. When the cache hits a size limit, the provider drops entries to make room.
Expiration protects you from stale data. Eviction protects you from running out of memory. A cache with neither grows until the JVM or Redis server fails.
Write-based and access-based expiry
Caffeine supports two time rules.
expireAfterWritestarts the clock when the entry is created or replaced. Use it when data has a known freshness limit.expireAfterAccessrestarts the clock on every read. Use it for rarely needed data, but remember that a popular entry may never expire and can stay stale indefinitely.
spring.cache.type=caffeine
spring.cache.cache-names=products,productSearch
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m,recordStatsmaximumSize=500 is the eviction rule. Caffeine uses the Window TinyLFU policy, which keeps entries that are used often and recently, so you do not pick LRU or LFU yourself. The size limit is applied approximately and in the background, so the cache may briefly exceed 500 entries.
The spec string applies to every cache the manager creates. Spring Boot does not let you give each cache its own Caffeine spec through properties.
Per-cache TTL in Redis
Redis has no maximumSize in Spring's configuration. The spring.cache.redis.time-to-live property sets one TTL for all caches. When caches need different lifetimes, use a customizer:
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;
@Configuration
public class CacheTtlConfig {
@Bean
RedisCacheManagerBuilderCustomizer cacheTtls() {
return builder -> builder
.withCacheConfiguration("products",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)))
.withCacheConfiguration("productSearch",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(1)));
}
}Eviction in Redis is handled by the server. Set maxmemory and a maxmemory-policy such as allkeys-lru in the Redis configuration. With the default noeviction policy, Redis rejects writes when memory is full, and cache writes then fail.
Choosing values
| Data | Suggested rule |
|---|---|
| Rarely changes (country list) | Long TTL, such as hours |
| Changes through your app | Moderate TTL plus `@CachePut` or `@CacheEvict` |
| Search results with many keys | Short TTL and a size limit |
A TTL is the safety net, not the main consistency tool. Keep evicting or updating entries on writes, and let the TTL catch the cases you missed.
Clearing everything
To drop a whole cache, for example after a bulk import, use allEntries:
@CacheEvict(cacheNames = "products", allEntries = true)
public void reloadCatalog() {
// reload data from the source
}Exercise
A Caffeine cache uses maximumSize=500,expireAfterAccess=10m. A product page is read every minute, and the product price changes in the database. Why can users see the old price for hours, and what is the smallest spec change that fixes it?
Show answer
Each read restarts the 10-minute access timer, so the entry never expires. Add expireAfterWrite=10m (or use it instead of expireAfterAccess), so the entry is reloaded at most 10 minutes after it was written, no matter how often it is read.