Quick revision
The short answer
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.
What to remember
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.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
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.
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.
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.
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.
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/