Using Caffeine Cache in Spring Boot: Algorithms, Configuration, and Code Examples

This article introduces Caffeine Cache, explains its W‑TinyLFU eviction algorithm, compares it with Guava, and provides detailed usage examples—including manual, synchronous, and asynchronous loading, eviction policies, Spring Boot integration, annotations, and configuration snippets—for building high‑performance backend caches.

Top Architect
Top Architect
Top Architect
Using Caffeine Cache in Spring Boot: Algorithms, Configuration, and Code Examples

The article begins by recalling Guava Cache’s features—thread‑safe get/put, expiration, and eviction—and notes its reliance on LRU. It then introduces Caffeine Cache, which builds on Guava’s ideas but adopts the modern W‑TinyLFU algorithm to achieve near‑optimal hit rates.

Algorithm advantages : Caffeine combines LFU and LRU via W‑TinyLFU, using a Count‑Min Sketch to track recent access frequencies with a sliding‑window reset that halves counters after a fixed number of inserts, thus handling both steady‑state and bursty workloads.

Cache filling strategies :

Manual loading – specify a function in cache.get(key, k -> computeValue(k)).

Synchronous loading – provide a CacheLoader when building the cache.

Asynchronous loading – use AsyncLoadingCache with CompletableFuture for non‑blocking loads.

Eviction policies :

Size‑based eviction via .maximumSize() or .maximumWeight().

Time‑based eviction with .expireAfterWrite(), .expireAfterAccess(), or a custom Expiry implementation.

Reference‑based eviction using .weakKeys(), .weakValues(), or .softValues() (mutually exclusive).

Statistics : Enable with .recordStats() and retrieve hit rate, eviction count, and load penalty via cache.stats().

Spring Boot integration :

Include the dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>com.github.ben-manes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
    <version>2.6.2</version>
</dependency>

Enable caching with @EnableCaching and configure Caffeine via properties (e.g.,

spring.cache.caffeine.spec=initialCapacity=50,maximumSize=500,expireAfterWrite=10s

) or Java beans. A sample bean creates a SimpleCacheManager with two caches (userCache, deptCache) using Caffeine.newBuilder() and sets TTL and maximum size.

Define a CacheLoader<Object,Object> bean when using refreshAfterWrite so that the cache can refresh entries after the configured interval.

Use Spring’s cache annotations: @Cacheable(value="userCache", key="#id", sync=true) for read‑through caching. @CachePut(value="userCache", key="#user.id") for updates. @CacheEvict(value="userCache", key="#user.id") for deletions.

Annotations support SpEL for keys, conditions, and synchronization, and can be combined with @Caching or @CacheConfig for class‑level defaults.

The article also warns about incompatibilities (e.g., AsyncLoadingCache cannot use weak/soft references, CacheWriter cannot be used with weak keys), and provides best‑practice tips for choosing eviction strategies based on workload characteristics.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaCachecachingCaffeineSpringBoot
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.