Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Explain the difference between expireAfterWrite, expireAfterAccess and refreshAfterWrite in Caffeine, and how you would configure a Caffeine cache in Spring Boot through properties.

expireAfterWrite removes an entry a fixed time after it was created or last replaced, however often it is read. expireAfterAccess removes an entry after a period with no reads or writes, so a popular entry can live forever. refreshAfterWrite does not remove anything: after the period, the next access triggers an asynchronous reload through a CacheLoader while the old value is still returned. In Spring Boot we set spring.cache.type=caffeine, list the caches in spring.cache.cache-names and set spring.cache.caffeine.spec, for example maximumSize=10000,expireAfterWrite=10m, or define our own Caffeine configuration for finer control.

Background to this question

Caffeine is the default choice for in-process caching in Java, and Spring Boot supports it out of the box. Its three time-based settings sound similar, but they answer different questions: how old may a value be, how long may an unused value stay, and should a value be renewed before anyone has to wait for it. Picking the wrong one leads either to stale data that never leaves the cache or to users waiting for slow reloads. In this answer, we will recap what Caffeine is, look at each of the three settings with a timeline, see how size limits work, and configure a Caffeine cache in Spring Boot through properties and through code.

1A Quick Recap of Caffeine

Caffeine is a high-performance cache library that lives inside our JVM. Conceptually it is a ConcurrentHashMap with rules for removing entries: by size, by time, or by reference. Because it is in-process, a hit costs a hash lookup, with no network call and no serialization. Spring's CaffeineCacheManager adapts it to the cache abstraction, so @Cacheable methods can use it without any Caffeine code in our services.

Each Caffeine cache is configured with a builder. The time-based settings take a Duration, and they can be combined with each other and with a size limit.

2ExpireAfterWrite: A Fixed Maximum Age

expireAfterWrite measures time from when the entry was created or last replaced. Reads do not extend it. So with expireAfterWrite(10, MINUTES) an entry written at 09:00 is gone at 09:10, even if it was read a thousand times in between. This gives us a guaranteed upper bound on staleness, which is usually what we want for data that changes in the source, such as prices or product details.

3ExpireAfterAccess: Removing Idle Entries

expireAfterAccess measures time since the last read or write. Every access resets the clock. With expireAfterAccess(10, MINUTES), an entry read every minute never expires, while an entry nobody reads for ten minutes disappears. That is good for keeping memory focused on what is in use, for example per-session data, but it gives no staleness bound: a popular entry can stay forever with a value loaded hours ago. If the data can change in the source, combine it with expireAfterWrite or use expireAfterWrite instead.

4RefreshAfterWrite: Renewing Without Making Anyone Wait

refreshAfterWrite marks an entry as eligible for refresh after the period, but does not remove it. The next access after that point still returns the current value immediately and starts a reload in the background. When the reload finishes, the new value replaces the old one. If the reload fails, the old value stays. Because Caffeine has to know how to reload, refreshAfterWrite needs a CacheLoader, which makes the cache a LoadingCache.

Java
LoadingCache<Long, Price> prices = Caffeine.newBuilder()
.maximumSize(10_000)
.refreshAfterWrite(Duration.ofMinutes(1)) // reload in the background after 1 minute
.expireAfterWrite(Duration.ofMinutes(10)) // but never serve a value older than 10 minutes
.build(id -> repo.loadPrice(id));
prices.get(42L); // 09:00:00 miss: loads and waits, returns 9.99
prices.get(42L); // 09:00:30 hit: returns 9.99
prices.get(42L); // 09:01:10 returns 9.99 at once and starts a reload in the background
prices.get(42L); // 09:01:11 returns 10.49 once the reload has finished
// no reads until 09:11:00 or later: the entry has expired, the next read waits for a load
Three time settings compared
SettingClock starts atReads extend it?When time is up
expireAfterWritecreate or replacenoentry removed; next read waits for a load
expireAfterAccesslast read or writeyesentry removed; hot entries may never expire
refreshAfterWritecreate or replacenoold value returned, reload in background
Expiry removes entries; refresh renews them. refreshAfterWrite needs a CacheLoader.

Notice how the two settings work together. refreshAfterWrite keeps hot entries fresh without making callers wait, and expireAfterWrite still removes entries nobody reads, so a rarely used entry does not stay stale forever. The refresh interval should be shorter than the expiry interval, otherwise the entry expires before a refresh can happen.

5Size Limits and Eviction

