Spring Boot Cache Abstraction
Overview
Spring Boot ships with a cache abstraction that wraps expensive service calls
behind annotation-driven caches. This abstraction supports multiple cache
providers (ConcurrentMap, Caffeine, Redis, Ehcache, JCache) without changing
business code. The skill provides a concise workflow for enabling caching,
managing cache lifecycles, and validating behavior in Spring Boot 3.5+ services.
When to Use
- Add
@Cacheable, @CachePut, or @CacheEvict to Spring Boot service methods.
- Configure Caffeine, Redis, or JCache cache managers for Spring Boot.
- Diagnose cache invalidation, eviction scheduling, or cache key issues.
- Expose cache management endpoints or scheduled eviction routines.
Use trigger phrases such as "implement service caching", "configure
CaffeineCacheManager", "evict caches on update", or "test Spring cache
behavior" to load this skill.
Prerequisites
- Java 17+ project based on Spring Boot 3.5.x (records encouraged for DTOs).
- Dependency
spring-boot-starter-cache; add provider-specific starters as
needed (spring-boot-starter-data-redis, caffeine, ehcache, etc.).
- Constructor-injected services that expose deterministic method signatures.
- Observability stack (Actuator, Micrometer) when operating caches in
production.
Quick Start
Add dependencies
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency> <!-- Optional: Caffeine -->
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
implementation "org.springframework.boot:spring-boot-starter-cache"
implementation "com.github.ben-manes.caffeine:caffeine"
Enable caching
@Configuration
@EnableCaching
class CacheConfig {
@Bean
CacheManager cacheManager() {
return new CaffeineCacheManager("users", "orders");
}
}
Annotate service methods
@Service
@CacheConfig(cacheNames = "users")
class UserService {
@Cacheable(key = "#id", unless = "#result == null")
User findUser(Long id) { ... }
@CachePut(key = "#user.id")
User refreshUser(User user) { ... }
@CacheEvict(key = "#id", beforeInvocation = false)
void deleteUser(Long id) { ... }
}
Verify behavior
- Run focused unit tests that call cached methods twice and assert repository
invocations.
- Inspect Actuator
cache endpoint (if enabled) for hit/miss counters.
🔄 Workflow
Kaynak: Spring Boot Caching Guide & Caffeine Cache Best Practices
Aşama 1: Strategy & Provider Selection
Aşama 2: Annotation Implementation
Aşama 3: LifeCycle & Monitoring
Kontrol Noktaları
| Aşama |
Doğrulama |
| 1 |
Transactional işlemler sırasında cache tutarlılığı (Data drift) bozuluyor mu? |
| 2 |
"Cache-aside" veya "ReadOnly" stratejisi doğru uygulandı mı? |
| 3 |
Çoklu instance yapısında "Cache Stampede" riski önlendi mi? |
Cache Patterns v2.0 - With Workflow
Advanced Options
- Integrate JCache annotations when interoperating with providers that favor
JSR-107 (
@CacheResult, @CacheRemove). Avoid mixing with Spring annotations
on the same method.
- Cache reactive return types (
Mono, Flux) or CompletableFuture values.
Spring stores resolved values and resubscribes on hits; consider TTL alignment
with publisher semantics.
- Apply HTTP caching headers using
CacheControl when exposing cached responses
via REST.
Examples
- Load
references/cache-examples.md for
progressive scenarios (basic product cache, conditional caching, multilevel
eviction, Redis integration).
- Load
references/cache-core-reference.md
for annotation matrices, configuration tables, and property samples.
References
references/spring-framework-cache-docs.md:
curated excerpts from the Spring Framework Reference Guide (official).
references/spring-cache-doc-snippet.md:
narrative overview extracted from Spring documentation.
references/cache-core-reference.md:
annotation parameters, dependency matrices, property catalogs.
references/cache-examples.md:
end-to-end examples with tests.
Best Practices
- Prefer constructor injection and immutable DTOs for cache entries.
- Separate cache names per aggregate (
users, orders) to simplify eviction.
- Log cache hits/misses only at debug to avoid noise; push metrics via Micrometer.
- Tune TTLs based on data staleness tolerance; document rationale in code.
- Guard caches that store PII or credentials with encryption or avoid caching.
- Align cache eviction with transactional boundaries to prevent dirty reads.
Constraints and Warnings
- Avoid caching mutable entities that depend on open persistence contexts.
- Do not mix Spring cache annotations with JCache annotations on the same
method.
- Ensure multi-level caches (e.g. Caffeine + Redis) maintain consistency; prefer
publish/subscribe invalidation channels.
- Validate serialization compatibility when caching across service instances.
- Monitor memory footprint to prevent OOM when using in-memory stores.
Related Skills
1---2name: cache-patterns3description: Instruction set for enabling and operating the Spring Cache abstraction in Spring Boot when implementing application-level caching for performance-sensitive workloads.4---5
6# Spring Boot Cache Abstraction
7
8## Overview
9
10Spring Boot ships with a cache abstraction that wraps expensive service calls
11behind annotation-driven caches. This abstraction supports multiple cache
12providers (ConcurrentMap, Caffeine, Redis, Ehcache, JCache) without changing
13business code. The skill provides a concise workflow for enabling caching,
14managing cache lifecycles, and validating behavior in Spring Boot 3.5+ services.
15
16## When to Use
17
18- Add `@Cacheable`, `@CachePut`, or `@CacheEvict` to Spring Boot service methods.
19- Configure Caffeine, Redis, or JCache cache managers for Spring Boot.
20- Diagnose cache invalidation, eviction scheduling, or cache key issues.
21- Expose cache management endpoints or scheduled eviction routines.
22
23Use trigger phrases such as **"implement service caching"**, **"configure
24CaffeineCacheManager"**, **"evict caches on update"**, or **"test Spring cache
25behavior"** to load this skill.
26
27## Prerequisites
28
29- Java 17+ project based on Spring Boot 3.5.x (records encouraged for DTOs).
30- Dependency `spring-boot-starter-cache`; add provider-specific starters as
31 needed (`spring-boot-starter-data-redis`, `caffeine`, `ehcache`, etc.).
32- Constructor-injected services that expose deterministic method signatures.
33- Observability stack (Actuator, Micrometer) when operating caches in
34 production.
35
36## Quick Start
37
381. **Add dependencies**
39
40 ```xml
41 <!-- Maven -->
42 <dependency>
43 <groupId>org.springframework.boot</groupId>
44 <artifactId>spring-boot-starter-cache</artifactId>
45 </dependency>
46 <dependency> <!-- Optional: Caffeine -->
47 <groupId>com.github.ben-manes.caffeine</groupId>
48 <artifactId>caffeine</artifactId>
49 </dependency>
50 ```
51
52 ```gradle
53 implementation "org.springframework.boot:spring-boot-starter-cache"
54 implementation "com.github.ben-manes.caffeine:caffeine"
55 ```
56
572. **Enable caching**
58
59 ```java
60 @Configuration
61 @EnableCaching
62 class CacheConfig {
63 @Bean
64 CacheManager cacheManager() {
65 return new CaffeineCacheManager("users", "orders");
66 }
67 }
68 ```
69
703. **Annotate service methods**
71
72 ```java
73 @Service
74 @CacheConfig(cacheNames = "users")
75 class UserService {
76
77 @Cacheable(key = "#id", unless = "#result == null")
78 User findUser(Long id) { ... }
79
80 @CachePut(key = "#user.id")
81 User refreshUser(User user) { ... }
82
83 @CacheEvict(key = "#id", beforeInvocation = false)
84 void deleteUser(Long id) { ... }
85 }
86 ```
87
884. **Verify behavior**
89 - Run focused unit tests that call cached methods twice and assert repository
90 invocations.
91 - Inspect Actuator `cache` endpoint (if enabled) for hit/miss counters.
92
93## 🔄 Workflow
94
95> **Kaynak:** [Spring Boot Caching Guide](https://spring.io/guides/gs/caching/) & [Caffeine Cache Best Practices](https://github.com/ben-manes/caffeine/wiki/Best-Practices)
96
97### Aşama 1: Strategy & Provider Selection
98- [ ] **Identifying Hot Paths**: En çok beklenen ve nadir değişen veri okuma (I/O) noktalarını belirle.
99- [ ] **Provider Selection**: Bellek içi (Caffeine) veya dağıtık (Redis) cache seçimine karar ver.
100- [ ] **Key Design**: SpEL kullanarak benzersiz ve tahmin edilebilir cache key strategy'si oluştur.
101
102### Aşama 2: Annotation Implementation
103- [ ] **@Cacheable**: Veriyi cache'e yaz we sonraki çağrılarda oradan oku.
104- [ ] **@CachePut**: Veri güncellendiğinde cache'i de yenile.
105- [ ] **@CacheEvict**: Silme işlemlerinde veya belirli periyotlarda cache'i temizle (`allEntries=true` opsiyonunu değerlendir).
106
107### Aşama 3: LifeCycle & Monitoring
108- [ ] **TTL/Eviction**: Veri tazeliği (TTL) ve temizleme (Eviction) politikalarını (LRU/LFU) konfigüre et.
109- [ ] **Actuator Audit**: `cache` endpoint'i üzerinden hit/miss oranlarını izle.
110- [ ] **Integration Testing**: `@SpringBootTest` ile cache izolasyonunu ve tutarlılığını test et.
111
112### Kontrol Noktaları
113| Aşama | Doğrulama |
114|-------|-----------|
115| 1 | Transactional işlemler sırasında cache tutarlılığı (Data drift) bozuluyor mu? |
116| 2 | "Cache-aside" veya "ReadOnly" stratejisi doğru uygulandı mı? |
117| 3 | Çoklu instance yapısında "Cache Stampede" riski önlendi mi? |
118
119---
120*Cache Patterns v2.0 - With Workflow*
121
122## Advanced Options
123
124- Integrate JCache annotations when interoperating with providers that favor
125 JSR-107 (`@CacheResult`, `@CacheRemove`). Avoid mixing with Spring annotations
126 on the same method.
127- Cache reactive return types (`Mono`, `Flux`) or `CompletableFuture` values.
128 Spring stores resolved values and resubscribes on hits; consider TTL alignment
129 with publisher semantics.
130- Apply HTTP caching headers using `CacheControl` when exposing cached responses
131 via REST.
132
133## Examples
134
135- Load [`references/cache-examples.md`](references/cache-examples.md) for
136 progressive scenarios (basic product cache, conditional caching, multilevel
137 eviction, Redis integration).
138- Load [`references/cache-core-reference.md`](references/cache-core-reference.md)
139 for annotation matrices, configuration tables, and property samples.
140
141## References
142
143- [`references/spring-framework-cache-docs.md`](references/spring-framework-cache-docs.md):
144 curated excerpts from the Spring Framework Reference Guide (official).
145- [`references/spring-cache-doc-snippet.md`](references/spring-cache-doc-snippet.md):
146 narrative overview extracted from Spring documentation.
147- [`references/cache-core-reference.md`](references/cache-core-reference.md):
148 annotation parameters, dependency matrices, property catalogs.
149- [`references/cache-examples.md`](references/cache-examples.md):
150 end-to-end examples with tests.
151
152## Best Practices
153
154- Prefer constructor injection and immutable DTOs for cache entries.
155- Separate cache names per aggregate (`users`, `orders`) to simplify eviction.
156- Log cache hits/misses only at debug to avoid noise; push metrics via Micrometer.
157- Tune TTLs based on data staleness tolerance; document rationale in code.
158- Guard caches that store PII or credentials with encryption or avoid caching.
159- Align cache eviction with transactional boundaries to prevent dirty reads.
160
161## Constraints and Warnings
162
163- Avoid caching mutable entities that depend on open persistence contexts.
164- Do not mix Spring cache annotations with JCache annotations on the same
165 method.
166- Ensure multi-level caches (e.g. Caffeine + Redis) maintain consistency; prefer
167 publish/subscribe invalidation channels.
168- Validate serialization compatibility when caching across service instances.
169- Monitor memory footprint to prevent OOM when using in-memory stores.
170
171## Related Skills
172
173- [`skills/spring-boot/spring-boot-rest-api-standards`](../spring-boot-rest-api-standards/SKILL.md)
174- [`skills/spring-boot/spring-boot-test-patterns`](../spring-boot-test-patterns/SKILL.md)
175- [`skills/junit-test/unit-test-caching`](../../junit-test/unit-test-caching/SKILL.md)