Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Configure Spring Cache with Redis so that product lookups are cached for 10 minutes, and explain the cache-aside behaviour.

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 add spring-boot-starter-cache and spring-boot-starter-data-redis, put @EnableCaching on a configuration class, set spring.cache.type=redis and spring.cache.redis.time-to-live=10m, and annotate the lookup with @Cacheable("products"). That gives cache-aside behaviour: on each call Spring checks Redis first, returns the cached value on a hit, and on a miss runs the method and stores its result for ten minutes. Changes go through @CacheEvict or @CachePut, and because caching works through a proxy, a call from inside the same class skips the cache.

Why this question is asked

Caching a product lookup is often the first performance fix a service gets, and it is easy to do almost right. The common mistakes are stale data after an update, a cache that never works because of self-invocation, and values that cannot be read because of the serializer. Interviewers ask this to check that we can configure it and that we understand the cache-aside pattern well enough to reason about staleness. In this answer, we will recap what cache-aside means, add the dependencies and configuration, annotate the methods, follow a hit and a miss step by step, handle updates, and look at the proxy rule.

1A Quick Recap of Cache-Aside

Cache-aside, also called lazy loading, is a pattern where the application, not the database, manages the cache. To read, it first looks in the cache. If the value is there, a hit, it uses it. If not, a miss, it reads from the database, puts the result in the cache, and returns it. The cache only ever holds data someone asked for, and each entry has a time to live, a TTL, after which Redis deletes it so the next read fetches fresh data.

Spring's cache abstraction implements this pattern for us through annotations. We describe which methods are cacheable, and Spring wraps them in a proxy, a generated object that sits in front of our bean and runs the cache logic before and after the real method.

2Dependencies and Configuration

We need the cache abstraction, the Redis client, and caching switched on.

Java
// build.gradle
implementation "org.springframework.boot:spring-boot-starter-cache"
implementation "org.springframework.boot:spring-boot-starter-data-redis"
# application.yml
spring:
data.redis.host: localhost
cache:
type: redis
redis:
time-to-live: 10m # every cache entry expires after 10 minutes
@Configuration
@EnableCaching
class CacheConfig {
@Bean // optional: different TTL per cache, JSON values instead of JDK serialization
RedisCacheManagerBuilderCustomizer caches() {
return b -> b
.withCacheConfiguration("products", RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.serializeValuesWith(SerializationPair.fromSerializer(RedisSerializer.json())))
.withCacheConfiguration("prices", RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(1)));
}
}

spring.cache.type=redis makes the choice explicit; Spring Boot would also pick Redis when it is the available provider. The time-to-live property applies to every cache. The customizer bean shows how to give each cache its own TTL and how to store values as JSON; by default the Redis cache manager stores values with JDK serialization, so cached classes must implement Serializable and appear as binary in redis-cli. Check your Spring Data Redis version for the JSON serializer class, since Jackson 3 support renamed some of them.

3Annotating the Lookup and Following a Call

Now we mark the method. The cache name is products, and by default the key is built from the method arguments, here the product id.

Java
@Service
class ProductService {
@Cacheable("products")
public Product find(String id) {
log.info("loading {} from the database", id);
return repo.findById(id).orElseThrow();
}
}
service.find("42"); // log: loading 42 from the database; Redis now has key products::42 with TTL 600 s
service.find("42"); // no log: served from Redis
// 10 minutes later the key expires
service.find("42"); // log again: miss, reload, store
Step throughCache-aside through the proxy
ControllerCache proxyRedisProductServiceDatabase
find("42")
GET products::42
nil (miss)
call real method
SELECT ... WHERE id = 42
row
Product
SET products::42 EX 600
Product

9 messages in order. Play them, or step through them one at a time.

On a hit, the proxy returns after the GET and the service and database are never called.

Notice that the second call never reaches our method body; the proxy returns the cached value directly. By default Spring also caches null results, so a lookup for a missing product does not hammer the database; that can be switched off with disableCachingNullValues(), or skipped per method with unless = "#result == null". A method that throws, as orElseThrow does here, stores nothing.

