Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Configure a RedisCacheManager in Spring Boot so that all caches store values as JSON with a 10 minute TTL, the cache "rates" uses a 30 second TTL, and null values are not cached. Explain what the default configuration would have done instead.

Try it yourself

Cache-aside: one read, three cache states

See what a cache hit saves, what a miss costs, and why a write deletes the cached entry instead of updating it.

Read this example as text

When the entry is in the cache (a hit)

  1. A request arrives. A caller asks the service for product 42. The cache already holds it.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Hit: the value comes back. The entry is there and still fresh, so the cache answers at once. The database is never touched.

1 cache call, 0 database reads.

When it was never cached (a miss)

  1. A request arrives. A caller asks the service for product 42. Nobody has asked for it before, so the cache holds nothing.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. The key was never stored. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When its time to live has run out

  1. A request arrives. A caller asks the service for product 42. The cache held it once, but its time to live ran out 12 seconds ago.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. An expired key is the same as a missing one: Redis no longer returns it, and removes it. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When the price changes afterwards

  1. The price changes. Later, someone updates the price to 25. The service writes the database first: UPDATE products SET price = 25 WHERE id = 42.
  2. Delete the cached entry. Then it deletes the key: DEL product:42. It does not write 25 into the cache. Deleting is simpler and safer: the next read misses and loads whatever the database holds then.
  3. The next read will miss. The cache is empty for this key again, so the next request repeats the miss path and stores 25.

3 cache calls, 1 database read, 1 database write.

What this example leaves out
  • One request at a time. Two requests missing at the same moment (a stampede) are not shown.
  • The write deletes the key. Some systems update the cache instead, which this example does not model.
  • The numbers are counts of round trips, not measured times.

We define a RedisCacheConfiguration bean built from defaultCacheConfig() with entryTtl(Duration.ofMinutes(10)), disableCachingNullValues() and a JSON value serializer, and a RedisCacheManagerBuilderCustomizer that adds withCacheConfiguration("rates", ...) with a 30 second TTL. Without this, the default configuration would have kept entries forever, cached nulls, and stored values with JDK serialization, which needs Serializable classes and ties every cached entry to the exact class version; keys would still be prefixed with the cache name and two colons.

Why this question is asked

Moving a cache from an in-process map to Redis is usually a few lines of configuration, and that is exactly why it goes wrong: the defaults are chosen to be safe for any type, not to be good for production. A service that ships with them stores binary Java objects with no expiry, and the problems appear months later during a deployment or a memory alarm. Interviewers ask this coding question to check that we know what the defaults are and how to override them globally and per cache. In this answer, we will recap how Spring Boot builds the RedisCacheManager, write the configuration, see what each line changes, compare it with the property-only approach, and look at what the defaults would have done.

1A Quick Recap: How Boot Builds the RedisCacheManager

When spring-boot-starter-data-redis is on the classpath and caching is enabled, Spring Boot auto-configures a RedisCacheManager. It needs a configuration for each cache: the TTL (time to live, how long an entry stays in Redis), whether null values may be stored, how keys are prefixed and how keys and values are turned into bytes, which is called serialization.

Boot looks for a RedisCacheConfiguration bean and uses it as the default for every cache. If there is none, it builds one from the spring.cache.redis.* properties. On top of that, any RedisCacheManagerBuilderCustomizer bean can adjust the builder, which is where per-cache settings go. Notice one detail: if we define our own RedisCacheConfiguration bean, the spring.cache.redis.* properties are no longer applied, because our bean replaces the one Boot would have built from them.

2Writing the Configuration

Here is the configuration for the requirements: JSON values, a 10 minute default TTL, 30 seconds for rates, and no cached nulls.

Java
@Configuration
@EnableCaching
class CacheConfig {
@Bean
RedisCacheConfiguration cacheConfiguration() {
return RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)) // every cache: 10 minutes
.disableCachingNullValues() // a null result is not stored
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer())); // values as JSON
}
@Bean
RedisCacheManagerBuilderCustomizer ratesTtl(RedisCacheConfiguration base) {
return builder -> builder.withCacheConfiguration("rates",
base.entryTtl(Duration.ofSeconds(30))); // only "rates": 30 seconds
}
}
// In Redis after rateService.rate("EURUSD") and productService.find(42):
// rates::EURUSD -> {"@class":"com.shop.Rate","pair":"EURUSD","value":1.0832} TTL 30
// products::42 -> {"@class":"com.shop.Product","id":42,"name":"Lamp"} TTL 600

Notice that RedisCacheConfiguration is immutable: each method returns a new configuration. That is why base.entryTtl(...) in the customizer gives rates its own TTL while keeping JSON and the null rule from the base. The keys stay readable strings because the default key serializer is already a string serializer.

3What Each Setting Changes at Runtime

