Scrivio Interview library
CodingFoundations6 min read · updated 13 November 2026

A Spring Boot service looks up currency exchange rates from a slow internal service. One developer writes cache-aside code by hand; another proposes a read-through cache, where the cache itself knows how to load a missing value.

Implement the lookup as a read-through cache with Caffeine's LoadingCache, and explain what changes compared with hand-written cache-aside code.

Try it yourself

Cache-aside: one read, three cache states

See what a cache hit saves, what a miss costs, and why a write deletes the cached entry instead of updating it.

Read this example as text

When the entry is in the cache (a hit)

  1. A request arrives. A caller asks the service for product 42. The cache already holds it.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Hit: the value comes back. The entry is there and still fresh, so the cache answers at once. The database is never touched.

1 cache call, 0 database reads.

When it was never cached (a miss)

  1. A request arrives. A caller asks the service for product 42. Nobody has asked for it before, so the cache holds nothing.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. The key was never stored. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When its time to live has run out

  1. A request arrives. A caller asks the service for product 42. The cache held it once, but its time to live ran out 12 seconds ago.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. An expired key is the same as a missing one: Redis no longer returns it, and removes it. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When the price changes afterwards

  1. The price changes. Later, someone updates the price to 25. The service writes the database first: UPDATE products SET price = 25 WHERE id = 42.
  2. Delete the cached entry. Then it deletes the key: DEL product:42. It does not write 25 into the cache. Deleting is simpler and safer: the next read misses and loads whatever the database holds then.
  3. The next read will miss. The cache is empty for this key again, so the next request repeats the miss path and stores 25.

3 cache calls, 1 database read, 1 database write.

What this example leaves out
  • One request at a time. Two requests missing at the same moment (a stampede) are not shown.
  • The write deletes the key. Some systems update the cache instead, which this example does not model.
  • The numbers are counts of round trips, not measured times.

A read-through cache is built once with its loader, for example Caffeine.newBuilder().maximumSize(10_000).expireAfterWrite(Duration.ofMinutes(5)).build(code -> rateClient.fetch(code)), and callers just call rates.get("EUR"). Compared with hand-written cache-aside, the check-load-put logic lives in one place, and Caffeine runs the loader only once per key while other callers for that key wait for the same result. A loader exception reaches the callers and nothing is cached, so we decide whether to cache failures or keep serving an older value with refreshAfterWrite, and Spring's @Cacheable(sync = true) gives similar once-per-key loading for annotated methods.

Why this question is asked

Exchange rates are a perfect cache candidate: they change every few minutes, are read constantly, and come from a slow service. Both developers' approaches work on a quiet day. The difference shows when a popular key expires under load, or when the rate service fails. Interviewers ask this to see whether we know what a read-through cache gives us beyond saving a few lines of code. In this answer, we will recap the two patterns, write the hand-written version and its problem, build the LoadingCache, look at how it coalesces loads, handle loader failures, and compare it with Spring's @Cacheable.

1A Quick Recap of Cache-Aside and Read-Through

In cache-aside, the application manages the cache itself: it looks in the cache, and on a miss it loads the value from the source and puts it into the cache. The cache is a passive map.

In read-through, the cache knows how to load a missing value. We give it a loader function when we create it, and callers only ever ask the cache. On a miss, the cache calls the loader, stores the result and returns it. The caller never talks to the source directly.

2The Hand-Written Cache-Aside Version and Its Problem

Here is the first developer's code. It is correct, but notice what happens when 50 threads ask for EUR at the moment its entry has expired.

Java
Cache<String, Rate> cache = Caffeine.newBuilder()
.expireAfterWrite(Duration.ofMinutes(5)).maximumSize(10_000).build();
Rate rateFor(String code) {
Rate r = cache.getIfPresent(code); // null for all 50 threads at the same moment
if (r == null) {
r = rateClient.fetch(code); // 50 calls to the slow rate service
cache.put(code, r);
}
return r;
}

Each thread sees a miss and calls the rate service, so one expiry turns into 50 remote calls, a small thundering herd, also called a cache stampede. The logic is also repeated in every place that needs a rate, and every copy must remember timeouts and fallbacks the same way.

3Building the Read-Through LoadingCache

With Caffeine, we pass the loader to build(). The result is a LoadingCache, and get() either returns the cached value or loads it.

Java
LoadingCache<String, Rate> rates = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofMinutes(5))
.recordStats()
.build(code -> rateClient.fetch(code)); // the loader, called only on a miss
Rate eur = rates.get("EUR"); // first call: loads from the rate service (~300 ms)
Rate again = rates.get("EUR"); // within 5 minutes: from memory, microseconds
rates.stats().hitRate(); // 0.5 after these two calls

Callers now call rates.get(code) and nothing else. Loading policy, such as the client timeout, a circuit breaker or a fallback, lives in the loader, so it is written once.

4How the Loader Runs Once per Key

The bigger change is concurrency. When several threads call get("EUR") on a missing key, Caffeine runs the loader for EUR once, and the other threads for that key wait for that one result instead of calling the service themselves. Threads asking for other keys are not blocked. So 50 concurrent requests on an expired EUR produce one remote call.

