Caching
31 questions in 9 subtopics.
Spring Cache abstraction
Explain how Spring's cache abstraction intercepts a call to a method annotated with@Cacheable after you add @EnableCaching. Which beans are involved, how is the cache key computed by default, and how does Spring Boot decide which CacheManager to create?A developer reports that caching does not work. The class is:@Service
class PriceService {
public List<Price> pricesFor(List<Long> ids) {
return ids.stream().map(this::price).toList();
}
@Cacheable("prices")
public Price price(Long id) {
return repo.load(id);
}
}
pricesFor hits the database. Why, and what are the fixes?You are adding caching to a product service that runs 12 instances behind a load balancer. Product details change a few times a day, prices change every few minutes, and stock levels change constantly. Using the Spring cache abstraction, how would you decide what to cache, with which provider, and with what expiry for each kind of data?Thirty teams in your organisation use Spring caching in different ways: some use Redis with JDK serialization, some use unbounded ConcurrentMapCacheManager in production, and nobody exports cache metrics. What standards would you set, and how would you roll them out through a shared starter without breaking teams?Over ten years your teams have written caching code against provider APIs directly (Ehcache 2, Hazelcast, Redis clients) and against Spring's cache abstraction. Provider changes have been expensive each time. What long-term rule would you set for how application code uses caches, and what are its limits?@Cacheable, @CachePut, @CacheEvict
In Spring's caching annotations, what is the difference between the condition and unless attributes, and what does@Cacheable(sync = true) change? Give an example where using condition instead of unless is a bug.Write the annotations for a ProductService with three methods: Product find(long id) should be cached in cache "products" but null results must not be cached; Product update(Product p) must refresh the cached entry; void delete(long id) must remove the entry. Explain what each annotation does at runtime.Two methods in different services share one cache name: @Cacheable("lookup") Country byCode(String code) and @Cacheable("lookup") Currency byIso(String iso). After deployment, callers of byIso sometimes get a ClassCastException. Explain the cause and how you would fix it and prevent it.An order service method annotated @Transactional and @CacheEvict(cacheNames = "orders", key = "#id") updates an order. Under load, readers sometimes see the old order for the whole TTL after the update succeeded. Explain the race and how to fix it.Caffeine
Explain the difference betweenexpireAfterWrite, expireAfterAccess and refreshAfterWrite in Caffeine, and how you would configure a Caffeine cache in Spring Boot through properties.Why can Caffeine evict an entry that was inserted recently while keeping older entries, and what does that mean for caches with a one-off scan of many keys, such as a nightly report?A service holds a Caffeine cache of 2 million customer profiles with maximumSize set and no weigher. After a release that added fields to the profile, the service starts spending a lot of time in GC and old generation usage stays near the limit. What do you investigate and change?Redis caching
Configure aRedisCacheManager 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.After a deployment that renamed a field in the cached Customer class, a service using Redis caching returns errors for some customers with SerializationException while others work. Explain the cause and how you would recover now and avoid it in future.Your Redis cluster had a 10 minute outage and the product service, which uses @Cacheable with Redis, returned 500 errors for every request even though the database was healthy. How would you change the service so a cache outage degrades performance instead of availability?Several teams want to share one Redis cluster for caching. Some cache large payloads, one team has a single key read 50,000 times per second, and nobody sets eviction policies consistently. How would you decide between a shared cluster and per-team instances, and what rules would you set?Your company runs hundreds of self-managed Redis instances for caching. Licence changes in the Redis ecosystem (for example the 2024 licence change and the Valkey fork) and rising operating costs have put the setup under review. How would you decide the long-term direction for the cache layer?Cache invalidation
Compare these strategies for keeping a cache consistent with a database: TTL-only expiry, evict on write, update (put) on write, and write-through. When would you choose each?A pricing service runs 20 instances, each with a local Caffeine cache of prices. Prices are updated through an admin API on one instance. Design how the other 19 instances learn about the change, and explain the consistency you can promise.Incident reviews in your organisation keep finding stale-cache bugs: customers see old addresses, old prices and revoked permissions. How would you set a policy for what can be cached and how invalidation must work across teams?A data protection audit finds that personal data deleted from your primary databases still lives in caches, search indexes and replicated read models for weeks. How would you build a programme that makes erasure and retention rules apply to every copy of data, including caches?Cache stampede
What is a cache stampede (thundering herd) and what does the probabilistic early expiration technique do to prevent it?Every day at 09:00 the database CPU of a catalog service jumps to 100 percent for about a minute. The service caches the home page catalog in Redis with a 24 hour TTL written at 09:00 the previous day, and it runs 30 instances. Explain what is happening and give several fixes.A regional Redis failover leaves the cache empty for all 200 services that use it, and the shared databases start failing under the sudden load. As the architect responsible, what immediate actions do you take and what do you change afterwards?Multi-level caching
Design a two-level cache for a read-heavy service: a local Caffeine cache in each instance in front of a shared Redis cache in front of the database. Describe read and write paths, TTLs and how invalidation reaches the local caches.Over several years your platform has added caches at the CDN, API gateway, service, Hibernate second level and database layers. Outages now often involve cache behaviour, and capacity plans assume hit ratios nobody verifies. How would you decide which caches to keep, and how do you change the organisation's approach to caching?Ehcache and JCache
What is JCache (JSR-107), how does Ehcache 3 relate to it, and how do you configure Spring Boot to use Ehcache 3 through JCache? What happened to Ehcache 2?An older Spring application uses Ehcache 2 for its service caches and Hibernate second-level cache, with disk persistence enabled for some caches. You are upgrading to Spring Boot 3. Plan the cache migration and the decisions you need to make.Transaction-aware caching
What does making a Spring cache transaction-aware do? ExplainTransactionAwareCacheDecorator or RedisCacheManager's transactionAware() option, which operations it delays, and what it does not protect against.A method annotated with @Transactional and @CachePut(cacheNames = "accounts", key = "#result.id") saves an account. When a constraint violation causes the transaction to roll back at commit time, the cache still contains the new account data that was never saved, and readers see it for an hour. Explain and fix.Several services keep Redis caches of data owned by other services' databases. Evict-after-commit in each writer is not enough, because some writes come from batch jobs, SQL scripts and other services. Design a cache invalidation approach that stays correct with transactions across these sources.No question matches these choices.