Cache design and invalidation
What you will learn
A cache stores a reusable copy of an expensive result. Cache-aside reads the cache first, loads from the authoritative store on a miss, and stores a bounded-lifetime copy. An eviction is not a deletion of the original data. Decide how stale a value may be before choosing a cache policy.
- Trace hits, misses, expiry and invalidation.
- Design tenant-aware keys and explain stale refill races.
- Compare local bounded caches with a shared cache.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. External cache and broker examples require the companion lab or configured infrastructure. Their predicted results are not execution evidence.
Count origin reads
public class Main {
public static void main(String[] args) {var cache = new java.util.HashMap<String,Integer>(); var reads = new java.util.concurrent.atomic.AtomicInteger(); for(int i=0;i<3;i++) System.out.println(cache.computeIfAbsent("a:B1", k->{reads.incrementAndGet();return 5;})); cache.remove("a:B1"); cache.computeIfAbsent("a:B1", k->{reads.incrementAndGet();return 6;}); System.out.println("reads="+reads.get()); }}Expected output:
555reads=2A sequential map models hits and invalidation, not a production concurrent bounded cache.
Cache-aside and freshness
Text diagram: authorized caller → cache lookup → hit returns copy; miss → database → cache fill → return. After a successful write, invalidate the old cache entry. An in-flight reader may have read the old value before the write and fill it after invalidation; TTL limits the exposure only if every fill has an expiry and assumptions about clocks and delays hold. Use version-aware writes or a coordinated consistency mechanism when required. Cache failures are not evidence that a record is missing.
Capacity, stampedes and scope
Bound entry count or weight, configure expiry, measure hit ratio and origin load. A stampede occurs when many requests miss the same key at once. Coalesce concurrent loads per key, limit origin concurrency and consider jittered expiry. Coalescing in one JVM does not coordinate all replicas. Caffeine is an in-process cache; Spring Cache provides an abstraction and proxy-based annotations. Use trusted tenant identity in cache keys and authorize before a cached response is returned; keys alone do not authorize. Cache immutable DTOs rather than managed entities.
Reject stale cache refill
public class Main { record Value(int version,int stock) {} public static void main(String[] args) {var cache=new java.util.HashMap<String,Value>(); cache.put("a:B1",new Value(2,4)); cache.merge("a:B1",new Value(1,5),(old,incoming)->old.version()>=incoming.version()?old:incoming); System.out.println(cache.get("a:B1")); }}Expected output:
Value[version=2, stock=4]A retained newer version defeats a stale refill in this model. If eviction removes the version fence, a stale refill can still win; durable version tracking may be needed.
Bounded local Caffeine cache
Source-reviewed, NOT RUN. File lab-fixtures/cache-messaging-v44/CaffeineExample.java; use the companion lab README.
import com.github.benmanes.caffeine.cache.Cache;import com.github.benmanes.caffeine.cache.Caffeine;import java.time.Duration;public class CaffeineExample { public static void main(String[] args) { Cache<String, Integer> cache = Caffeine.newBuilder() .maximumSize(100).expireAfterWrite(Duration.ofSeconds(30)).build(); System.out.println(cache.get("tenant-a:B1", k -> 5)); cache.invalidate("tenant-a:B1"); System.out.println(cache.getIfPresent("tenant-a:B1")); }}Predicted behavior: 5 then null after explicit invalidation.
Expiry and eviction behavior require a real library test.
Cache annotations and proxy calls
Source-reviewed, NOT RUN. File lab-fixtures/cache-messaging-v44/CachedCatalog.java; use the companion lab README.
// Fragment: register this bean in a Spring context with @EnableCaching// and a bounded, TTL-configured cache manager. Call through the proxy.import org.springframework.cache.annotation.Cacheable;import org.springframework.cache.annotation.CacheEvict;public class CachedCatalog { @Cacheable(cacheNames="catalog", key="#p0 + ':' + #p1", sync=true) public int stock(String tenant, String sku) { // Fictional read only. Production: authorized tenant-scoped repository. if (!tenant.equals("tenant-a") || !sku.equals("B1")) throw new IllegalArgumentException("unknown item"); return 5; } @CacheEvict(cacheNames="catalog", key="#p0 + ':' + #p1") public void invalidate(String tenant, String sku) { }}Predicted behavior: Repeated proxied reads can reuse an entry; invalidation removes the key.
sync=true is provider-dependent coalescing, not distributed synchronization.
Common mistakes
Do not use only SKU as the key in a multi-tenant API. Do not let @Cacheable bypass access checks, assume TTL implies strong consistency, or replace an authoritative stock update with a cache write.
Practice
Use an immutable Key record (tenant, sku). Cache stock 5 for a/B1 and 9 for b/B1. Remove only a/B1 and print its presence and b/B1 stock.
Expected output:
false9Compare with the manual review criteria.
Official reading: Caffeine · Spring Cache. Cache and broker execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cache design and invalidation — knowledge check
Cache and messaging reasoning.
What is authoritative in cache-aside?
What happens on a cache miss?
Which key prevents accidental tenant collisions?
Why coalesce loads?
Why can invalidation still leave stale data?