Back to Backend Development

spring-boot-cache

spring bootcachingjavaperformancerediscaffeineehcacheapplication development
282📄 MIT🕒 2026-06-15Source ↗

Install this skill

npx skills add giuseppe-trisciuoglio/developer-kit

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

The spring-boot-cache skill provides a structured approach to implementing declarative method-level caching within Spring Boot 3.5+ applications. By using the Spring cache abstraction, developers offload expensive computation or database lookups to an in-memory or distributed store, minimizing redundant processing. The skill manages the integration of various providers like Caffeine, Redis, and Ehcache, allowing application code to remain agnostic of the underlying cache storage. It guides the implementation of core annotations such as @Cacheable, @CachePut, and @CacheEvict while addressing critical concerns like SpEL-based key generation, conditional caching, and cache synchronization. This framework enables developers to optimize read-heavy service layers, manage cache lifecycles through standardized configuration, and verify operational health using Spring Actuator metrics and dedicated eviction routines.

When to Use This Skill

  • Caching frequently read, slowly changing user profile data
  • Storing computed results from expensive external API calls
  • Managing session-scoped data in local memory
  • Invalidating stale database-backed cache entries on update operations

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • implement service caching
  • configure CaffeineCacheManager
  • evict caches on update
  • test Spring cache behavior
  • optimize database queries with caching

Pro Tips

  • 💡Always define explicit cache keys using the `key` attribute to avoid unexpected behavior when method parameters change or are complex objects.
  • 💡Implement a cache health check endpoint using Spring Boot Actuator to monitor cache hits/misses and eviction policies in production.
  • 💡Consider using Spring's `CacheResolver` for dynamic cache selection based on runtime conditions, especially in multi-tenancy scenarios.

What this skill does

  • Declarative caching through method-level annotations
  • Abstracted interface supporting multiple storage providers
  • SpEL-driven cache key generation and condition evaluation
  • Synchronized data updates to prevent concurrent race conditions
  • Operational monitoring via Actuator cache endpoints

When not to use it

  • Caching highly volatile or real-time data where consistency is critical
  • Large datasets that exceed heap memory limits without distributed storage
  • Simple objects that do not justify the overhead of cache management

Example workflow

  1. Add spring-boot-starter-cache to your project dependencies
  2. Annotate the configuration class with @EnableCaching
  3. Define your CacheManager bean specifying the preferred provider
  4. Apply @Cacheable on service methods to identify cache targets
  5. Configure eviction logic via @CacheEvict to maintain data consistency
  6. Verify performance gains through Actuator metrics and unit tests

Prerequisites

  • Java 17 or higher
  • Spring Boot 3.5.x environment
  • A configured cache provider dependency

Pitfalls & limitations

  • !Mixing Spring cache annotations with JSR-107 JCache annotations
  • !Using non-deterministic SpEL keys leading to unpredictable cache misses
  • !Overlooking cache size limits causing unexpected memory pressure

FAQ

Can I switch cache providers without changing my service logic?
Yes. The abstraction layer allows you to swap providers like Caffeine or Redis by updating the CacheManager bean configuration.
How do I prevent storing null values in the cache?
Use the unless attribute in your @Cacheable annotation, such as unless = "#result == null".
What happens when multiple threads call a cacheable method simultaneously?
Setting sync = true in the @Cacheable annotation forces threads to wait for the first caller to populate the cache.
Does this skill work with reactive return types?
Spring cache handles types like Mono or Flux, though it stores the resolved value rather than the publisher.

How it compares

Unlike manual caching logic that requires boilerplate 'if-get-else-put' blocks, this skill uses a standardized, annotation-driven approach that is maintainable and integrates natively with Spring Boot's lifecycle.

Source & trust

282 stars📄 MIT🕒 Updated 2026-06-15
📄 Full skill instructions — original source: giuseppe-trisciuoglio/developer-kit
# 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

1. **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"


2. **Enable caching**

@Configuration
@EnableCaching
class CacheConfig {
@Bean
CacheManager cacheManager() {
return new CaffeineCacheManager("users", "orders");
}
}


3. **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) { ... }
}


4. **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.

## Implementation Workflow

### 1. Define Cache Strategy

- Map hot-path read operations to @Cacheable.
- Use @CachePut on write paths that must refresh cache entries.
- Apply @CacheEvict (allEntries = true when invalidating derived caches).
- Combine operations with @Caching to keep multi-cache updates consistent.

### 2. Shape Cache Keys and Conditions

- Generate deterministic keys via SpEL (e.g. key = "#user.id").
- Guard caching with condition = "#price > 0" for selective caching.
- Prevent null or stale values with unless = "#result == null".
- Synchronize concurrent updates via sync = true when needed.

### 3. Manage Providers and TTLs

- Configure provider-specific options:
- Caffeine spec: spring.cache.caffeine.spec=maximumSize=500,expireAfterWrite=10m
- Redis TTL: spring.cache.redis.time-to-live=600000
- Ehcache XML: define ttl and heap/off-heap resources.
- Expose cache names via spring.cache.cache-names=users,orders,catalog.
- Avoid on-demand cache name creation in production unless metrics cover usage.

### 4. Operate and Observe Caches

- Surface cache maintenance via a dedicated CacheManagementService with
programmatic cacheManager.getCache(name) access.
- Schedule periodic eviction for time-bound caches using @Scheduled.
- Wire Actuator cache endpoint and Micrometer meters to track hit ratio,
eviction count, and size.

### 5. Test and Validate

- Prefer slice or unit tests with Mockito/SpyBean to ensure method invocation
counts.
- Add integration tests with Testcontainers for Redis/Ehcache when using
external providers.
- Validate concurrency behavior under load (e.g. sync = true scenarios).

## 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](references/cache-examples.md) for
progressive scenarios (basic product cache, conditional caching, multilevel
eviction, Redis integration).
- Load [references/cache-core-reference.md](references/cache-core-reference.md)
for annotation matrices, configuration tables, and property samples.

## References

- [references/spring-framework-cache-docs.md](references/spring-framework-cache-docs.md):
curated excerpts from the Spring Framework Reference Guide (official).
- [references/spring-cache-doc-snippet.md](references/spring-cache-doc-snippet.md):
narrative overview extracted from Spring documentation.
- [references/cache-core-reference.md](references/cache-core-reference.md):
annotation parameters, dependency matrices, property catalogs.
- [references/cache-examples.md](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

- [skills/spring-boot/spring-boot-rest-api-standards](../spring-boot-rest-api-standards/SKILL.md)
- [skills/spring-boot/spring-boot-test-patterns](../spring-boot-test-patterns/SKILL.md)
- [skills/junit-test/unit-test-caching](../../junit-test/unit-test-caching/SKILL.md)

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/spring-boot-cache/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/giuseppe-trisciuoglio/developer-kit/spring-boot-cache/SKILL.md
  • Cursor: ~/.cursor/skills/giuseppe-trisciuoglio/developer-kit/spring-boot-cache/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/giuseppe-trisciuoglio/developer-kit/spring-boot-cache/SKILL.md

🚀 Install with CLI:
npx skills add giuseppe-trisciuoglio/developer-kit

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid backend development issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under Backend Development and is published by Giuseppe Trisciuoglio, maintained in giuseppe-trisciuoglio/developer-kit.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.