What's the difference between cache invalidation and eviction?
Invalidation is primarily about correctness — the cached value should no longer be considered valid because the underlying data changed or its freshness window expired.
Eviction is primarily about cache resource management — removing an entry to free space or according to a cache policy such as LRU or LFU. An entry can be valid but evicted, or stale but still physically present until it’s removed.
| Invalidation | Eviction | |
|---|---|---|
| Main concern | Correctness | Capacity |
| Why? | Data became stale | Cache needs space |
| Who usually triggers it? | Application/business event | Cache system |
| Does value have to be stale? | Usually yes | No |
| Example | Product price changed | Redis is full |
| Typical mechanism | Delete/update/version | LRU/LFU/TTL policy |
Explain the execution differences between
@Cacheable,@CachePut, and@CacheEvictin Spring Boot.
@Cacheableskips execution on a cache hit.@CachePutalways executes to update the cache.@CacheEvictdeletes cache entries.💡 Best answer
These three dictate how Spring’s AOP proxies interact with the caching layer.
@Cacheableintercepts the call, checks the cache for the key, and on a hit returns the cached value — bypassing the method entirely.🔬 Deeper explanation
@CachePutguarantees the method runs; it’s for refreshing a stale entry after a mutation.@CacheEvictpurges entries (oftenallEntries=true) when the underlying record is deleted, so users never see stale ghost data.➡️ Follow-up What happens if you put
@Cacheableon a private method in a Spring service? (Nothing — proxy-based AOP can't intercept self-invoked private methods.)🏗️ Real-world usage
@CacheableongetUserById(),@CachePutonupdateUser(),@CacheEvictondeleteUser().
What is a Cache Stampede (Thundering Herd), and how do you prevent it? `
Occurs when a hot key expires and thousands of threads hit the DB at once. Prevent with distributed locks (single-flight) or TTL jitter.
Contrast Cache-Aside, Write-Through, and Write-Behind.
Cache-Aside checks cache then DB. Write-Through writes both synchronously. Write-Behind writes cache and syncs to DB asynchronously.