Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

Multiple services call an expensive pricing API and each instance memoizes results per product id. During cache expiry, hundreds of concurrent requests for the same product hit the API at once. Design a standard approach for request coalescing and memoization that teams can reuse.

The standard I would set is a shared loading cache that coalesces requests in-process: a map from product id to the in-flight CompletableFuture, so only one pricing call per key per instance runs and every other caller waits on that future. Failed futures are removed promptly and every load has a timeout, so a stuck call cannot hold all waiters. To stop synchronized expiry we refresh ahead of expiry, serve the stale value while revalidating, and add jitter to TTLs; across instances we accept one call per instance unless the API cost justifies a shared cache with a lock or lease. It ships as a small library on top of Caffeine's AsyncLoadingCache, with metrics for loads, hits and failures.

Why this question is asked

Expensive downstream APIs, pricing engines, tax calculators, recommendation services, are usually protected by a per-instance cache. The cache hides most traffic, and then at the moment a popular entry expires, hundreds of requests that were being served from memory all miss at once and stampede the downstream. This is called a cache stampede, or the thundering herd. Interviewers ask senior engineers to design a reusable answer because the individual tricks are well known, but combining them into something every team can use safely is real platform work. In this answer, we will recap why stampedes happen, coalesce requests in one instance, handle failures and timeouts, spread out expiry, decide what to do across instances, and package it all for reuse.

1A Quick Recap of the Stampede

Suppose product 123 is requested 500 times per second on each of 20 instances, and its price is cached for 60 seconds. For 60 seconds every request is a hit. At the moment the entry expires, each instance sees maybe 50 requests arrive before the first pricing call returns 100 milliseconds later. A naive cache lets all 50 miss and call the API, so the API receives about 1,000 calls for one product in a fraction of a second. If many popular products were loaded at the same time, at start-up for example, they also expire at the same time, and the burst multiplies.

Three separate problems hide in that story: duplicate calls inside one instance, many keys expiring together, and duplicate calls across instances. A good standard addresses each one deliberately.

2Coalescing Requests Inside One Instance

Request coalescing means that concurrent requests for the same key share one in-flight load. The building block is a ConcurrentHashMap from key to CompletableFuture. computeIfAbsent installs a future in microseconds, the first caller's future starts the API call, and everyone who arrives before it completes gets the same future.

Java
final class Coalescer<K, V> {
private final ConcurrentHashMap<K, CompletableFuture<V>> inFlight = new ConcurrentHashMap<>();
private final Function<K, V> loader;
private final Executor io;
private final Duration timeout;
CompletableFuture<V> get(K key) {
CompletableFuture<V> f = inFlight.computeIfAbsent(key, k ->
CompletableFuture.supplyAsync(() -> loader.apply(k), io)
.orTimeout(timeout.toMillis(), TimeUnit.MILLISECONDS));
f.whenComplete((v, err) -> inFlight.remove(key, f)); // in-flight only; the value goes to the cache
return f;
}
}
// 50 concurrent get(123) calls -> 1 pricing call, 50 callers complete together
Step throughFifty requests, one call
Request 1Request 2..50CoalescerPricing API
get(123)
price(123)
get(123) x49
same future
price after 100 ms
complete
complete

7 messages in order. Play them, or step through them one at a time.

Notice that the mapping function never calls the API itself. It only creates the future, so the map's bin lock is held for microseconds, never for the duration of the network call. Notice also that the future is removed when it completes in either way: this map tracks only work in progress, and finished values live in the cache with their own TTL.

3Failures and Timeouts

Coalescing has a dark side: if the one shared call hangs, every waiter hangs with it, and if its failure were cached, every caller would see the error until the entry expired. So the standard says two things. Every load has a timeout shorter than the callers' own deadline, for example 800 milliseconds for an API whose p99 is 150 milliseconds, so a stuck call fails all its waiters quickly. And a failed future is removed immediately, using remove(key, future) so that we never delete a newer future someone else installed.

Waiters can also apply their own shorter timeout with future.get(300, TimeUnit.MILLISECONDS) or completeOnTimeout with a fallback, so one slow load does not decide every caller's fate. If a stale value exists, falling back to it is usually better than an error, which leads to the next part.

4Spreading Expiry: Refresh-Ahead, Stale-While-Revalidate and Jitter

Coalescing reduces a stampede to one call per key per instance, but users still wait for that call at every expiry. Refresh-ahead fixes that: once an entry is older than, say, 45 of its 60 seconds, the next read triggers a background reload while still returning the current value. Stale-while-revalidate is the same idea seen from the reader: an expired value can be served for a short grace period while one refresh runs. Hot keys then never expire in front of users.