4Keeping the Cache Correct When Products Change

A cached product stays in Redis for up to ten minutes. If the price changes and we do nothing, readers see the old price until the entry expires. So the methods that change products tell the cache.

Java
@CacheEvict(value = "products", key = "#p.id")
public void update(Product p) { repo.save(p); } // removes products::42; next read reloads
@CachePut(value = "products", key = "#result.id")
public Product rename(String id, String name) { // always runs, then stores the returned value
Product p = repo.findById(id).orElseThrow();
p.setName(name);
return repo.save(p);
}
@CacheEvict(value = "products", allEntries = true)
public void reloadCatalogue() { ... }

Eviction is usually the safer choice. With @CachePut, two concurrent updates can finish in a different order in Redis than in the database and leave the older value cached. Eviction only removes the entry, and the next read loads the current row. Notice also that the TTL remains our safety net: even if an update path forgets to evict, the stale value lives at most ten minutes.

5The Proxy Rule: Self-Invocation Skips the Cache

The annotations only work when a call goes through the proxy. A call from one method of ProductService to another method of the same class uses this, the real object, so the proxy and the cache are skipped.

Java
public List<Product> findAll(List<String> ids) {
return ids.stream().map(this::find).toList(); // never cached: this.find bypasses the proxy
}

The fix is to call the cached method from another bean, or move it into a small dedicated class. The same rule applies to @Transactional and @Async, and so do the other proxy rules: the method must be public in the usual configuration, and calls during construction are not intercepted.

6Follow-up questions

What is the sync attribute on @Cacheable for?

With sync = true, concurrent misses for the same key in one application instance wait for the first caller to load the value instead of all hitting the database. It does not coordinate across instances, so ten pods can still load the same key once each, which is usually acceptable.

Is cache-aside consistent with the database?

Not strictly. Between the database write and the eviction there is a brief window where readers see the old value, and a reader that loaded just before the update can put the old value back after the eviction. TTLs bound how long such a stale entry lives, which is why they should match how stale the business can tolerate.

How do you test that caching works?

In an integration test with Redis in Testcontainers, call the method twice and verify with a spy or a counter that the repository was called once, then call the evicting method and verify the next read hits the repository again.

7Conclusion

In this answer, we configured Spring Cache with Redis using the cache and Redis starters, @EnableCaching, spring.cache.type=redis and a 10 minute TTL, with a customizer for per-cache TTLs and JSON values. We followed the cache-aside flow through the proxy: check Redis, return on a hit, run the method and store the result on a miss. We kept data fresh with @CacheEvict, preferred over @CachePut because of ordering races, and saw that self-invocation bypasses the proxy and therefore the cache.

What to say in the interviewAbout 90 seconds aloud

Open with

I would add spring-boot-starter-cache and spring-boot-starter-data-redis, put @EnableCaching on a configuration class, and set spring.cache.type to redis and spring.cache.redis.time-to-live to 10m. If different caches need different TTLs, or I want JSON values instead of the default JDK serialization, I add a RedisCacheManagerBuilderCustomizer with a RedisCacheConfiguration per cache name.

Then, if they want more

Then I put @Cacheable with the name products on the lookup method. The behaviour is cache-aside: the call goes through a Spring proxy, which builds the key from the arguments, like products::42, and does a GET in Redis. On a hit it returns the cached product without running my method.

On a miss it runs the method, which reads the database, stores the result with the ten minute TTL, and returns it. Nulls are cached by default, which protects the database from repeated lookups of missing ids, but exceptions are not.

For changes, I put @CacheEvict on the update method so the next read loads fresh data; I prefer evict over @CachePut because concurrent puts can leave an older value in Redis. And the TTL is the safety net if an update path forgets.

The classic trap is self-invocation: if another method in the same class calls find through this, the proxy is skipped and nothing is cached, so the cached method has to be called from another bean.

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.
Official documentation
Spring Data reference
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 Spring Cache with Redis so that product lookups are cached for 10 minutes, and...": https://scrivio-interview-library.netlify.app/databases/spring-data-nosql/266fc823a4/