Step through50 concurrent get("EUR") on a missing key
Threads 1-50LoadingCacheRate service
get("EUR") x 50
fetch("EUR"), once
threads 2-50 wait on the same load
Rate EUR
same Rate to all 50

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

Compare with the cache-aside version, where all 50 called the service.

Notice that the waiting threads are blocked for the duration of the load. With a 300 ms service, a cold key costs 300 ms for all of them, which is why refreshing before expiry, covered next, is worth adding.

5When the Loader Fails

If the loader throws, get() throws to every caller waiting on that load, and nothing is cached, so the next call tries again. Unchecked exceptions arrive as they are; checked exceptions are wrapped in a CompletionException. Two decisions follow. Should we cache a failure, for example a "currency not supported" answer, for a short time so a bad code does not hit the service on every request? And should we keep serving an older value when the service is down?

For the second, refreshAfterWrite helps. After the refresh interval, the next read still returns the current value immediately and triggers a reload in the background. If the reload fails, Caffeine logs it and keeps the old value, so callers keep getting the last known rate until expireAfterWrite finally removes it.

Java
LoadingCache<String, Rate> rates = Caffeine.newBuilder()
.maximumSize(10_000)
.refreshAfterWrite(Duration.ofMinutes(1)) // reload in the background after 1 minute
.expireAfterWrite(Duration.ofMinutes(30)) // give up on a value older than 30 minutes
.build(code -> rateClient.fetch(code));
// rate service down for 10 minutes: callers keep the last rate, no errors
// down for more than 30 minutes: entries expire, get() throws again
Cache-aside by hand vs LoadingCache
ConcernHand-written cache-asideCaffeine LoadingCache
Where loading logic livesevery callerone loader
Concurrent misses on one keyeach calls the serviceone call, others wait
Loader failureeach caller handles itthrown to waiters, nothing cached
Serving stale on failurecustom coderefreshAfterWrite keeps old value

6How Spring's @Cacheable Compares

Spring's @Cacheable is cache-aside performed by a proxy: before the method runs, the proxy looks in the cache, and on a miss it runs the method and puts the result. By default, concurrent misses each run the method. @Cacheable(sync = true) asks the cache provider to load once per key, and with Caffeine as the provider that gives similar coalescing for annotated methods. The trade-off is that sync = true supports only a single cache per annotation and no unless condition, so check those limits for your case.

Java
@Cacheable(cacheNames = "rates", sync = true)
public Rate rateFor(String code) {
return rateClient.fetch(code); // runs once per key, even with 50 concurrent misses
}

7Follow-up questions

What would you do if the rate service is down at startup?

Make the service start anyway and degrade per request, rather than fail. The LoadingCache is lazy, so startup does not depend on the rate service unless we preload. If rates must be available immediately, I would keep a last-known copy, for example in Redis or a file written on every successful load, and use it to warm the cache at startup, marking those values with their age. The readiness probe can then depend on having some rates, not on the rate service being up, and callers that need fresh rates can check the timestamp.

What is the difference between expireAfterWrite and refreshAfterWrite?

expireAfterWrite removes an entry after the duration, so the next read blocks on a load. refreshAfterWrite keeps the entry and reloads it in the background on the first read after the duration, so readers get the old value without waiting. They are often combined: refresh keeps values fresh, and expiry is the upper limit on how stale a value may get.

Does a LoadingCache work across several service instances?

No, Caffeine is in-process, so each instance has its own copy and its own loads. With 20 instances, a key can be loaded 20 times per refresh period. For a slow, rate-limited source, a shared Redis layer behind the local cache, or a two-level cache, reduces that.

8Conclusion

In this answer, we turned hand-written cache-aside into a Caffeine LoadingCache whose loader is defined once and called only on a miss. Caffeine runs the loader once per key while other callers wait, which removes the stampede of the hand-written version. Loader failures reach the callers without caching anything, and refreshAfterWrite lets us keep serving the last good value when the source is down. Spring's @Cacheable is cache-aside through a proxy, and sync = true gives similar once-per-key loading.

What to say in the interviewAbout 80 seconds aloud

Open with

With Caffeine I build the cache once with its loader: Caffeine.newBuilder().maximumSize(10_000).expireAfterWrite of five minutes, then build with a lambda that calls rateClient.fetch(code). That returns a LoadingCache, and callers just call rates.get("EUR").

Then, if they want more

The difference from hand-written cache-aside is who owns loading. With cache-aside, every caller checks the cache, loads on a miss and puts the value, so the logic is repeated, and when a popular key expires, every concurrent caller calls the slow service; 50 threads means 50 calls. With read-through, the cache owns loading.

Caffeine runs the loader once per key and other callers for that key wait for the same result, and policies like timeouts and fallbacks live in one place. If the loader throws, the exception reaches the waiting callers and nothing is cached, so I decide whether to cache negative results briefly, and whether to keep serving an older value.

For that I would add refreshAfterWrite of one minute: the old value keeps being served while a background reload runs, and if the reload fails the old value stays, up to the expireAfterWrite limit.

Spring's @Cacheable is cache-aside done by a proxy, and @Cacheable with sync = true asks the provider to load once per key, which gives similar coalescing for annotated methods.

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 "Implement the lookup as a read-through cache with Caffeine's LoadingCache, and explain...": https://scrivio-interview-library.netlify.app/architecture/caching-strategies/f1a0fea49e/