How do you implement caching with Spring, and how do you keep the cache consistent?
The cache abstraction
@EnableCachingplus aCacheManager(Caffeine for local, Redis for distributed).@Cacheable("products"): return the cached value if present, otherwise call the method and store the result. The key defaults to the method parameters; customise it with SpEL (key = "#id") and addcondition/unless.@CachePut: always execute and update the cache.@CacheEvict: remove entries (allEntries = truefor a whole cache), optionallybeforeInvocation.- Same proxy rules apply: self-invocation bypasses caching.
Local vs distributed
- Caffeine (in-process): nanosecond reads, no network; but each instance has its own copy, so instances can disagree and memory is multiplied.
- Redis (shared): one copy for all instances, survives deployments; costs a network hop and serialisation; needs its own HA.
- Two-level (Caffeine in front of Redis) for very hot keys, with pub/sub invalidation.
Consistency strategies
- Cache-aside with TTL is the default: read through the cache, evict or update on write, and let a TTL bound staleness.
- Evict after the database commit (
@TransactionalEventListener), not before, otherwise a concurrent reader can repopulate the cache with the old value. - For critical data, prefer eviction over update (less risk of writing a stale value), and use versioned keys.
- Protect against a stampede on hot keys: Caffeine and
@Cacheable(sync = true)let one caller load while others wait; in Redis use a short lock or early probabilistic refresh. Add jitter to TTLs so keys do not all expire at once.
Example
java
@Cacheable(cacheNames = "product", key = "#id", sync = true)
public ProductView getProduct(long id) { return repo.findView(id).orElseThrow(); }
@Transactional
public void updatePrice(long id, BigDecimal price) {
repo.updatePrice(id, price);
events.publishEvent(new ProductChanged(id)); // evicted after commit by a listener
}Follow-up questions interviewers ask
Try answering each one before you open it.
What should you not cache?
Data that must be strongly consistent (balances, inventory counts at checkout), highly personalised responses with low reuse, very large objects that churn memory, and anything containing secrets unless the cache is secured. Also do not cache null/Optional.empty() for non-existent keys unless you deliberately want negative caching with a short TTL.
How do you choose TTLs and size limits?
From the data's change rate and the business tolerance for staleness (catalogue descriptions: hours; prices: minutes or event-based eviction), and from hit-rate metrics. Bound local caches by size (maximumSize) or weight so they cannot cause OutOfMemoryError, and monitor hit ratio, evictions and load time through Micrometer.