Eviction Policies

Four eviction behaviours — use one, several, or all together.

Expire after access

Evicts entries that haven't been read or written within a time-to-live window. The timer resets on every access:

import io.peekandpoke.ultra.cache.fastCache
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds

val cache = fastCache<String, String> {
    expireAfterAccess(5.minutes)
}

cache.put("session", "abc123")

// Reading resets the TTL
cache.get("session")  // resets the 5-minute timer

// After 5 minutes of no access, the entry is evicted
Eviction is processed in the background loop, not on the calling thread. An expired entry might survive briefly past its TTL until the next loop iteration (default: 50ms).

Expire after write

Evicts entries that haven't been written within a TTL window. Unlike expireAfterAccess, reading an entry does NOT reset the timer — only put() does:

val cache = fastCache<String, String> {
    expireAfterWrite(5.minutes)
}

cache.put("token", "abc123")

// Reading does NOT reset the TTL
cache.get("token")  // timer keeps ticking from the original put

// Only a new put resets the TTL
cache.put("token", "xyz789")  // timer resets now

Use expireAfterWrite when the data has a known staleness window regardless of how often it's read — API tokens, DNS lookups, config values fetched from a remote service, exchange rates.

If you need stale data to be refreshed rather than evicted, see Background Refresh — it serves the old value while reloading in the background.

Max entries

Caps the number of entries. When the limit is exceeded, the least-recently-accessed entries are evicted first (LRU):

val cache = fastCache<String, String> {
    maxEntries(100)
}

// After 100 entries, the oldest-accessed entry is evicted
// when a new one is added

Max memory usage

Caps the total estimated memory usage. Uses an ObjectSizeEstimator to recursively measure object graphs. When the budget is exceeded, LRU eviction kicks in:

import io.peekandpoke.ultra.cache.ObjectSizeEstimator

val estimator = ObjectSizeEstimator()

val cache = fastCache<String, MyData> {
    maxMemoryUsage(
        maxMemorySize = 50 * 1024 * 1024,  // 50 MB
        estimator = estimator,
    )
}

The estimator walks the object graph recursively, accounting for:

  • Object headers (16 bytes on 64-bit HotSpot)
  • Primitive fields (1–8 bytes each)
  • String content (header + char array)
  • Collections and maps (header + pointers + elements)
  • Nested objects (recursive traversal with cycle detection)
Memory estimation is exactly that — an estimate. It's close enough for cache budgeting but don't treat it as a precise memory profiler.

Combining behaviors

Stack multiple behaviors for fine-grained control. All active behaviors are checked during each eviction cycle:

val cache = fastCache<String, ExpensiveResult> {
    expireAfterAccess(10.minutes)     // remove stale entries
    maxEntries(5000)                   // hard cap on count
    maxMemoryUsage(                    // hard cap on memory
        maxMemorySize = 100 * 1024 * 1024,
        estimator = ObjectSizeEstimator(),
    )
}

Custom loop delay

The background eviction loop runs every 50ms by default. Adjust it for your use case:

import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds

// Faster eviction checks (more CPU)
val responsive = fastCache<String, String>(loopDelay = 10.milliseconds) {
    expireAfterAccess(1.seconds)
}

// Slower checks (less CPU)
val relaxed = fastCache<String, String>(loopDelay = 1.seconds) {
    expireAfterAccess(5.minutes)
}

Custom coroutine scope

By default the eviction loop runs in a global scope. Pass a custom scope if you need lifecycle control:

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers

val scope = CoroutineScope(Dispatchers.Default)

val cache = fastCache<String, String>(scope = scope) {
    expireAfterAccess(5.minutes)
}

// When the scope is cancelled, the eviction loop stops

All behaviours at a glance

Behaviour Trigger Strategy
expireAfterAccess No read or write within TTL Time-based, resets on read + write
expireAfterWrite No write within TTL Time-based, resets on write only
maxEntries Entry count exceeds limit LRU (least recently accessed)
maxMemoryUsage Estimated memory exceeds budget LRU (least recently accessed)
refreshAfterWrite Write age exceeds soft TTL Async reload; optional hard TTL evicts
onEviction Another behaviour evicts an entry Observer — fires callback
statistics Every cache operation Observer — counts hits, misses, puts, evictions