Sub topic 10
Configuring Caffeine for a local cache
This chapter covers how to set up Caffeine as the cache provider in a Spring Boot application. It assumes you can already use @Cacheable, @CachePut and @CacheEvict, that you know how @EnableCaching works, and that you can edit application.properties and your Maven or Gradle dependencies. The code uses the ProductService from the earlier chapters.
What Caffeine is and when it fits
Caffeine is a Java in-memory caching library. Entries live on the JVM heap of one application instance. Reads and writes are fast because there is no network hop and no serialization. Values are stored as live Java objects.
This has two consequences:
- Each application instance has its own cache. If you run three instances, you have three independent caches that can disagree with each other.
- The cache is lost when the process restarts.
Caffeine fits data that is read often, is expensive to compute, and can tolerate being briefly stale or slightly different between instances. Examples are reference data, product lookups, and the results of slow remote calls. If all instances must see the same value at once, look at a shared cache such as Redis, covered in the next chapter.
Adding the dependencies
Spring Boot detects Caffeine when it is on the classpath. You need the cache starter and the Caffeine library. The Spring Boot dependency management supplies the Caffeine version, so you don't set one.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>With @EnableCaching on your application class, Boot's auto-configuration then creates a CaffeineCacheManager. If more than one supported provider is on the classpath, set spring.cache.type=caffeine to choose explicitly. Being explicit also makes the build fail early if the library is missing, rather than silently falling back to a simple ConcurrentHashMap cache.
Configuring with properties
The quickest way to configure Caffeine is through properties.
# build.gradle / pom.xml: spring-boot-starter-cache and com.github.ben-manes.caffeine:caffeine
spring.cache.type=caffeine
spring.cache.cache-names=products,productSearch
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m,recordStatsEach line does a specific job:
spring.cache.type=caffeineselects the provider.spring.cache.cache-nameslists the caches to create at startup. Boot then refuses to create other caches on demand. If a method uses@Cacheable("reports")andreportsis not in the list, startup or the first call fails with an "Cannot find cache named" error. Leave the property out if you want caches created dynamically.spring.cache.caffeine.specis a compact configuration string that Caffeine parses.
The spec string
The spec is a comma-separated list of settings. The most useful ones are in this table.
| Setting | Meaning |
|---|---|
| `maximumSize=500` | Keep at most 500 entries per cache. Beyond that, Caffeine evicts entries it judges least useful. |
| `expireAfterWrite=10m` | Remove an entry 10 minutes after it was created or last replaced. |
| `expireAfterAccess=5m` | Remove an entry 5 minutes after it was last read or written. |
| `refreshAfterWrite=1m` | Reload an entry in the background after 1 minute. This needs a loader, which the Spring abstraction does not provide. |
| `recordStats` | Collect hit and miss counters. Required for useful metrics. |
Durations take the suffixes d, h, m and s. There is no ms suffix in the spec.
The last entry in the table is a trap. refreshAfterWrite only works with a Caffeine LoadingCache, and Spring's CaffeineCacheManager builds plain caches unless you supply a loader. Setting it in the spec string causes an error at startup. For an intermediate setup, use expireAfterWrite instead.
The spec applies to every cache the manager creates. products and productSearch above both get the same size and expiry. If you need different settings per cache, you need Java configuration.
Expiry choices: write versus access
The two expiry styles behave differently, and the choice matters for staleness.
expireAfterWritebounds how old a value can be. A product cached at 09:00 with a 10-minute limit is gone by 09:10, no matter how often it is read. This gives you a hard ceiling on staleness.expireAfterAccesskeeps popular entries alive. A value read every minute never expires, so it can stay stale indefinitely unless you evict it with@CacheEvictor replace it with@CachePut.
For data that changes outside your application, such as rows modified by another service, prefer expireAfterWrite. Use expireAfterAccess mainly to free memory for entries nobody reads, and combine it with expireAfterWrite when you want both behaviours.
How size limits work
maximumSize counts entries, not bytes. 500 small Product records and 500 large search result lists count the same. If your values vary widely in size, a count limit does not bound memory well. Caffeine also supports maximumWeight with a weigher, but the spec string cannot supply a weigher, so that needs Java configuration.
Eviction is not exactly first-in, first-out. Caffeine uses a policy called Window TinyLFU, which favours entries that are both recent and frequently used. This means a one-off burst of unique keys, such as a crawler requesting thousands of different search terms, is less likely to push out your hot entries than it would be under a simple least-recently-used policy.
Size eviction is also asynchronous. Right after you exceed the limit, the cache can briefly hold slightly more entries than the maximum. Don't write tests that assert an exact count immediately after insertion.
Configuring in Java for per-cache settings
When caches need different settings, define the CacheManager yourself. This code registers one cache with its own limits and uses defaults for the rest.
import java.time.Duration;
import java.util.List;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class LocalCacheConfig {
@Bean
CacheManager cacheManager() {
CaffeineCache products = new CaffeineCache("products",
Caffeine.newBuilder()
.maximumSize(1_000)
.expireAfterWrite(Duration.ofMinutes(30))
.recordStats()
.build());
CaffeineCache productSearch = new CaffeineCache("productSearch",
Caffeine.newBuilder()
.maximumSize(200)
.expireAfterWrite(Duration.ofMinutes(2))
.recordStats()
.build());
SimpleCacheManager manager = new SimpleCacheManager();
manager.setCaches(List.of(products, productSearch));
return manager;
}
}Search results are cached for a short time and in smaller numbers because they go stale faster and take more memory. Single products live longer.
Two details matter here:
- Once you declare a
CacheManagerbean, Boot's auto-configuration backs off. Thespring.cache.caffeine.specproperty no longer has any effect, and neither doesspring.cache.cache-names. Keep settings in one place to avoid confusion. SimpleCacheManagerhas a fixed set of caches. A method that names an unregistered cache fails. That is usually what you want, since a typo in a cache name then fails loudly.
If you only want to customise Boot's manager, for example to add a shared Caffeine builder, you can declare a Caffeine bean or a CacheManagerCustomizer instead of replacing the manager.
Null values and mutable values
The CaffeineCacheManager that Boot creates allows null values by default, and wraps them internally. That is why the earlier findById used unless = "#result == null". Without it, a lookup for a missing product caches the miss, and later lookups return null even after the product is created, until the entry expires or is evicted.
Because Caffeine stores object references, not copies, a caller that modifies a returned object changes the cached one. A Product record is immutable, so it is safe. A mutable List returned from searchByName is not. Return an unmodifiable list, as Stream.toList() does, or copy it before returning.
Checking that it works
Add management.endpoints.web.exposure.include=health,caches,metrics, call a cached method twice, then request /actuator/metrics/cache.gets?tag=result:hit. Without recordStats, the counters stay at zero, which can look like caching is not working when it is.
Common mistakes
- Forgetting
recordStats, then finding no hit or miss metrics. - Listing
cache-namesand then using a cache name that is not in the list. - Declaring your own
CacheManagerand expecting the properties to still apply. - Using
expireAfterAccessalone for data that changes elsewhere. - Expecting every instance in a cluster to share cached values.
Exercise
You set spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m and later add a @Bean CacheManager with a SimpleCacheManager containing one cache named products. A method annotated @Cacheable("reports") now throws an error, and the 10 minute expiry no longer applies to products. Explain both effects and give a fix.
Show answer
Declaring your own CacheManager bean makes Boot's cache auto-configuration back off, so the spring.cache.caffeine.spec property is ignored and products uses whatever you built in Java. SimpleCacheManager only knows the caches you registered, so reports is unknown and the call fails. Fix it by registering a CaffeineCache named reports and setting expireAfterWrite(Duration.ofMinutes(10)) on the builder for each cache. Alternatively, remove the custom bean and let the properties configure the manager.