Scrivio Interview library
CodingIntermediate7 min read · updated 13 November 2026

A developer wants a two-level cache in Spring: Caffeine in each pod in front of Redis. They configure a CompositeCacheManager with a CaffeineCacheManager and a RedisCacheManager and expect level-one then level-two behaviour.

What does CompositeCacheManager actually do, and how would you implement a real two-level Spring cache?

CompositeCacheManager does not chain caches: getCache(name) returns the cache from the first delegate manager that has one for that name, and a CaffeineCacheManager that creates caches on demand has one for every name, so Redis is never used. A real two-level cache is a TwoLevelCache implementing org.springframework.cache.Cache: get checks Caffeine, then Redis, and fills Caffeine on a Redis hit; put and evict write both levels and publish an invalidation to other pods; get(key, Callable) loads once and writes both levels; and a small CacheManager creates one per name with a local TTL shorter than the Redis TTL.

Why this question is asked

Spring's cache abstraction makes it look as if caches can be combined by configuration, and CompositeCacheManager has a name that suggests layering. Interviewers ask this because many teams have shipped exactly this configuration and believed they had two levels. In this answer, we will see what CompositeCacheManager really does, design the read and write paths of a real two-level cache, implement it as a Spring Cache, keep the sync = true behaviour, wire it with a CacheManager and invalidation, and finish with existing libraries and testing.

1What CompositeCacheManager Actually Does

A CacheManager in Spring answers one question: given a cache name such as products, which Cache object handles it? CompositeCacheManager holds a list of managers and asks them in order, returning the first non-null answer. It exists so that different cache names can live in different technologies, for example sessions in one store and products in another. It never passes a request from one cache to another.

There is a second trap. A CaffeineCacheManager without a fixed list of cache names is dynamic: it creates a Caffeine cache for any name it is asked about. So it answers for every name, the composite never reaches the RedisCacheManager, and the application runs with local caches only. Nothing fails, the hit ratio looks fine in each pod, and the shared level silently does not exist.

Java
@Bean CacheManager cacheManager(RedisConnectionFactory cf) {
CompositeCacheManager m = new CompositeCacheManager(
new CaffeineCacheManager(), // dynamic: answers for every name
RedisCacheManager.create(cf));
return m;
}
cacheManager.getCache("products"); // a CaffeineCache, never a RedisCache

2Designing the Two Levels

A real two-level cache is one Cache that talks to both levels. The read path checks the local level first, because it costs nanoseconds, then Redis, which costs about a millisecond, and only then the database. A Redis hit is copied into the local level so the next read in this pod is local. The write paths, put and evict, go to both levels, and evict must also tell the other pods to drop their local copies, because each pod's Caffeine is invisible to the others.

Step throughget(key, loader) in a two-level cache
  1. In Caffeine?Level one, in this pod
    YesReturn itNoAsk Redis
  2. In Redis?Level two, shared by all pods
    YesStore in Caffeine, returnNoRun the loader once
  3. Write Redis, then CaffeineBoth levels now hold the value
  4. On evict: publish invalidationOther pods drop their local copy

4 steps in order. Play them, or step through them one at a time.

3Implementing TwoLevelCache

The class delegates to two existing Spring caches, a CaffeineCache and a RedisCache, so we reuse their serialization, null handling and statistics rather than writing our own.

Java
public class TwoLevelCache implements Cache {
private final String name;
private final Cache local; // CaffeineCache, TTL 30 s
private final Cache remote; // RedisCache, TTL 10 min
private final Invalidations invalidations; // publishes to other pods
public String getName() { return name; }
public Object getNativeCache() { return this; }
public ValueWrapper get(Object key) {
ValueWrapper v = local.get(key);
if (v != null) return v; // level 1 hit
v = remote.get(key);
if (v != null) local.put(key, v.get()); // level 2 hit: fill level 1
return v; // null: a miss on both levels
}
public <T> T get(Object key, Class<T> type) {
ValueWrapper v = get(key);
return v == null ? null : type.cast(v.get());
}
@SuppressWarnings("unchecked")
public <T> T get(Object key, Callable<T> loader) {
return local.get(key, () -> { // Caffeine runs this once per key in this pod
ValueWrapper v = remote.get(key);
if (v != null) return (T) v.get(); // another pod already loaded it
T value = loader.call(); // the real load, once
remote.put(key, value);
return value; // Caffeine stores it locally
});
}
public void put(Object key, Object value) {
remote.put(key, value); local.put(key, value); invalidations.publish(name, key);
}
public void evict(Object key) {
remote.evict(key); local.evict(key); invalidations.publish(name, key);
}
public void clear() {
remote.clear(); local.clear(); invalidations.publishClear(name);
}
}

Notice the order in put and evict: Redis first, then the local level, then the message. If we published before Redis was updated, another pod could drop its local copy, reload from Redis and get the old value again. Newer Spring versions also add retrieve methods to Cache for asynchronous caching, with defaults that report them as unsupported; implement them only if you use async cached methods (check your Spring version).

