Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

A reactive service caches the result of a configuration call with a Mono stored in a field and cache(). Months later, stale configuration causes an incident. What went wrong, and what pattern would you standardise?

cache() without a duration subscribes to the source once and then replays that first result, including a first error or an empty result, to every subscriber for as long as the Mono exists. Stored in a field of a singleton bean, that means for the life of the process, so configuration changes were never seen. The standard pattern is to give every cached Mono explicit time-to-live values for values, errors and empty results, or better to use a real cache such as Caffeine with async loading, refresh and metrics, to document what may be cached for how long, and to test expiry with virtual time.

Why this question is asked

Caching mistakes are slow-burning incidents. The service works on day one, passes every test, and fails months later when someone changes a value and the running instances never notice, or when a brief outage at startup is cached as a permanent error. Interviewers ask this because it combines a Reactor detail with a team-level lesson: a convenience operator was used as a cache without anyone deciding the cache's rules. In this answer, we will recap what cache() does, reconstruct the incident, fix it with cache(Duration) and per-signal TTLs, move to a proper cache abstraction, and then write down the standard and the tests that enforce it.

1A Quick Recap of What cache() Does

A Mono is normally cold: each subscription runs the source again. cache() changes that. On the first subscription it subscribes to the source, records the signal that comes back (a value, an empty completion or an error), and from then on hands that same recorded signal to every subscriber without touching the source again.

Nothing in plain cache() ever forgets the recorded signal. It is a memo, not a cache in the usual sense, because a cache normally has a size limit, an expiry and a way to refresh. That is fine inside one request, where the Mono itself is thrown away when the request ends. It is a problem when the Mono lives in a field.

2Reconstructing the Incident

The service had a bean like this, written to avoid calling the configuration service on every request.

Java
@Service
class FeeService {
private final Mono<FeeConfig> config = configClient.fetch("fees").cache();
Mono<Fee> feeFor(Order o) { return config.map(c -> c.compute(o)); }
}
// day 1, 09:00 first request: GET /config/fees -> rate 2.5 percent
// day 1 to 120 every request: rate 2.5 percent, no further calls
// day 121 config changed to 1.9 percent: instances keep charging 2.5
Step throughWhat a field-level cache() does over time
  1. Bean created, Mono assemblednothing fetched yet
  2. First subscriber arrivessource subscribed once
  3. What came back?
    YesValue, empty or error is recordedNo(always one of the three)
  4. Every later subscribergets the recorded signal, source never called again
  5. Configuration changes upstreamthe recorded value is never replaced

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

The field is created once when the bean is created, and the bean lives as long as the application. So the first configuration ever fetched stayed in use for four months. Instances started after the change got the new value, which made the problem harder to see: depending on which instance served a request, customers were charged different fees.

The same code has two quieter failure modes. If the configuration service was down for the first request, cache() recorded the error, and that instance failed every fee calculation until it was restarted. And if the configuration service returned an empty result, the instance cached the emptiness forever.

3Fix 1: Give Every Signal Its Own Time-to-Live

Mono has variants of cache() that expire. cache(Duration ttl) re-subscribes to the source once the recorded signal is older than the ttl. The more precise variant takes three functions, one for values, one for errors and one for empty results, so each can have its own lifetime.

Java
private final Mono<FeeConfig> config = configClient.fetch("fees")
.cache(value -> Duration.ofMinutes(5), // reuse a good value for 5 minutes
error -> Duration.ofSeconds(5), // retry a failure soon, but not on every request
() -> Duration.ZERO); // never cache an empty result
// request at 09:00 -> fetch; 09:04 -> cached; 09:05:01 -> fetch again

Notice the separate decisions. Caching errors for a few seconds protects the configuration service from a stampede while it recovers, without making the error permanent. Caching empty for zero time means a missing entry is retried at once. When the cached value expires, the next subscriber triggers the fetch and waits for it, so latency spikes briefly every five minutes, which is acceptable for configuration but not for a hot path.

4Fix 2: Use a Real Cache Abstraction

For data that many services read, a proper cache is the better standard. Caffeine's AsyncLoadingCache holds CompletableFuture values, so it fits reactive code, and it gives us what cache() cannot: refreshAfterWrite, which reloads a value in the background while still serving the old one, expireAfterWrite as a hard limit, a maximum size, and statistics we can publish as metrics.

Java
AsyncLoadingCache<String, FeeConfig> configs = Caffeine.newBuilder()
.maximumSize(1_000)
.refreshAfterWrite(Duration.ofMinutes(5)) // background reload, callers keep the old value
.expireAfterWrite(Duration.ofMinutes(30)) // never serve anything older than this
.recordStats()
.buildAsync((key, executor) -> configClient.fetch(key).toFuture());
Mono<FeeConfig> config(String key) { return Mono.fromFuture(() -> configs.get(key)); }
// stats: hitRate 0.998, loadFailureCount 0, evictionCount 12

