Caching

suggest change

A cache keeps the result of an expensive operation (a database query, an HTTP call, a slow computation) so the next request for the same thing can be answered from memory.

Caching is easy to start and hard to get right. Every cache has to answer the same questions:

This article goes from the simplest option to the most capable:

Memoization with getOrPut

The simplest cache is a HashMap plus getOrPut. getOrPut returns the existing value, or computes, stores and returns a new one:

val cache = HashMap<Int, Long>()

fun slowSquare(n: Int): Long {
    println("computing $n")
    Thread.sleep(100) // pretend this is expensive
    return n.toLong() * n
}

fun cachedSquare(n: Int): Long = cache.getOrPut(n) { slowSquare(n) }

fun main() {
    println(cachedSquare(4))
    println(cachedSquare(4))
    println(cachedSquare(5))
}
computing 4
16
16
computing 5
25

Memoization turns exponential recursive algorithms into linear ones. Naive Fibonacci makes about 2^n calls; with a cache each value is computed once:

import java.math.BigInteger

val memo = HashMap<Int, BigInteger>()

fun fib(n: Int): BigInteger =
    if (n < 2) n.toBigInteger()
    else memo.getOrPut(n) { fib(n - 1) + fib(n - 2) }

fun main() {
    println(fib(100))
}
354224848179261915075

This works because Kotlin's getOrPut is a plain "get, compute, put" sequence, so the lambda can freely add other keys to the map. Don't do the same with ConcurrentHashMap.computeIfAbsent: modifying the map from inside its own mapping function throws IllegalStateException: Recursive update.

A generic memoize function

You can wrap any single-argument function in a cache:

fun <A, R> memoize(f: (A) -> R): (A) -> R {
    val cache = HashMap<A, R>()
    return { a -> cache.getOrPut(a) { f(a) } }
}

fun main() {
    val slowLength = { s: String ->
        println("computing '$s'")
        s.length
    }
    val fastLength = memoize(slowLength)

    println(fastLength("kotlin"))
    println(fastLength("kotlin"))
    println(fastLength("java"))
}
computing 'kotlin'
6
6
computing 'java'
4

For functions with several arguments, combine them into one key: a Pair, a Triple or, better, a data class:

data class PriceKey(val productId: Int, val currency: String)

val prices = HashMap<PriceKey, Double>()

fun price(productId: Int, currency: String): Double =
    prices.getOrPut(PriceKey(productId, currency)) {
        println("fetching price $productId $currency")
        19.99
    }

Two caveats about getOrPut:

A single value: by lazy

When there is just one value to cache, such as a parsed configuration file or a compiled regex, use a lazy property:

class Config(private val path: String) {
    val settings: Map<String, String> by lazy {
        println("reading $path")
        mapOf("port" to "8080", "host" to "localhost")
    }
}

fun main() {
    val config = Config("app.conf")
    println("created")
    println(config.settings["port"])
    println(config.settings["host"])
}
created
reading app.conf
8080
localhost

By default lazy is synchronized: if several threads read the property at once, the initializer runs only once. You can choose a different mode:

A lazy value never expires. For values that must be refreshed, use one of the caches below.

Thread-safe caching with ConcurrentHashMap

In a server, many threads access the cache at once. ConcurrentHashMap.computeIfAbsent atomically computes a missing value, and the mapping function runs at most once per key:

import java.util.concurrent.ConcurrentHashMap
import kotlin.concurrent.thread

val cache = ConcurrentHashMap<String, Int>()

fun lookup(key: String): Int = cache.computeIfAbsent(key) { k ->
    println("loading $k")
    Thread.sleep(100)
    k.length
}

fun main() {
    val threads = List(4) { thread { lookup("hello") } }
    threads.forEach { it.join() }
    println(cache)
}
loading hello
{hello=5}

Four threads asked for the same key, but loading hello is printed only once: the other threads waited for the first one to finish.

Things to keep in mind:

An LRU cache with LinkedHashMap

A least-recently-used (LRU) cache has a maximum size and, when full, evicts the entry that hasn't been used for the longest time.

java.util.LinkedHashMap has this built in. Created with accessOrder = true it keeps entries ordered from least to most recently accessed, and it calls removeEldestEntry after every insertion:

