Skip to content
Spring Boot Redis Caching: Beyond @Cacheable — Serialization, Keys, and Pitfalls

Spring Boot Redis Caching: Beyond @Cacheable — Serialization, Keys, and Pitfalls

This article explains how to properly implement Redis caching in Spring Boot using @Cacheable, @CachePut, and @CacheEvict, covering JSON serialization, key design, annotation failure scenarios, memory eviction policies, cache penetration/breakdown/avalanche prevention, consistency patterns, and template selection.

Code Farmer Manor Chronicle
Code Farmer Manor Chronicle
Code Farmer Manor Chronicle

Three Annotations Cover Read, Write, Delete

Most projects implement caching manually with try { redis.get() } catch blocks and JSON serialization, resulting in more cache logic than business logic. Spring provides @EnableCaching plus three annotations to handle CRUD caching declaratively.

@Service
public class UserService {

    @Cacheable(cacheNames = "user", key = "#id", unless = "#result == null")
    public User getById(Long id) {
        return userMapper.selectById(id); // only executes on cache miss
    }

    @CachePut(cacheNames = "user", key = "#user.id")
    public User update(User user) {
        userMapper.updateById(user); // always executes, return value written to cache
        return user;
    }

    @CacheEvict(cacheNames = "user", key = "#id")
    public void delete(Long id) {
        userMapper.deleteById(id); // delete DB and cache simultaneously
    }
}

Division of responsibilities: @Cacheable: method may not execute (cache hit skips body). Do not put logging or side effects inside. @CachePut: method always executes, return value updates cache. @CacheEvict: method always executes, removes cache entry (use allEntries = true to clear entire cacheNames).

Pitfall 1: Serialization (99% Encounter This)

Without explicit configuration, Spring Data Redis uses JDK serialization, producing unreadable binary keys and values (e.g., "\xac\xed\x00\x05sr\x00\x0ecom.example.User..."). Consequences: unreadable during production debugging, and cross-language incompatibility.

Configure JSON serialization:

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public RedisCacheConfiguration cacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(30))
                .disableCachingNullValues()
                .serializeKeysWith(SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
    }

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
        return RedisCacheManager.builder(factory)
                .cacheDefaults(cacheConfiguration())
                .build();
    }
}

Each line matters: StringRedisSerializer makes keys readable strings (default keys are binary). entryTtl(30min) sets a default TTL for all caches — this is the most important setting. disableCachingNullValues() prevents null from entering cache, complementing unless = "#result == null". GenericJackson2JsonRedisSerializer writes a @class field into JSON to remember type, enabling correct deserialization of User and List<User>. Trade-off: renaming or moving the class breaks deserialization of old cache entries — clear cache before refactoring or use a type-less serializer with explicit type parameters.

Pitfall 2: Key Design

cacheNames = "user"

becomes key prefix user::1 (double colon). Relying solely on cacheNames causes collisions:

Problem 1: Different methods under same cacheNames may collide (e.g., getById(1L) key 1 vs getByEmail("[email protected]") key "[email protected]" — if both keys become numeric they collide). Solution: embed business prefix in key expression: key = "'id:' + #id", key = "'email:' + #email".

Problem 2: SpEL throws NullPointerException when parameter is null. Write key = "#id ?: 'null'" or validate parameters first.

Problem 3: Different data needs different TTL (dictionary 24h, user 30min, captcha 5min). Configure per-cache TTL via withInitialCacheConfigurations:

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
    RedisCacheConfiguration base = cacheConfiguration();
    return RedisCacheManager.builder(factory)
            .cacheDefaults(base)
            .withInitialCacheConfigurations(Map.of(
                    "dict",  base.entryTtl(Duration.ofHours(24)),
                    "user",  base.entryTtl(Duration.ofMinutes(30)),
                    "captcha", base.entryTtl(Duration.ofMinutes(5))
            ))
            .build();
}

Pitfall 3: Annotation Suddenly Stops Working

Annotations rely on AOP proxy. Three scenarios bypass the proxy:

Internal method call: this.getById(id) inside same class skips proxy. Fix: move method to another bean, or inject self with @Lazy (awkward; prefer separate bean).

Non-public methods: private / protected methods are not intercepted.

Class not a Spring bean: Objects created with new have no proxy; annotations are decorative.

Troubleshooting order: check these three first. Direct verification: look in Redis for the key — if key exists, caching worked; problem lies elsewhere.

