Background Refresh
Stale-while-revalidate for your cache. When an entry gets old, refresh it in the background — no reader ever sees a miss, no reader ever waits.
The problem with expiry
With expireAfterWrite, when the TTL passes the entry is gone. The next reader pays the full cost
of reloading it — a database query, an API call, whatever. Under high traffic, many readers can hit that gap
simultaneously.
refreshAfterWrite flips this: when the TTL passes, the stale value keeps being
served
while a background coroutine quietly reloads it. No reader ever sees a miss.
refreshAfterWrite, it's the same idea.
Basic usage
import io.peekandpoke.ultra.cache.fastCache
import kotlin.time.Duration.Companion.minutes
val cache = fastCache<String, UserProfile> {
refreshAfterWrite(ttl = 5.minutes) { key ->
// This is a suspend function — runs in a background coroutine
userService.fetchProfile(key)
}
}
// First put — starts the TTL clock
cache.put("user:42", initialProfile)
// After 5 minutes:
// - Reader A gets the old profile instantly (no wait)
// - A background coroutine calls userService.fetchProfile("user:42")
// - Reader B (moments later) gets the new profile The loader function receives the key and returns the new value. It runs in the cache's
CoroutineScope, so it integrates with structured concurrency.
Hard TTL
What if the loader is slow or keeps failing? You might not want to serve infinitely stale data.
The optional hardTtl parameter evicts entries past a hard deadline, even during a refresh:
val cache = fastCache<String, String> {
refreshAfterWrite(
ttl = 5.minutes, // start refreshing after 5 minutes
hardTtl = 30.minutes, // evict completely after 30 minutes
) { key ->
fetchFromApi(key)
}
} Without hardTtl, stale entries are served indefinitely as long as a refresh is in-flight or
pending. With it, you get a backstop.
Deduplication
Only one refresh runs per key at a time. If the cache detects that key "x" is stale and a
refresh is already in-flight, it skips launching another one. When the refresh completes and calls
cache.put(), the write timestamp resets and the entry is fresh again.
Error handling
If the loader throws, the refresh is considered failed. The key is marked as eligible for retry on the next processing loop iteration (~50ms later). This means a transient failure (network blip, temporary API error) will self-heal on the next loop cycle.
var attempt = 0
val cache = fastCache<String, String> {
refreshAfterWrite(ttl = 5.minutes) { key ->
attempt++
if (attempt == 1) error("transient failure")
fetchFromApi(key) // succeeds on retry
}
} Combining with other behaviours
Stack refreshAfterWrite with other behaviours for fine-grained control:
val cache = fastCache<String, UserProfile> {
refreshAfterWrite(ttl = 5.minutes) { key ->
userService.fetchProfile(key)
}
maxEntries(10_000) // hard cap on entry count
onEviction { key, _ -> // log evictions
logger.info("evicted $key")
}
} Note: refreshAfterWrite and expireAfterWrite are independent behaviours.
If you use both, the write-TTL eviction happens regardless of whether a refresh is pending. Use
hardTtl on the refresh behaviour instead if you want the refresh to have a deadline.