class LruCache<K, V>(private val maxSize: Int) {
    private val map = object : LinkedHashMap<K, V>(16, 0.75f, true) {
        override fun removeEldestEntry(eldest: MutableMap.MutableEntry<K, V>?): Boolean =
            size > maxSize
    }

    @Synchronized
    operator fun get(key: K): V? = map[key]

    @Synchronized
    operator fun set(key: K, value: V) {
        map[key] = value
    }

    @Synchronized
    fun getOrPut(key: K, compute: () -> V): V = map.getOrPut(key, compute)

    val size: Int
        @Synchronized get() = map.size

    @Synchronized
    override fun toString(): String = map.toString()
}

fun main() {
    val cache = LruCache<String, Int>(maxSize = 3)
    cache["a"] = 1
    cache["b"] = 2
    cache["c"] = 3
    println(cache)

    cache["a"]      // reading "a" makes it the most recently used
    cache["d"] = 4  // cache is full: evicts "b", the least recently used
    println(cache)
    println(cache["b"])
}
{a=1, b=2, c=3}
{c=3, a=1, d=4}
null

Note that with accessOrder = true even a read modifies the map (it moves the entry to the end), so every access must be synchronized, not just writes. Here @Synchronized locks on the LruCache instance. Holding a lock while getOrPut computes a value blocks all other callers, which is fine for cheap computations but not for slow I/O.

Expiring entries with a TTL

Data from a database or a remote service goes stale. A time-to-live (TTL) cache stores, with each value, the moment it expires.

Measure time with kotlin.time.TimeSource rather than System.currentTimeMillis(). The monotonic time source isn't affected by wall-clock changes, and taking TimeSource as a parameter lets tests control time with TestTimeSource:

import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
import kotlin.time.TestTimeSource
import kotlin.time.TimeMark
import kotlin.time.TimeSource

class TtlCache<K, V>(
    private val ttl: Duration,
    private val timeSource: TimeSource = TimeSource.Monotonic,
) {
    private class Entry<V>(val value: V, val expiresAt: TimeMark)

    private val map = HashMap<K, Entry<V>>()

    @Synchronized
    fun get(key: K): V? {
        val entry = map[key] ?: return null
        if (entry.expiresAt.hasPassedNow()) {
            map.remove(key)
            return null
        }
        return entry.value
    }

    @Synchronized
    fun put(key: K, value: V) {
        map[key] = Entry(value, timeSource.markNow() + ttl)
    }

    @Synchronized
    fun getOrPut(key: K, compute: () -> V): V =
        get(key) ?: compute().also { put(key, it) }
}

fun main() {
    val time = TestTimeSource()
    val cache = TtlCache<String, String>(ttl = 10.seconds, timeSource = time)

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

    time += 9.seconds
    println(cache.get("token"))

    time += 2.seconds
    println(cache.get("token"))
}
abc123
abc123
null

In production code you would create it with the default time source: TtlCache<String, String>(5.minutes).

This cache removes an expired entry only when someone reads it. Keys that are never read again stay in memory, so a real implementation also needs a size limit or a periodic cleanup. At this point it's usually better to use a library such as Caffeine, shown below.

Caching suspend functions

With coroutines you can't call a suspend function from inside computeIfAbsent or getOrPut on a shared map. You also want to avoid a cache stampede: if 100 coroutines ask for the same missing key at once, the backend should be called once, not 100 times.

The trick is to cache the Deferred (the in-progress computation) instead of the value. Everyone who asks for the key awaits the same Deferred:

import kotlinx.coroutines.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger

class SuspendCache<K : Any, V>(
    private val scope: CoroutineScope,
    private val loader: suspend (K) -> V,
) {
    private val map = ConcurrentHashMap<K, Deferred<V>>()

    suspend fun get(key: K): V {
        val deferred = map.computeIfAbsent(key) { k ->
            scope.async(start = CoroutineStart.LAZY) { loader(k) }
        }
        try {
            return deferred.await()
        } catch (e: Throwable) {
            // the load itself failed or was cancelled: forget it so the next call retries
            if (deferred.isCompleted) map.remove(key, deferred)
            throw e
        }
    }

    fun invalidate(key: K) {
        map.remove(key)?.cancel()
    }
}