With Micrometer bound to the cache, the hit rate, load failures and load times appear on dashboards. A failed refresh keeps serving the previous value until the hard expiry, which is usually the behaviour we want for configuration. If changes must take effect within seconds, a push mechanism, such as a refresh event on a topic that invalidates the entry, sits on top of this.

5Writing Down the Standard

The technical fix is half the answer. The incident happened because nobody decided how long fee configuration could be stale. The standard we would write says that a Mono stored in a field must not use plain cache(); long-lived caching goes through the shared cache abstraction; and every cached piece of data has an entry in a short table with its owner, its maximum acceptable staleness, how errors and empty results are treated, and how a change is propagated. For fees the business might say five minutes; for feature flags, thirty seconds; for a currency list, a day.

A simple static check helps: a rule in code review, or an ArchUnit or lint rule, that flags .cache() with no arguments on a field initializer.

6Testing Expiry With Virtual Time

Expiry bugs are invisible in tests that run for a few milliseconds, so we test them with virtual time, a scheduler whose clock we move by hand.

Java
@Test
void configIsRefetchedAfterTtl() {
AtomicInteger calls = new AtomicInteger();
VirtualTimeScheduler clock = VirtualTimeScheduler.create();
Mono<String> config = Mono.fromCallable(() -> "v" + calls.incrementAndGet())
.cache(Duration.ofMinutes(5), clock);
assertEquals("v1", config.block()); // first fetch
clock.advanceTimeBy(Duration.ofMinutes(4));
assertEquals("v1", config.block()); // still cached
clock.advanceTimeBy(Duration.ofMinutes(2));
assertEquals("v2", config.block()); // expired, fetched again
assertEquals(2, calls.get());
}

block() is fine here because this is a test, not an event-loop thread. For Caffeine, the equivalent is a Ticker we control, passed with Caffeine.newBuilder().ticker(fakeTicker), so the test advances the cache's clock instead of sleeping.

7Follow-up questions

Why did instances disagree about the fee?

Each instance cached whatever value it fetched first. Instances started before the change kept 2.5 percent, instances started after it fetched 1.9 percent, and the load balancer spread requests across both. Inconsistent results between instances are a strong hint that some local state, such as a cache without expiry, is involved.

Is it ever right to cache errors?

Briefly, yes. Caching an error for a few seconds stops every request from hammering a struggling dependency, which helps it recover. Caching an error forever is never right, because it turns a temporary outage into a permanent failure until restart.

What about @Cacheable in a reactive service?

Recent Spring Framework versions (6.1 and later) support @Cacheable on methods returning Mono and Flux with a cache provider that supports async operations, such as Caffeine in async mode; check your version and provider. It gives the same benefits as using Caffeine directly with less code, as long as the TTL and size are configured.

8Conclusion

In this answer, we saw that cache() on a Mono stored in a field records the first value, error or empty result and replays it for the life of the bean, which is how a configuration change went unnoticed for months. We fixed it with cache variants that give values, errors and empty results their own time-to-live, and preferred a real cache such as Caffeine with refresh, expiry, size limits and metrics. We then wrote a standard that records how stale each piece of data may be, banned plain cache() on fields, and tested expiry with virtual time.

What to say in the interviewAbout 100 seconds aloud

Open with

The root cause is that cache() without a duration isn't really a cache, it's a memo. On the first subscription it subscribes once and records the result, and then replays that recorded signal to every subscriber forever.

Then, if they want more

Inside a single request that's fine, but here the Mono was a field on a singleton bean, so forever meant the life of the process. The config changed months later and the running instances never fetched it again, while newly started instances did, so we even had instances disagreeing.

And it records errors and empty results too, so an outage at startup would have been cached as a permanent failure. The immediate fix is to use the cache variant with separate TTLs: for example five minutes for a value, a few seconds for an error so we don't stampede the config service but recover quickly, and zero for empty.

But the pattern I'd standardise is a real cache abstraction, Caffeine's AsyncLoadingCache, wrapped with Mono.fromFuture, with refreshAfterWrite so we reload in the background and keep serving the old value, a hard expireAfterWrite, a size limit and stats exported to Micrometer.

Then the standard says no plain cache() on fields, and each cached item has a documented owner and maximum staleness agreed with the business, five minutes for fees, thirty seconds for flags. Finally I'd require tests that prove expiry using virtual time, a VirtualTimeScheduler for Reactor or a fake Ticker for Caffeine, so expiry behaviour is tested without sleeping.

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 "A reactive service caches the result of a configuration call with a Mono stored in a...": https://scrivio-interview-library.netlify.app/spring-boot/reactive-fundamentals/283d15d4eb/