entryTtl makes RedisCache write every entry with an expiry, so Redis itself removes it when the time is up. With disableCachingNullValues(), the cache refuses null values instead of storing a null marker. Be aware that @Cacheable will then fail if it tries to put a null into such a cache, so pair this with unless = "#result == null" on methods that can return null, or Spring will throw an exception saying the cache does not allow null values (check your version for the exact message).

The JSON serializer writes a readable document. GenericJackson2JsonRedisSerializer adds a type property such as @class so it can rebuild the right class when reading. In newer Spring Data Redis versions, which move to Jackson 3, the serializer classes have new names; check your version for the Jackson 3 based serializer names.

4The Property-Only Alternative

For simple global settings we can skip the beans entirely.

Properties
spring.cache.type=redis
spring.cache.redis.time-to-live=10m
spring.cache.redis.cache-null-values=false
# key-prefix and use-key-prefix are also available

Properties cannot set a JSON serializer or a per-cache TTL, so for our requirements we need the beans. And as noted above, once we define a RedisCacheConfiguration bean, these properties stop being applied, so mixing the two leads to settings that look configured but are silently ignored.

5What the Default Configuration Would Have Done

Without our beans or properties, defaultCacheConfig() would have applied four things, and each one causes a known production problem.

Default versus our configuration
SettingDefaultOurs
TTLnone: entries never expire10 minutes, rates 30 seconds
Null valuescached (as a special null marker)not cached
Value formatJDK serialization, binaryJSON with a type property
Key formatcacheName::keycacheName::key (unchanged)

6Why JDK Serialization Is the Problematic Default

JDK serialization only works for classes that implement Serializable, so the first call often fails with a SerializationException for an ordinary DTO. Worse, the bytes are tied to the exact class: if the class has no explicit serialVersionUID, almost any change to it makes old entries unreadable after the next deployment. Entries are also opaque, so we cannot inspect them with redis-cli, and other languages cannot read them. JSON avoids all three problems, at the cost of slightly larger values and the need to think about how class changes affect old documents.

7Follow-up questions

What are the risks of storing type information in the JSON?

The @class property names a Java class, so renaming or moving the class breaks every entry written before the change, just like JDK serialization. Polymorphic type handling is also a security concern: if the deserializer accepts any class name it finds, a value written by an attacker could make it instantiate a dangerous class. Safer options are a serializer bound to one type per cache, such as Jackson2JsonRedisSerializer<Rate> configured per cache, or a restricted type validator, and versioned key prefixes so old documents are never read by new code.

Why give rates a shorter TTL instead of evicting on change?

Exchange rates change continuously and often come from an external feed, so there is no single update method to annotate with @CacheEvict. A 30 second TTL makes the staleness bound explicit and needs no coordination. For data that changes through our own code, eviction on write plus a TTL safety net is usually better.

Would the TTL be reset on every read?

No. RedisCache sets the expiry when it writes the entry, and reads do not change it by default, so the TTL behaves like expireAfterWrite. Newer Spring Data Redis versions can be configured for time-to-idle behaviour; check your version if you need it.

8Conclusion

In this answer, we configured a RedisCacheManager with a RedisCacheConfiguration bean based on defaultCacheConfig(), giving every cache a 10 minute TTL, no cached nulls and JSON values, and used a RedisCacheManagerBuilderCustomizer to give rates its own 30 second TTL. We saw that spring.cache.redis.time-to-live and cache-null-values cover simple global settings but are ignored once our own configuration bean exists. The defaults would have kept entries forever, cached nulls and stored values with JDK serialization, which needs Serializable types and breaks when classes change, while keys keep the cacheName:: prefix either way.

What to say in the interviewAbout 80 seconds aloud

Open with

I would define a RedisCacheConfiguration bean starting from RedisCacheConfiguration.defaultCacheConfig(), call entryTtl with Duration.ofMinutes(10), disableCachingNullValues(), and serializeValuesWith a JSON serializer such as GenericJackson2JsonRedisSerializer. Spring Boot uses that bean as the default configuration for every cache.

Then, if they want more

Then I would add a RedisCacheManagerBuilderCustomizer that calls withCacheConfiguration("rates", base.entryTtl(Duration.ofSeconds(30))). Because the configuration is immutable, rates keeps JSON and the null rule but gets its own TTL. For methods that can return null I would also add unless #result == null, since the cache now refuses nulls.

If I only needed a global TTL and no nulls, the properties spring.cache.redis.time-to-live and spring.cache.redis.cache-null-values would be enough, but they cannot set the serializer or per-cache TTLs, and they are ignored once I define my own configuration bean.

The defaults would have been quite different: no TTL at all, so entries live forever; null values cached; and values written with JDK serialization, which requires Serializable classes, is unreadable with redis-cli, and breaks old entries whenever the class changes. Keys would have been the same, the cache name plus two colons plus the key.

I would also mention that with newer Spring Data Redis the Jackson 3 serializer names differ, so I would check the version.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Configure a RedisCacheManager in Spring Boot so that all caches store values as JSON...": https://scrivio-interview-library.netlify.app/databases/caching/61aa5e6dab/