fun main() = runBlocking {
    val cacheScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
    val calls = AtomicInteger()

    val users = SuspendCache<Int, String>(cacheScope) { id ->
        calls.incrementAndGet()
        delay(100) // simulate a network call
        "user-$id"
    }

    val results = List(10) { async { users.get(42) } }.awaitAll()
    println(results.distinct())
    println("loader calls: ${calls.get()}")

    println(users.get(42))
    println("loader calls: ${calls.get()}")

    cacheScope.cancel()
}
[user-42]
loader calls: 1
user-42
loader calls: 1

Design notes:

Production caching with Caffeine

Caffeine is the standard in-memory cache for the JVM. It is used by Spring, and it gives you everything the hand-written caches above lack: size limits with a near-optimal eviction policy (W-TinyLFU), expiry, refresh, statistics and high concurrency.

// build.gradle.kts
dependencies {
    implementation("com.github.ben-manes.caffeine:caffeine:3.3.1")
}

Manual cache

import com.github.benmanes.caffeine.cache.Caffeine
import java.time.Duration

data class User(val id: Int, val name: String)

fun loadUser(id: Int): User {
    println("loading user $id")
    return User(id, "user$id")
}

fun main() {
    val cache = Caffeine.newBuilder()
        .maximumSize(10_000)
        .expireAfterWrite(Duration.ofMinutes(5))
        .recordStats()
        .build<Int, User>()

    println(cache.get(1) { id -> loadUser(id) }) // miss: loads
    println(cache.get(1) { id -> loadUser(id) }) // hit

    println(cache.getIfPresent(2))               // miss: null, nothing loaded
    cache.put(2, User(2, "bob"))
    println(cache.getIfPresent(2))               // hit

    cache.invalidate(2)
    println(cache.getIfPresent(2))               // miss

    val stats = cache.stats()
    println("hits=${stats.hitCount()} misses=${stats.missCount()} hitRate=${stats.hitRate()}")
}
loading user 1
User(id=1, name=user1)
User(id=1, name=user1)
null
User(id=2, name=bob)
null
hits=2 misses=3 hitRate=0.4

cache.get(key) { ... } is atomic, like computeIfAbsent: concurrent callers for the same key wait for a single load. Use recordStats() and watch the hit rate in production; a cache with a low hit rate only costs memory.

Loading cache

If values are always loaded the same way, pass the loader to build and get a LoadingCache:

import com.github.benmanes.caffeine.cache.Caffeine
import java.time.Duration

data class User(val id: Int, val name: String)

fun loadUser(id: Int): User {
    println("loading user $id")
    return User(id, "user$id")
}

fun main() {
    val users = Caffeine.newBuilder()
        .maximumSize(1_000)
        .expireAfterWrite(Duration.ofMinutes(10))
        .refreshAfterWrite(Duration.ofMinutes(1))
        .build<Int, User> { id -> loadUser(id) }

    println(users.get(7))
    println(users.get(7))
    println(users.getAll(listOf(7, 8)))
}
loading user 7
User(id=7, name=user7)
User(id=7, name=user7)
loading user 8
{7=User(id=7, name=user7), 8=User(id=8, name=user8)}

expireAfterWrite and refreshAfterWrite work together: after 1 minute, the next read still returns the old value immediately while Caffeine reloads it in the background; after 10 minutes without a successful reload the entry is dropped. This keeps latency low and avoids many requests waiting on a reload at the same moment.

Eviction options

Caffeine's builder has options for most needs:

Eviction happens asynchronously, so right after a burst of writes the cache may briefly hold more than maximumSize entries. In tests, run maintenance on the calling thread and call cleanUp() to get deterministic results:

import com.github.benmanes.caffeine.cache.Caffeine

fun main() {
    val cache = Caffeine.newBuilder()
        .maximumSize(100)
        .executor(Runnable::run) // run maintenance on the caller's thread
        .build<Int, Int>()

    for (i in 1..1_000) cache.put(i, i * i)
    cache.cleanUp()
    println(cache.estimatedSize())
}
100

Don't write tests that expect a specific key to be evicted: W-TinyLFU considers how often keys are used, not only how recently, so it doesn't behave like a strict LRU.

Pitfalls and best practices

For caching HTTP responses in browsers and proxies, see the Cache-Control and ETag headers in HTTP headers.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents