Scrivio Interview library
CodingFoundations7 min read · updated 13 November 2026

A Spring Boot service running 40 pods caches a costly report summary per customer in Caffeine. When an entry is missing, dozens of concurrent requests for the same customer arrive within milliseconds.

Show how Caffeine coalesces concurrent loads of one key inside a JVM, and explain what still happens across the 40 pods and how you would deal with it.

In Caffeine, cache.get(key, k -> loadSummary(k)) on a Cache, or get(key) on a LoadingCache, runs the loading function at most once per key at a time, and the other threads asking for that key wait and receive the same value; AsyncLoadingCache does the same by sharing one CompletableFuture per key. Across 40 pods each pod still loads once, so up to 40 loads can hit the backend together, which is usually fine; for very expensive values we add a shared cache with a short distributed lock or a single-flight service, and refreshAfterWrite keeps popular entries from ever missing.

Why this question is asked

A cache stampede is what happens when a missing value is requested by many callers at the same moment and every one of them goes to the backend to compute it. For a costly report summary, dozens of identical computations at once can overload the database that the cache was meant to protect. Interviewers ask this to check that we know Caffeine's built-in protection, use it correctly, and understand where it stops. In this answer, we will reproduce the stampede, fix it inside the JVM, look at the asynchronous version, see the rules for loading functions, and then deal with 40 pods and with misses on popular keys.

1Reproducing the Stampede

The usual first version of caching code checks the cache, loads on a miss and puts the result back. It looks correct, and it is correct for one thread.

Java
Cache<Long, Summary> cache = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(10)).maximumSize(10_000).build();
AtomicInteger loads = new AtomicInteger();
Summary naive(long customerId) {
Summary s = cache.getIfPresent(customerId);
if (s == null) { // 50 threads all see null
s = loadSummary(customerId); // each one runs the 2-second query
loads.incrementAndGet();
cache.put(customerId, s);
}
return s;
}
// 50 concurrent requests for customer 7 -> loads.get() == 50

The check and the load are two separate steps. Between them, every thread that arrives sees the same empty cache and starts its own load. With a two-second report query and dozens of requests arriving within milliseconds, the database receives dozens of identical heavy queries.

2Letting Caffeine Coalesce the Loads

Caffeine solves this when we hand it the loading function instead of loading ourselves. Cache.get(key, mappingFunction) computes the value atomically per key: the first caller runs the function, and every other caller for the same key waits for that result instead of starting its own.

Java
Summary coalesced(long customerId) {
return cache.get(customerId, id -> { // runs at most once per key at a time
loads.incrementAndGet();
return loadSummary(id);
});
}
// 50 concurrent requests for customer 7 -> loads.get() == 1, all 50 get the same Summary
LoadingCache<Long, Summary> summaries = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(10)).maximumSize(10_000)
.build(id -> loadSummary(id));
summaries.get(7L); // same guarantee, loader fixed at build time

The LoadingCache form is the same idea with the loader given once at build time, which keeps every call site consistent. Requests for different customers still load in parallel; only requests for the same key share a load. In Spring, @Cacheable(sync = true) asks the cache provider for this same behaviour.

3The Asynchronous Version

The synchronous form makes waiting threads block until the load finishes. In a service handling many requests, blocked threads are a cost, and with virtual threads or a reactive stack we may prefer not to block at all. AsyncLoadingCache stores a CompletableFuture per key. The first caller starts the load, and every other caller receives the same in-flight future.

Java
AsyncLoadingCache<Long, Summary> async = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(10)).maximumSize(10_000)
.buildAsync((id, executor) -> CompletableFuture.supplyAsync(() -> loadSummary(id), executor));
CompletableFuture<Summary> f1 = async.get(7L); // starts the load
CompletableFuture<Summary> f2 = async.get(7L); // f1 == f2: the same in-flight future
f1.thenAccept(s -> render(s)); // no thread waits while the query runs

So callers share the work without holding threads. If the future fails, Caffeine removes it, so the next caller tries again instead of receiving a cached failure.

4Rules for the Loading Function

In the synchronous cache the loading function runs inside Caffeine's per-key computation, which is built on ConcurrentHashMap.compute. Two rules follow. Keep it short and focused: a very slow computation holds a lock that, in ConcurrentHashMap, can also delay writes to other keys that happen to share the same internal bin. For loads that take seconds, the asynchronous cache avoids that, because the computation only stores the future and the slow work runs outside the lock.

And never modify the same cache from inside the loading function, for example by putting a related key or calling get for another key that recurses. ConcurrentHashMap does not allow recursive updates during a compute, so this can fail with an IllegalStateException or, in some cases, deadlock. If one load naturally produces several entries, return the main value and put the others after the call returns, or use getAll with a bulk loader.

5What Still Happens Across 40 Pods

Caffeine lives inside one JVM, so its guarantee is per pod. When customer 7's summary is missing everywhere and requests are spread over 40 pods, each pod coalesces its own callers into one load, and up to 40 loads still reach the database at the same moment. That is far better than thousands, and for most data it is acceptable.

For a value that is truly expensive, say a report taking 20 seconds of database time, 40 copies is a real cost. Then we add a shared level: pods first check a Redis cache, and on a Redis miss one pod takes a short lock, SET lock:summary:7 <token> NX PX 5000, builds the value and stores it in Redis, while the others wait briefly and read the result. Another option is a single-flight service, a small internal service that owns the report computation and coalesces requests from all pods, so the guarantee becomes once per cluster rather than once per pod.

Step throughWhere loads are coalesced
  1. RequestsDozens per customer within milliseconds, spread over 40 pods
  2. Caffeine in each podOne load per key per pod: at most 40 in total
  3. Redis with a short lockOptional: one load per key for the whole cluster
  4. DatabaseRuns the costly report query

4 layers, from the top down. Step through them one at a time.

Each layer reduces the number of identical loads that reach the next one.

6Avoiding the Miss With refreshAfterWrite

Coalescing reduces the cost of a miss; refreshing avoids the miss for popular keys. With refreshAfterWrite, an entry older than the refresh interval is reloaded in the background the next time someone reads it, and the reader receives the current value immediately.

Java
LoadingCache<Long, Summary> summaries = Caffeine.newBuilder()
.refreshAfterWrite(Duration.ofMinutes(4)) // a read after 4 minutes triggers a background reload
.expireAfterWrite(Duration.ofMinutes(10)) // an entry nobody reads still goes away
.maximumSize(10_000)
.build(id -> loadSummary(id));

Popular customers are read often, so their entries are refreshed before they expire and their callers never wait. Unpopular ones simply expire. Note that refresh happens on access, not on a timer, so an entry nobody reads is not reloaded, which is exactly what we want.

7Follow-up questions

What happens to waiting callers if the load throws an exception?

Nothing is cached. In the synchronous cache, the caller that ran the loader receives the exception, and threads waiting on the same key then run the computation themselves, so they retry rather than all receiving a cached error. In the asynchronous cache, every caller sharing the future sees it complete exceptionally, and the failed future is removed so the next request starts a fresh load. During a refresh, a failure is logged and the old value is kept.

Does @Cacheable use this behaviour automatically?

Only with sync = true. Without it, Spring checks the cache, calls the method on a miss and then puts the result, which is the naive pattern and allows a stampede. With sync = true and a Caffeine cache manager, Spring calls the cache's get with a loader, so Caffeine coalesces the loads.

Why not lock across pods for every key?

Because a distributed lock costs a network round trip on each miss and adds a failure mode: a dead lock holder makes others wait. For cheap or moderately expensive values, 40 parallel loads are cheaper than the coordination.

8Conclusion

In this answer, we saw that the get-then-put pattern lets every concurrent caller load the same key, while Caffeine's cache.get(key, loader) and LoadingCache run the loader once per key at a time and share the result, and AsyncLoadingCache shares one future without blocking threads. The loader must be short and must not modify the same cache. Across 40 pods each pod loads once, so a shared Redis level with a short lock or a single-flight service is added only for very expensive values, and refreshAfterWrite keeps popular entries from missing at all.

What to say in the interviewAbout 80 seconds aloud

Open with

If the code does getIfPresent and then loads and puts on a miss, every thread that arrives during the load sees the miss and runs its own load, so dozens of identical report queries hit the database.

Then, if they want more

Caffeine fixes this inside the JVM: cache.get with a loading function, or get on a LoadingCache, computes atomically per key. The first caller runs the loader, the others for that key wait and get the same value, and different keys still load in parallel. In Spring that is @Cacheable with sync true.

AsyncLoadingCache does the same with one CompletableFuture per key, so callers share the in-flight load without blocking threads, and a failed future is removed so the next call retries. The loader should be short, because the synchronous cache runs it inside a ConcurrentHashMap compute, and it must never write to the same cache.

Across 40 pods, though, each pod loads once, so up to 40 loads reach the backend. That is usually fine. For very expensive values I would add Redis as a shared level with a short SET NX PX lock, or a single-flight service, so it is one load per cluster.

And refreshAfterWrite reloads popular entries in the background while serving the old value, so they rarely miss at all.

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 "Show how Caffeine coalesces concurrent loads of one key inside a JVM, and explain what...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/50f3b5294a/