Video in progress

Strong Junior ⚡ Redis and caching

Which serializer should you use to write objects to a Redis cache in Spring, and what is wrong with the default?

The default JdkSerializationRedisSerializer uses Java serialization: the class must be Serializable, Redis holds bytes you can't read, and if the class changes, old entries become unreadable. In practice you switch to a JSON serializer.

📖 Answer

A typical prod incident with the JDK serializer: you add a new field to a DTO, deploy, and reading the old entries in the cache throws SerializationException / InvalidClassException. If serialVersionUID isn't set, this is guaranteed.

The JSON variant:

@Bean
RedisCacheConfiguration cacheConfig() {
    var json = new GenericJackson2JsonRedisSerializer();   // JSON + @class field
    return RedisCacheConfiguration.defaultCacheConfig()
        .serializeValuesWith(SerializationPair.fromSerializer(json))
        .entryTtl(Duration.ofMinutes(10));
}

GenericJackson2JsonRedisSerializer writes an @class field into the JSON, so if you rename the class or move the package, old entries still break. If one cache holds one type, Jackson2JsonRedisSerializer<ProductDto> is the cleaner option.

Either way, when the format changes, the reliable approach is to add a version to the key prefix or to clear that cache during the deploy.