In-Memory Caching with Caffeine Tuning
Configure Caffeine eviction, expiry, and size policies for high-throughput local caches.
Why Caffeine for Local Caches
Caffeine is a high-performance, near-optimal Java caching library and the default in-memory cache for Spring Boot when it is on the classpath.
- It uses the Window TinyLFU eviction policy, which beats plain LRU on real-world hit rates.
- It supports size-based, time-based, and reference-based eviction.
- It is fully concurrent and lock-free on the read path, ideal for high-throughput services.
In this lesson you will tune Caffeine's eviction, expiry, and size policies so a local cache stays fast without exhausting heap.
Adding Caffeine to a Spring Boot 4 App
Spring Boot auto-configures Caffeine when both spring-boot-starter-cache and the caffeine dependency are present.
Then enable caching with @EnableCaching on a configuration class. Methods annotated with @Cacheable will use the Caffeine-backed CacheManager.
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {
// CaffeineCacheManager is auto-configured
// when com.github.ben-manes.caffeine:caffeine is on the classpath
}All lessons in this course
- The Spring Cache Abstraction Fundamentals
- In-Memory Caching with Caffeine Tuning
- Distributed Caching with Redis and TTLs
- Cache Stampede, Invalidation, and Consistency