Sub topic 9
Choosing a cache provider
This chapter assumes you can build a Spring Boot application, define beans, manage dependencies with Maven or Gradle, and edit application.properties. You should also have used @EnableCaching and @Cacheable. The chapter covers how Spring Boot picks a provider, what the main options are, and how to decide between them.
What a provider is
The annotations you have used so far do not store anything. They call a CacheManager, and the CacheManager hands out Cache objects. A cache provider is the library that sits behind those two interfaces and actually holds the entries.
Your service code stays the same when you change providers. Only the dependency and the configuration change. That is the main benefit of the abstraction, and it lets you start with something simple and move later.
How Spring Boot picks a provider
Boot auto-configures a CacheManager when two conditions hold. Caching is enabled with @EnableCaching, and you have not defined your own CacheManager bean (or a CacheResolver). It then looks for a provider in a fixed order and uses the first one it can configure:
- Generic (only if you define
Cachebeans) - JCache (JSR-107), for example EhCache 3 or Hazelcast
- Hazelcast
- Infinispan
- Couchbase
- Redis
- Caffeine
- Cache2k
- Simple, which is a
ConcurrentHashMap
The last entry is the fallback. If nothing else is on the classpath, you silently get the simple map. It has no size limit and no expiration, so entries stay until the process exits or you evict them. This is fine for a demo and risky in production.
Two consequences follow from this ordering:
- Adding a second provider library can change which one wins. If both Redis and Caffeine are on the classpath and you set nothing else, Redis is chosen because it comes earlier in the list.
- You can end the guessing by setting
spring.cache.typeexplicitly.
spring.cache.type=caffeineIf the named provider is not on the classpath, the application fails at startup. That failure is useful, because it catches a missing dependency before users do. Setting spring.cache.type=none disables caching through a no-op manager, which is handy in tests or when you need to rule out the cache while debugging.
The main options
| Provider | Where entries live | Shared between instances | Expiration | Typical use |
|---|---|---|---|---|
| Simple (`ConcurrentHashMap`) | JVM heap | No | None | Demos, tests |
| Caffeine | JVM heap | No | Per cache, by spec | Single instance or read-heavy data that tolerates small differences between nodes |
| Redis | Separate server | Yes | Per cache, by TTL | Multiple instances, data that must be consistent across nodes |
| JCache (EhCache, Hazelcast) | Heap, off-heap, or cluster | Depends on the implementation | Provider-specific | Existing standards or clustering needs |
The next two chapters configure Caffeine and Redis in detail. Here the goal is to choose between them.
Local caches: Caffeine
A local cache keeps entries inside the application's own JVM. A lookup is a method call on a map-like structure. There is no network hop, no serialization, and the cached object is the same instance you stored. That makes it the fastest option, usually by a wide margin over any remote cache.
Caffeine adds what the simple map lacks: a maximum size, time-based expiration, and statistics. It uses an eviction algorithm (Window TinyLFU) that keeps frequently used entries and drops rarely used ones, which gives good hit rates for typical workloads.
The costs are specific:
- Memory. Entries consume heap that your application also needs. A cache with no size limit can cause
OutOfMemoryError. - Per-instance state. If you run three instances, you have three independent caches. After an update, one instance can evict its entry while the other two keep serving the old value until it expires.
- Cold starts. Each new instance begins empty, and a restart discards everything.
Remote caches: Redis
Redis is a separate server that all your application instances talk to. Every instance sees the same entries, so an eviction from one instance is visible to the rest. The cache survives application restarts, and its memory is not part of your JVM heap.
The costs mirror the benefits of a local cache:
- Latency. Each lookup is a network round trip, typically around a millisecond rather than nanoseconds to microseconds.
- Serialization. Values must be converted to bytes. By default
RedisCacheManageruses JDK serialization, which requiresSerializableclasses and produces opaque data. Most teams switch to JSON. - Another system to run. Redis can be down or slow, and your application must decide what happens when it is.
JCache and others
JCache is a Java standard API (JSR-107) that several libraries implement. Choose it if your organization already standardizes on EhCache or Hazelcast, or if you need features such as off-heap storage or a data grid. For most new Spring Boot projects, Caffeine or Redis covers the need with less setup.
Decision criteria
Ask these questions in order.
- Does more than one instance serve traffic? If not, a local cache has no consistency problem, and Caffeine is the natural choice.
- Can stale reads be tolerated for a short, bounded time? If yes, Caffeine with a short expiration works even with several instances. If an update must be visible everywhere immediately, you need a shared cache such as Redis.
- How large is the data? If the working set does not fit comfortably in the heap alongside your application, use Redis.
- Are values expensive to serialize? Large or deeply nested objects cost more in Redis. A local cache avoids that cost.
- Must the cache survive restarts? Only a remote cache does that.
Using both
Some systems combine the two. A small local cache sits in front of Redis, so hot entries are served from memory and the rest from the shared cache. Spring Boot does not auto-configure this. You build it with a custom CacheManager, or with a library that provides a two-level cache. It adds complexity, particularly around invalidation, so adopt it only when measurements show Redis latency is a problem.
Declaring caches and checking the result
With Caffeine or Redis you can list cache names in properties. Boot then creates only those caches, and any other name used in an annotation raises an IllegalArgumentException for an unknown cache. If you omit the list, caches are created on demand with the default settings.
spring.cache.type=caffeine
spring.cache.cache-names=products,productSearch
spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10mTo see which manager Boot chose, inject it and print its class at startup.
@Component
public class CacheManagerReport implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(CacheManagerReport.class);
private final CacheManager cacheManager;
public CacheManagerReport(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
@Override
public void run(String... args) {
log.info("CacheManager: {}", cacheManager.getClass().getName());
log.info("Caches: {}", cacheManager.getCacheNames());
}
}With Caffeine configured, the first line shows org.springframework.cache.caffeine.CaffeineCacheManager. If you see ConcurrentMapCacheManager, your provider dependency is missing or was not picked up.
Common mistakes
- Shipping the simple fallback. No provider on the classpath means no size limit and no expiration. Set
spring.cache.typeexplicitly so a missing dependency fails at startup. - Using a local cache across instances for data that must be consistent. Evictions affect only the instance that runs them.
- Leaving Redis on JDK serialization. Class changes between deployments can break deserialization of existing entries, and the stored bytes are hard to inspect.
- Mixing providers by accident. A transitive dependency can bring in another provider and change the auto-configuration result. Check the startup log.
Exercise
Your service runs as four instances behind a load balancer. Product prices change a few times a day, and a price must not be served stale for more than a few seconds after a change. You are choosing between Caffeine alone and Redis. Which do you choose, and what would make you reconsider?
Show answer
Choose Redis. With Caffeine, each instance has its own cache, so an @CacheEvict on one instance leaves the other three serving the old price until their entries expire. To meet a "few seconds" limit with Caffeine you would need an expireAfterWrite of a few seconds, which lowers the hit rate and defeats much of the purpose. Redis gives all four instances one shared entry, so one eviction or @CachePut is visible to all. Reconsider if measurements show the Redis round trip is too slow for your latency budget. Then a short expireAfterWrite on Caffeine, or a local cache in front of Redis, becomes an option, as long as the bounded staleness is acceptable.
Exercise
An application has spring-boot-starter-cache and the Caffeine library as dependencies, but at startup the log shows ConcurrentMapCacheManager. Name two likely causes.
Show answer
First, spring.cache.type may be set to simple or another value, or a different provider earlier in the detection order may have been selected. Second, the Caffeine dependency may not be on the runtime classpath, for example because of a wrong scope, or the application defines its own CacheManager bean, which stops auto-configuration. Setting spring.cache.type=caffeine makes the first and second cases fail loudly if the dependency is missing.