Expiration and Eviction: Prevent Redis Memory Exhaustion

Annotations handle when to write , not how much memory . Must explicitly configure:

maxmemory 512mb
maxmemory-policy allkeys-lru

Redis defaults to noeviction — writes fail with OOM command not allowed when used memory > 'maxmemory' when full. Eviction policies: noeviction (default): writes error when full — never use for caching . allkeys-lru: evicts least recently used among all keys — preferred for pure caching . volatile-lru: evicts only keys with TTL set — suitable when same instance runs caching and important data. allkeys-lfu: evicts least frequently used — good for clear hotspot workloads.

Hidden prerequisite: eviction policies work effectively only when keys have expiration. Keys without TTL (e.g., SET without EX) are invisible to volatile-lru, leading to OOM. Therefore entryTtl default is mandatory — a cache without TTL will eventually cause trouble .

Application-Layer Prevention of Penetration, Breakdown, Avalanche

Penetration : Query non-existent data, every request hits DB. Fix: cache empty value (short TTL) or use Bloom filter.

Breakdown : Hot key expires, concurrent requests hit DB. Fix: @Cacheable(sync = true) or mutex rebuild.

Avalanche : Mass keys expire simultaneously. Fix: add random offset to TTL.

Breakdown detail: sync = true adds a local JVM lock so only one thread reloads the key.

@Cacheable(cacheNames = "user", key = "#id", sync = true)
public User getById(Long id) { ... }

Caveat: sync = true uses a local lock — works for single instance, but in multi-instance deployments each instance acquires its own lock, so DB still gets hammered. For multi-instance, use distributed lock (e.g., Redisson) or accept the load.

Avalanche mitigation: scatter TTL with random seconds.

.entryTtl(Duration.ofMinutes(30).plusSeconds(ThreadLocalRandom.current().nextInt(300)))

Trade-off: keys in same batch expire at different times; analytics must not assume simultaneous invalidation.

Consistency: Update DB First, Then Delete Cache

Only conclusion given (principles covered in architecture series):

@Transactional
public void updateUser(User user) {
    userMapper.updateById(user); // 1. update DB first
    redis.delete("user::id:" + user.getId()); // 2. delete cache (not update)
}

Three rules:

Delete cache, don't write it. Writing risks stale values under concurrency; deletion forces next read to reload.

Order: DB update then cache delete. Reverse order (delete then update) leaves a window where a read fetches old value and writes it back, persisting dirty data.

Even update-then-delete can have brief inconsistency under extreme concurrency (read occurs between update and delete, writes old value back). Strong consistency requires delayed double-delete or binlog subscription.

StringRedisTemplate vs RedisTemplate

When annotations fall short, manual coding is needed. Choose template:

StringRedisTemplate : key/value are Strings, store JSON strings. Human-readable, cross-language friendly. Beginners should always use this.

RedisTemplate : defaults to JDK serialization (source of the \xac\xed garbage). Either reconfigure serializer or avoid.

@Autowired
private StringRedisTemplate redis;

public User getWithCache(Long id) {
    String key = "user:id:" + id;
    String json = redis.opsForValue().get(key);
    if (json != null) return JSON.parseObject(json, User.class);

    User u = userMapper.selectById(id);
    if (u != null) {
        redis.opsForValue().set(key, JSON.toJSONString(u), 30, TimeUnit.MINUTES);
    }
    return u;
}

This manual code mirrors annotation behavior but makes serialization and TTL explicit. Manual is not safer, just more verbose — prefer annotations where possible.

Checklist

@EnableCaching

+ three annotations: read with @Cacheable, write with @CachePut, delete with @CacheEvict.

Mandatory JSON serialization: keys with StringRedisSerializer, values with GenericJackson2JsonRedisSerializer.

Mandatory default entryTtl; per-business TTL via withInitialCacheConfigurations.

Key includes business prefix; handle null parameters with #id ?: 'null'.

Annotation failure troubleshooting: internal call, non-public, non-bean. maxmemory + maxmemory-policy allkeys-lru must be set; default noeviction causes hard errors.

Breakdown: use sync = true but remember it's a local lock — ineffective in clustered deployments.

Consistency: update DB then delete cache; delete instead of write.

Caching is easy to add, hard to get right. Each item above seems like a detail, but together they separate "cache works" from "cache causes daily incidents."

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.

RedisSerializationCachingSpring BootConsistencyKey DesignCache Patterns@Cacheable
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.