Time is one limit; size is the other, and every production cache should have one. maximumSize limits the number of entries. maximumWeight with a weigher limits a total weight that we define, for example an estimate of bytes per entry, which matters when entries vary greatly in size. When the limit is reached, Caffeine evicts using the Window TinyLFU policy, which keeps entries that are used often rather than simply the most recently used ones. Eviction runs asynchronously on an executor, so the cache can briefly exceed its limit.

6Configuring Caffeine in Spring Boot

With Caffeine on the classpath, Spring Boot creates a CaffeineCacheManager. Properties cover the common case, where all caches share one specification.

Properties
# application.properties
spring.cache.type=caffeine
spring.cache.cache-names=products,prices
spring.cache.caffeine.spec=maximumSize=10000,expireAfterWrite=10m,recordStats
# Result: two caches, products and prices, each holding at most 10,000 entries,
# each entry removed 10 minutes after it was written, with hit and miss statistics on

The spec string uses Caffeine's own format: comma-separated settings, with durations written as a number and a unit such as 10m or 30s. recordStats turns on hit and miss statistics, which Micrometer can then export. Boot also accepts a Caffeine bean or a CaffeineSpec bean if we prefer code.

If the spec uses refreshAfterWrite, Spring Boot needs a CacheLoader bean, which it attaches to the CaffeineCacheManager. That is awkward with one shared loader, because a single loader must know how to reload keys of every cache. In practice, when we need refresh we usually build that cache in code with its own loader, or keep @Cacheable caches on plain expiry.

7Follow-up questions

How would you give two caches different expiry settings?

The spring.cache.caffeine.spec property applies the same spec to every cache it creates, so we move to code. A CacheManagerCustomizer<CaffeineCacheManager> can call registerCustomCache("prices", Caffeine.newBuilder().expireAfterWrite(Duration.ofSeconds(30)).maximumSize(10_000).build()) and the same for products with ten minutes, each cache with its own settings. Caches not registered this way still use the default spec.

What happens if we set both expireAfterWrite and expireAfterAccess?

Both rules apply and an entry is removed when either one says so. That can make sense when we want idle entries gone after five minutes and every entry gone after an hour, whatever its popularity. For a single fixed lifetime, one setting is clearer.

Does refreshAfterWrite mean the value is always fresh?

No. The refresh only starts when someone reads the entry after the period, and the reader that triggers it still gets the old value. So the staleness of a hot entry is roughly the refresh interval plus the reload time, and a cold entry is only renewed by expiry. It reduces latency spikes, not the need for an expiry bound.

8Conclusion

In this answer, we compared Caffeine's three time-based settings. expireAfterWrite removes an entry a fixed time after it was written and gives a real staleness bound. expireAfterAccess removes entries that have been idle, so popular entries may never expire. refreshAfterWrite keeps the entry and reloads it asynchronously on the next access, returning the old value meanwhile, and it needs a CacheLoader. We saw that size limits use maximumSize or maximumWeight with Window TinyLFU eviction, and we configured Caffeine in Spring Boot with spring.cache.type, spring.cache.cache-names and spring.cache.caffeine.spec, or with registerCustomCache when caches need different settings.

What to say in the interviewAbout 80 seconds aloud

Open with

In Caffeine, expireAfterWrite removes an entry a fixed time after it was created or last replaced; reads do not extend it, so it gives a hard upper bound on staleness, which is what I want for data that changes in the source. expireAfterAccess resets the clock on every read or write, so it removes idle entries, but a popular entry can stay forever with an old value, so it is more for memory than for freshness. refreshAfterWrite does not remove anything: after the period, the next access returns the current value immediately and triggers an asynchronous reload, and if the reload fails the old value stays.

Then, if they want more

Because Caffeine has to reload by itself, it needs a CacheLoader. I often combine refreshAfterWrite with a longer expireAfterWrite, so hot keys are renewed without waits and cold keys still expire. Every cache should also have a size bound, maximumSize for entry counts or maximumWeight with a weigher, and eviction uses Window TinyLFU, asynchronously.

In Spring Boot I set spring.cache.type=caffeine, spring.cache.cache-names, and spring.cache.caffeine.spec such as maximumSize=10000,expireAfterWrite=10m,recordStats. That spec applies to every cache, so when two caches need different expiry I use a CacheManagerCustomizer and registerCustomCache with its own Caffeine builder.

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 "Explain the difference between expireAfterWrite, expireAfterAccess and refreshAfterWrite...": https://scrivio-interview-library.netlify.app/databases/caching/44ab6b4788/