Provides Redis integration patterns for Spring Boot: cache-aside, key naming, TTL strategy, and JSON serialization config. Useful when implementing caching, session storage, or rate limiting.
Ships in spring-boot-3-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(jsonSerializer()); // JSON, not Java serialization
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jsonSerializer());
return template;
}
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer()))
.disableCachingNullValues();
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.transactionAware() // put/evict only after the surrounding transaction commits
.withCacheConfiguration("orders", config.entryTtl(Duration.ofMinutes(5)))
.withCacheConfiguration("products", config.entryTtl(Duration.ofHours(1)))
.build();
}
// Records are final, so DefaultTyping.NON_FINAL writes no type id for them and every
// cache read fails ("missing type id property '@class'"). The builder's defaultTyping(true)
// types user classes too; the validator limits type ids to an allow-list instead of
// LaissezFaire's "any class". BigDecimal is non-final, so java.math must be allowed.
private GenericJackson2JsonRedisSerializer jsonSerializer() {
ObjectMapper mapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.polymorphicTypeValidator(BasicPolymorphicTypeValidator.builder()
.allowIfSubType("com.example.") // your DTO packages
.allowIfSubType("java.util.")
.allowIfSubType("java.math.")
.allowIfSubType("java.time.")
.build())
.build();
return GenericJackson2JsonRedisSerializer.builder()
.objectMapper(mapper)
.defaultTyping(true)
.build();
}
}
{app}:{domain}:{id} → orders:order:uuid-here
{app}:{domain}:list:{filter} → orders:order:list:status:PENDING
{app}:session:{userId} → orders:session:uuid-here
{app}:ratelimit:{ip} → orders:ratelimit:192.168.1.1
@Service
@RequiredArgsConstructor
public class ProductService {
@Cacheable(value = "products", key = "#id")
public ProductResponse findById(UUID id) {
return productRepository.findById(id)
.map(ProductResponse::from)
.orElseThrow(() -> new EntityNotFoundException("Product not found: " + id));
}
@CachePut(value = "products", key = "#result.id") // update cache after write
@Transactional
public ProductResponse update(UUID id, UpdateProductRequest request) {
Product product = productRepository.findById(id).orElseThrow();
product.update(request);
return ProductResponse.from(productRepository.save(product));
}
@CacheEvict(value = "products", key = "#id") // invalidate on delete
@Transactional
public void delete(UUID id) {
productRepository.deleteById(id);
}
@CacheEvict(value = "products", allEntries = true) // clear all
public void clearCache() {}
}
@Service
@RequiredArgsConstructor
public class OrderCacheService {
private final RedisTemplate<String, Object> redisTemplate;
private final ObjectMapper objectMapper;
private static final Duration TTL = Duration.ofMinutes(5);
public Optional<OrderResponse> get(UUID orderId) {
String key = "orders:order:" + orderId;
Object cached = redisTemplate.opsForValue().get(key);
if (cached == null) return Optional.empty();
return Optional.of(objectMapper.convertValue(cached, OrderResponse.class));
}
public void put(OrderResponse order) {
String key = "orders:order:" + order.id();
redisTemplate.opsForValue().set(key, order, TTL);
}
public void evict(UUID orderId) {
redisTemplate.delete("orders:order:" + orderId);
}
}
Use AtomicWindowLimiter with StringRedisTemplate. It runs a single-key Lua script: the first allowed request creates the counter and expiry in one SET; later requests increment only below the limit and do not extend the window. Separate INCR and EXPIRE calls can leave a permanent counter if the client fails between them.
This is a first-request-anchored fixed window, not a sliding window or token bucket; bursts across expiry are possible. The example restricts windows to 1ms through one day. Derive the bounded bucket from trusted tenant/principal and operation data, not arbitrary client keys. Keep quota/window settings consistent across callers, bound key cardinality and use a dedicated namespace. The v2 prefix avoids reusing counters leaked by the old non-atomic example.
Redis errors propagate: choose the endpoint's explicit fail-closed or fail-open policy; do not silently grant permission on infrastructure failure. Do not pipeline this boolean decision. Redis restart/failover can lose counters; this is traffic control, not a financial quota ledger. Test simultaneous requests, expiry, scope isolation and unavailable Redis against real Redis. See Redis INCR rate-limiter discussion and Spring Data Redis scripting.
spring:
data:
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
password: ${REDIS_PASSWORD:}
timeout: 2000ms
lettuce:
pool:
max-active: 10
max-idle: 5
min-idle: 2
cache:
type: redis
sync = true delegates loading coordination to the cache provider. The default Redis writer
in the configuration above is non-locking: do not claim that this annotation alone prevents
duplicate loads, even inside one application instance.
For expensive read-only loads, the optional
CoalescingRedisCacheManager uses a locking
writer with a finite lock TTL. Register it under a distinct bean name, keeping your normal
cache manager primary, and pass a JSON-serialized RedisCacheConfiguration:
@Cacheable(cacheManager = "coalescingCacheManager", value = "products", key = "#id", sync = true)
public ProductResponse findById(UUID id) { ... }
Add this bean method to the shown RedisConfig, reusing its jsonSerializer() helper,
and mark the normal cacheManager bean @Primary so existing annotations stay unchanged:
@Bean("coalescingCacheManager")
RedisCacheManager coalescingCacheManager(RedisConnectionFactory factory) {
var config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5))
.disableCachingNullValues()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonSerializer()));
return CoalescingRedisCacheManager.create(factory, config, Duration.ofSeconds(10));
}
The writer lock is cache-wide, not per key: unrelated misses may block too. Configure finite loader/transport timeouts and a lock TTL longer than the expected load, and test contention. Lock expiry during a stalled load can still permit duplicates; this is load reduction, not an exactly-once guarantee or protection for payment/order mutations. Redis command timeouts do not bound the writer's entire lock-wait loop. Use a bounded caller deadline or a different coalescing strategy when strict waiting bounds are required.
Use sync loading only for committed, read-only data; transaction-aware put/evict does not make
the loader-based cache get transactional. Prefer TTL jitter or local coalescing when the
cache-wide lock would reduce throughput excessively. Do not implement a bare SETNX/delete
lock without ownership tokens, atomic owner-checked release and a lease-expiry design.
See Spring Redis cache behavior.
| Usage | Redis unavailable | Recovery concern |
|---|---|---|
| Disposable read cache | Optionally fall back to the source, with bounded concurrency | Avoid a database overload during an outage |
| Write-side eviction | Do not silently ignore failures | A committed DB update can leave stale cached values; use bounded TTL plus durable invalidation when needed |
| Authentication/session/authorization | Do not grant access because Redis failed | Return a controlled unavailable response or require reauthentication |
| Security rate limit | Fail closed or use an explicitly approved bounded fallback | Never silently allow unlimited traffic |
OptionalCacheLookup demonstrates narrow read-side
fallback for connection failures and timeouts, with an observability callback. It deliberately
does not suppress serialization errors or write/eviction failures. Recovery restores cache
reads; do not assume transactionAware() makes Redis and the database one atomic transaction.
Verification must include concurrent misses, TTL expiration, DTO round-trips (including money/time fields), rollback, outage fallback and recovery. A short negative-cache TTL can be useful for repeated misses; disabling null caching is an example choice, not a universal rule.
The repository fixture targets Boot 3.5.16 with Java 17/21 and checks Redis 7.4 serialization, TTL, normal concurrent loads and transaction callbacks; not failover or lease-expiry correctness. Check the coverage matrix before treating another minor version or an illustrative snippet as verified.
@Transactional with @CachePut/@CacheEvict on a non-transaction-aware cache manager — the cache can be updated before commit (or evicted then re-filled with stale data); build it with .transactionAware()INCR then EXPIRE calls — a failure between them leaves a TTL-less key that blocks the caller forever; use one Lua scriptjava.util. for default typing — BigDecimal is non-final and carries a type id, so cached prices/totals fail to deserialize; allow java.math. (and java.time.) tooGenericJackson2JsonRedisSerializer)new GenericJackson2JsonRedisSerializer() — its plain mapper has no JSR-310 module, so any Instant/LocalDate field fails to serialize; build it with JavaTimeModule@EnableCaching — @Cacheable silently does nothing without itsync = true guarantees a single load - verify the provider/writer and test concurrent misses.agents/openai.yaml (opens in a new tab)examples/bad-cache-service.java (opens in a new tab)examples/good-cache-service.java (opens in a new tab)templates/AtomicWindowLimiter.java (opens in a new tab)templates/CoalescingRedisCacheManager.java (opens in a new tab)templates/OptionalCacheLookup.java (opens in a new tab)templates/RedisConfig.java (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
44 skills in this plugin
/agent-qa-browser-regressionUse when verifying an existing browser journey with agent-qa against a running Spring Boot application. Covers target selection, scoped execution, run evidence, and memidex provenance while preserving backend tests and security contracts.
/ai-observabilityUse when adding Spring AI-specific model observations, token usage, latency, externally configured cost attribution, advisor telemetry, or protected prompt and completion logging. Use production-observability for general service metrics, health, logs, and OTLP setup.
/api-versioningUse when versioning Spring MVC or WebFlux APIs in Spring Boot 3 / Spring Framework 6. Covers explicit URL, header, and media-type strategies, compatibility rules, and deprecation handling.
/async-executionUse when adding or debugging Spring @Async work, executor saturation, asynchronous failures or lost thread context. Not a substitute for durable jobs or reactive pipelines.
/configuration-propertiesUse when introducing or correcting grouped Spring Boot configuration, typed property binding, validation, profiles or secret injection. Do not rewrite unrelated single-value configuration.
/container-native-deploymentUse when packaging a Spring Boot 3 application as an OCI image or GraalVM native executable. Covers buildpacks, layered images, JVM containers, AOT hints, probes, security, and verification.
/spring-boot-3-skills:spring-data-redisfrom spring-boot-3-skills
npx claudepluginhub rrezartprebreza/spring-boot-skills --plugin spring-boot-3-skillsOther plugins' skills for the same job