Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Design the caching of product details in a Spring Boot service with Redis using cache-aside. Cover reads, writes, invalidation, serialization and what happens when Redis is unavailable.

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.

Reads use @Cacheable(cacheNames = "product", key = "#id") with a RedisCacheManager: a miss loads from the database and writes the entry with a TTL. Writes update the database first and then evict the key with @CacheEvict, ideally after the transaction commits, rather than writing the new value, to avoid races that leave stale data. Values are stored as JSON with versioned DTOs and prefixed keys, not JDK serialization, and short Lettuce timeouts plus a CacheErrorHandler make Redis failures behave like misses, while we measure hit ratio, latency and evictions and cache only data whose staleness for the TTL is acceptable.

Why this question is asked

Caching product details is one of the first things teams add when a product page gets popular, and it is easy to do badly: stale prices after an update, deserialization errors after a deploy, or a service that goes down with Redis. Interviewers ask this design question to see whether we can cover the whole lifecycle, not just the annotation. In this answer, we will recap cache-aside, design the read path, the write and invalidation path, choose serialization and keys, handle Redis being unavailable, and decide what to measure.

1A Quick Recap of Cache-Aside

In cache-aside, also called lazy loading, the application owns the logic. It reads from the cache first; on a miss it reads from the database and puts the result into the cache. On a change, it updates the database and removes or updates the cached copy. Redis never talks to the database itself. The database stays the source of truth, and the cache is a disposable copy that may be slightly behind for at most its TTL.

2The Read Path

Spring's cache abstraction lets us express the read path with an annotation, and Spring Boot configures a RedisCacheManager when Spring Data Redis is on the classpath and caching is enabled.

Java
@Configuration
@EnableCaching
class CacheConfig {
@Bean
RedisCacheManagerBuilderCustomizer productCache(ObjectMapper mapper) {
var json = new Jackson2JsonRedisSerializer<>(mapper, ProductView.class); // typed JSON
return b -> b.withCacheConfiguration("product",
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10))
.prefixCacheNameWith("catalog:v2:") // service and version
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(json)));
}
}
@Service
class ProductService {
@Cacheable(cacheNames = "product", key = "#id")
public ProductView find(long id) {
return ProductView.from(repository.findById(id).orElseThrow());
}
}
// find(42) first call: database query, key catalog:v2:product::42 written, TTL 600 s
// find(42) again: served from Redis, no query
Step throughRead path on a miss
ControllerProductService proxyRedisDatabase
find(42)
GET catalog:v2:product::42
nil: miss
select product 42
row
SET ... EX 600 with JSON
ProductView

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

Notice that we cache a ProductView, a DTO made for this purpose, not the JPA entity. Entities carry lazy-loading proxies and fields the page never needs, and their shape changes with the database; a small view class is cheaper to serialize and changes only on purpose.

3The Write Path and Invalidation

When a product changes, we update the database first and then evict the cache key, rather than writing the new value into the cache. The reason is races. If two updates run at nearly the same time and each writes its value to the cache after its database write, the cache can end up holding the older value if the writes to Redis arrive in the opposite order to the database commits. Evicting cannot leave a wrong value behind: the next read loads whatever the database holds.

Java
@Transactional
@CacheEvict(cacheNames = "product", key = "#id")
public void changePrice(long id, BigDecimal price) {
repository.findById(id).orElseThrow().setPrice(price);
}
// evicts catalog:v2:product::42; the next find(42) loads the new price

But there is a catch with timing. By default the eviction runs when the method returns, which can be just before the transaction commits. A read arriving in that tiny gap misses, loads the old row, still uncommitted from its point of view, and caches the old price for ten minutes. Two remedies help. RedisCacheManager can be made transaction-aware with transactionAware() in its builder, which delays cache puts and evictions until after commit; or we publish an event and evict in a @TransactionalEventListener with phase AFTER_COMMIT. A rare race remains, a slow reader writing an old value after the eviction, and the TTL bounds how long that can last, which is one reason every entry has one.

4Serialization and Keys

The default RedisCacheConfiguration uses JDK serialization, which is a poor fit: values are unreadable in redis-cli, every class must implement Serializable, a renamed field breaks deserialization after a deploy, and deserializing untrusted bytes is a known security risk. JSON is readable and tolerant of added fields. GenericJackson2JsonRedisSerializer stores type information so one serializer handles many classes; a typed Jackson2JsonRedisSerializer per cache, as above, stores cleaner JSON without class names. Spring Data Redis 4 adds Jackson 3 variants, so check your version for the class names.