Jitter fixes the many-keys-at-once problem. If every entry gets exactly 60 seconds, entries loaded together expire together. Giving each entry a TTL of 60 seconds plus or minus a random 10 percent spreads the reloads over a 12-second window instead of a single instant.

Java
AsyncLoadingCache<String, Price> prices = Caffeine.newBuilder()
.maximumSize(200_000)
.refreshAfterWrite(Duration.ofSeconds(45)) // reload in background, keep serving old value
.expireAfter(Expiry.creating((String id, Price p) ->
Duration.ofSeconds(54 + ThreadLocalRandom.current().nextInt(13)))) // 54 to 66 s, jittered
.executor(pricingExecutor)
.recordStats()
.buildAsync(id -> pricingClient.price(id));
prices.get("123"); // hit, or one coalesced load; failed loads are dropped automatically

Caffeine already coalesces loads per key, drops failed futures and supports refresh, so in practice the Coalescer above is what we explain and Caffeine is what we ship. Check the Expiry helper methods available in your Caffeine version; a full Expiry implementation works in all versions.

5Across Instances: Accept It or Coordinate

With per-instance caches, the best we can do alone is one call per key per instance: 20 calls per refresh for 20 instances. For most APIs that is perfectly acceptable, and it keeps every instance independent. The standard should say so explicitly, so teams do not build distributed locking they do not need.

When the API is expensive enough, for example billed per call or limited to 50 calls per second, we add a shared cache such as Redis in front of it. Instances first read the shared value; on a miss, one of them takes a short lease, a lock with an expiry such as SET key NX PX 2000, loads the price and writes it, while the others wait briefly or serve stale data. The lease must expire on its own, so a crashed instance cannot block the key forever. This costs a network hop and a new dependency, so it is an option the standard documents, not a default.

Finally, the library exports metrics per cache: hit rate, load count, load failures, load latency and the number of coalesced waiters. Without them, nobody can tell whether the cache is protecting the API or whether refresh settings are wrong.

Step throughChoosing the cross-instance policy
  1. Per-instance AsyncLoadingCachecoalescing, refresh, jitter, timeouts
  2. Is one call per key per instance acceptable?
    YesStop here: simplest designNoAdd a shared cache
  3. Shared cache with a leaseSET NX with expiry; others wait or serve stale
  4. Same metrics everywherehits, loads, failures, waiters

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

6Follow-up questions

Why not just make the TTL longer?

A longer TTL reduces how often the stampede happens but not how big it is, and it serves older prices. Refresh-ahead gives the freshness of a short TTL with the stability of a long one, because hot keys are reloaded in the background before users ever see a miss.

How do you stop one team's slow loads from starving another team's cache?

Give each cache its own bounded executor, or at least a per-cache concurrency limit for loads, and a timeout on every load. Then a slow downstream can exhaust only its own loading capacity, and the metrics show which cache is stuck.

7Conclusion

In this answer, we designed a reusable approach to request coalescing and memoization. Inside one instance, a map from key to in-flight CompletableFuture lets only one pricing call per key run, with timeouts and prompt removal of failed futures so stuck or failed calls do not trap waiters. Refresh-ahead, stale-while-revalidate and jittered TTLs stop keys from expiring together in front of users. Across instances we accept one call per instance by default and add a shared cache with a lease only when the API cost demands it. We package it as a thin library over Caffeine's AsyncLoadingCache with metrics for loads, hits and failures.

What to say in the interviewAbout 100 seconds aloud

Open with

I would treat this as three problems. First, duplicate calls inside one instance. The fix is request coalescing: a map from product id to the in-flight CompletableFuture, so the first miss starts the call and everyone else waits on the same future. computeIfAbsent only installs the future, so no lock is held during the network call.

Then, if they want more

Second, failure handling: every load gets a timeout well under the callers' deadline, and a failed future is removed right away with remove of key and future, so errors are not cached and a stuck call does not hang every waiter. Third, synchronized expiry.

I would use refresh-ahead, so a hot entry is reloaded in the background at around three quarters of its TTL while the old value is still served, which is stale-while-revalidate, and add jitter of about ten percent to TTLs so entries loaded together do not expire together.

Across instances, the default is to accept one call per key per instance, which is usually fine. Only if the API is very expensive or rate limited would I add a shared cache like Redis with a short lease, so one instance loads and the others wait or serve stale data.

To make it reusable, I would not have each team build this. I would ship a small library on top of Caffeine's AsyncLoadingCache, which already coalesces, drops failed loads and supports refresh, with our defaults for timeouts, jitter and executors, and standard metrics for hits, loads, failures and load latency.

About this answer

Last updated
12 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 documentation below. 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 "Multiple services call an expensive pricing API and each instance memoizes results per...": https://scrivio-interview-library.netlify.app/java/concurrent-collections/93c5906986/