4Keeping sync = true Working

@Cacheable(sync = true) asks Spring to call get(key, Callable), so that concurrent misses for one key run the method once. Our implementation keeps that promise inside a pod by passing the whole two-level lookup to CaffeineCache.get(key, Callable), which uses Caffeine's per-key atomic computation. Fifty threads asking for the same key run the lambda once; inside it, Redis is checked before the real loader runs.

Across pods there is no coalescing, so in the worst case each pod loads once. That matches what a plain RedisCache offers, and for most data it is fine; if not, a short distributed lock can be added inside the lambda.

5Wiring the CacheManager and Invalidation

A small CacheManager creates one TwoLevelCache per name on first use, from a CaffeineCacheManager configured with a short TTL and a RedisCacheManager configured with a longer one.

Java
@Bean CacheManager cacheManager(RedisConnectionFactory cf, Invalidations inv) {
CaffeineCacheManager l1 = new CaffeineCacheManager();
l1.setCaffeine(Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(30)).maximumSize(50_000));
RedisCacheManager l2 = RedisCacheManager.builder(cf)
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)))
.build();
Map<String, Cache> caches = new ConcurrentHashMap<>();
return new CacheManager() {
public Cache getCache(String name) {
return caches.computeIfAbsent(name, n -> new TwoLevelCache(n, l1.getCache(n), l2.getCache(n), inv));
}
public Collection<String> getCacheNames() { return Collections.unmodifiableSet(caches.keySet()); }
};
}

Invalidations can be a Redis pub/sub channel: each pod subscribes, and on a message it evicts the key from its local cache only, ignoring messages it sent itself. Pub/sub does not store messages, so a pod that is disconnected for a moment misses some. That is why the local TTL, 30 seconds here, is much shorter than the Redis TTL: it bounds how long a pod can serve a value after a missed invalidation.

6Existing Implementations and Testing

Before maintaining our own, it is worth checking libraries that already provide multi-level caches, such as JetCache, or Redisson's local cached maps, which keep a local copy in sync with a Redis map; check their Spring integration and how they handle invalidation and missed messages. Either way, the tests must run against two application instances sharing one Redis: update a value through instance A and assert that instance B returns the new value within the expected time, evict on A and check B, and disconnect B from pub/sub briefly to confirm the local TTL bounds the staleness.

7Follow-up questions

How would you report hit ratio separately for each level?

Count inside TwoLevelCache: increment Micrometer counters for a level-one hit, a level-two hit and a miss on both, tagged with the cache name. Caffeine's own statistics (recordStats) and RedisCacheManager's statistics give per-level views too, but the counters in the composite show the full picture: level-one hit ratio, level-two hit ratio of level-one misses, and the overall fraction that reached the loader.

Why not let CompositeCacheManager do it with fixed cache names?

Configuring CaffeineCacheManager with a fixed list of names stops it answering for every name, so other names reach Redis. But each name still lives in exactly one level, so we get some caches local and others shared, never both levels for the same cache.

What happens if Redis is down?

Reads fall through to the loader after a Redis error unless we catch it. A production version should treat Redis errors as misses on level two, log them, and keep serving from level one and the loader, so a Redis outage degrades performance instead of failing requests.

8Conclusion

In this answer, we saw that CompositeCacheManager only picks the first manager that has a cache for a name, and a dynamic CaffeineCacheManager has one for every name, so Redis is never used. A real two-level cache implements Spring's Cache: reads check Caffeine, then Redis, filling Caffeine on a Redis hit; writes and evictions go to Redis, then Caffeine, then an invalidation message; get(key, Callable) runs inside Caffeine's per-key computation so sync = true still coalesces; and a custom CacheManager builds one per name with a local TTL shorter than the Redis TTL to bound missed invalidations.

What to say in the interviewAbout 80 seconds aloud

Open with

CompositeCacheManager does not layer caches. For a cache name it asks its managers in order and returns the first cache it gets, and a CaffeineCacheManager without fixed names creates a cache for any name, so every lookup goes to Caffeine and Redis is never touched.

Then, if they want more

To get real two levels I would write a TwoLevelCache that implements Spring's Cache and delegates to a CaffeineCache and a RedisCache. get checks Caffeine, then Redis, and on a Redis hit puts the value into Caffeine. put and evict write Redis first, then Caffeine, then publish an invalidation, for example on Redis pub/sub, so other pods drop their local copy. get with a Callable, which is what sync = true uses, passes the whole lookup into CaffeineCache's get with a loader, so concurrent misses in one pod run once: it checks Redis, and only if Redis misses it calls the real loader and writes Redis.

Then a small CacheManager creates one TwoLevelCache per name, with a local TTL like 30 seconds and a Redis TTL like 10 minutes, so a missed pub/sub message only causes 30 seconds of staleness. Before building it I would check libraries such as JetCache or Redisson's local cached maps, and I would test with two running instances sharing Redis.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "What does CompositeCacheManager actually do, and how would you implement a real...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/ece9ef3b13/