We also version the data. The key prefix catalog:v2: names the service and the version of ProductView. When we make an incompatible change to the DTO, we bump it to v3; new instances read and write v3 keys, old instances keep using v2 during a rolling deploy, and the v2 keys expire on their own. The prefix also keeps two services that share a Redis from colliding on a cache named product.

5When Redis Is Unavailable

The cache must make the service faster, never less available. Two settings achieve that. First, short timeouts on the Lettuce client, so a slow or unreachable Redis costs a request a few hundred milliseconds at most, not the default of a minute. Second, a CacheErrorHandler that logs cache errors and lets the call continue, so a failed get becomes a miss and the method runs against the database, and a failed put or evict is logged.

Java
# application.yml
spring:
data:
redis:
timeout: 200ms
connect-timeout: 500ms
@Configuration
class CacheErrors implements CachingConfigurer {
@Override public CacheErrorHandler errorHandler() { return new LoggingCacheErrorHandler(); }
}
// Redis down: find(42) logs a cache error and returns from the database, status 200

But there is a catch with failed evictions: if Redis is briefly unreachable during changePrice(), the old value may survive until its TTL. For product details that is usually acceptable; for data where it is not, we would retry the eviction or not cache that field. We also check that the database can survive the load of running without the cache, or add a bulkhead on the loader so it cannot be overwhelmed.

6Measuring and Choosing What to Cache

We measure the hit ratio, Redis latency, evictions and cache errors. RedisCacheManager can record statistics with enableStatistics(), and Spring Boot exposes cache metrics through Micrometer. A hit ratio far below 80 percent on product details suggests the TTL is too short or the keys are too varied; rising evictions suggest the instance is too small.

Finally, we cache only data where serving a value up to the TTL old is acceptable. A description or image list can be ten minutes stale; stock levels and the price used at checkout should come from the database, or from a much shorter cache, so a customer is never charged a price that changed.

7Follow-up questions

How would you invalidate across several services caching the same data?

The owning service publishes a ProductChanged event after commit, through Kafka or Redis pub/sub, and each caching service evicts its own key when it receives it. Pub/sub is fire-and-forget, so missed messages are possible; a durable event stream is safer, and the TTL remains the backstop for anything missed. Alternatively, services can share one cache owned by the product service, but that couples them to its key format.

Why not write through, putting the new value in the cache on update?

It can work with a single writer, but with concurrent updates the cache writes can arrive out of order and leave an older value cached until the TTL. Evicting is simpler and always converges to the database state on the next read, at the cost of one extra miss after each change.

Should null results be cached?

Caching a not-found result protects the database from repeated lookups of missing ids, which can be an attack pattern, but it also hides a product that is created a moment later. A short TTL for negative results, or a separate cache for them, is a common compromise; by default RedisCacheConfiguration caches nulls unless we call disableCachingNullValues().

8Conclusion

In this answer, we designed cache-aside product caching with Redis in Spring Boot. Reads use @Cacheable with a RedisCacheManager and a TTL; writes update the database and evict the key, after commit through a transaction-aware cache manager or an AFTER_COMMIT listener. Values are typed JSON of versioned DTOs under service and version prefixes, not JDK serialization. Short Lettuce timeouts and a CacheErrorHandler turn Redis failures into misses, and we measure hit ratio, latency and evictions while caching only data that may be stale for the TTL.

What to say in the interviewAbout 80 seconds aloud

Open with

I would use cache-aside with Spring's cache abstraction and a RedisCacheManager. For reads, @Cacheable with cacheNames product and key #id: on a miss the method loads from the database and Spring writes the entry with a TTL, say ten minutes, configured in RedisCacheConfiguration.

Then, if they want more

I cache a small view DTO, not the JPA entity. For writes, I update the database first and then evict the key with @CacheEvict rather than putting the new value, because concurrent updates could write the cache out of order and leave stale data, while an eviction always converges on the next read.

I make the eviction happen after commit, with a transaction-aware cache manager or an AFTER_COMMIT event listener, so a read cannot re-cache the old row in between, and the TTL bounds any remaining race.

For serialization I use JSON, for example GenericJackson2JsonRedisSerializer or a typed Jackson serializer, never JDK serialization, and I prefix keys with the service and DTO version so incompatible changes just use new keys. If Redis is unavailable, short Lettuce timeouts and a CacheErrorHandler that logs and treats errors as misses keep the service working on the database.

Finally I measure hit ratio, latency and evictions, and only cache data whose staleness for the TTL is acceptable, so not checkout prices or stock.

About this answer

Last updated
12 November 2026
Versions it names
Redis 4
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
Redis documentation
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 "Design the caching of product details in a Spring Boot service with Redis using...": https://scrivio-interview-library.netlify.app/databases/redis/9a154bbc16/