Two-tier caching with Caffeine, Redis, and Pub/Sub invalidation
Benchmarking a Caffeine L1 and Redis L2 cache across two JVM instances, measuring Pub/Sub invalidation latency, dropped messages, and versioned sweeps.
Even Redis requires a network round trip, so read-heavy configuration data often needs an in-process local cache in front of it. The hard part is keeping those local caches consistent across multiple instances. I ran a Caffeine L1 + Redis L2 setup across two JVM processes and measured read latency, Pub/Sub invalidation delay, and how long stale values linger when a message drops.
Tested with Spring Boot 4.0.2, Kotlin 2.2.21, Java 21, Caffeine 3.2.3, Spring Data Redis 4.0.2 (Lettuce 6.8.2), Redis 8.4.0, and PostgreSQL 17.6. Measurements ran on a local PC (12 cores, 32GB RAM, Windows with Docker Desktop/WSL2) with two instances of the same JAR running side by side.
Background
Our service reads configuration data—feature flags, visibility policies, and similar settings—on nearly every request. I covered Redis expiration hazards in my post on defending against cache stampede, penetration, and avalanche, but when a single request reads the same keys multiple times, even Redis round trips add up. Putting Caffeine (L1) in JVM memory in front of Redis (L2) and PostgreSQL removes almost all of that network overhead.
Here are the latencies for 20,000 reads across 1,000 keys (200-byte values), excluding 5,000 warmup reads and taking the median of three runs:
| Layer | p50 | p99 |
|---|---|---|
| L1 (Caffeine) | ≤ 0.1µs | ≤ 0.3µs |
| L2 (Redis) | 553µs | 768µs |
| DB (PostgreSQL) | 1,608µs | 2,172µs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"type": "bar",
"data": {
"labels": ["L1 Caffeine", "L2 Redis", "DB PostgreSQL"],
"datasets": [
{ "label": "p50 (µs)", "data": [0.1, 552.9, 1608.4], "backgroundColor": "#7aa2f7" },
{ "label": "p99 (µs)", "data": [0.3, 768.2, 2171.8], "backgroundColor": "#f7768e" }
]
},
"options": {
"scales": { "y": { "type": "logarithmic", "title": { "display": true, "text": "µs (log scale)" } } },
"plugins": { "title": { "display": true, "text": "Read latency by cache layer" } }
}
}
L1 reads fell below System.nanoTime() resolution, so I recorded them as ≤ 0.1µs—roughly 5,000× faster than L2. The DB path includes the initial L2 miss check and writing the loaded value back to L2.
Invalidation flow and internals
Because each JVM instance holds its own L1 cache, updating a key on Instance A requires evicting it on Instance B. I used Redis Pub/Sub to broadcast invalidation events.
flowchart TD
W["Instance A: DB commit"] --> L2["Update L2 Redis value"]
L2 --> P["PUBLISH cache:invalidate"]
P --> S["Instance B listener"]
S --> I["Invalidate L1 entry"]
I --> R["Next read loads fresh value from L2"]
RedisMessageListenerContainer keeps a dedicated subscriber connection open and dispatches incoming messages to registered MessageListener callbacks. Keep in mind that Redis Pub/Sub is fire-and-forget: Redis pushes each message only to subscribers connected at that exact moment and never buffers history. Any invalidation published while a subscriber connection is down is permanently lost, even after Lettuce reconnects.
To guard against both out-of-order loads and dropped messages, I attached a monotonic version number to every cached value and invalidation message. If an instance has already seen a newer invalidation version, it refuses to populate L1 with an older value fetched late from L2. To cap staleness when a Pub/Sub message drops, I set a short L1 TTL (10 seconds here) and added a 1-second background sweeper that batch-compares local L1 versions against L2.
Implementation
1
2
3
4
5
6
7
8
// build.gradle.kts
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-redis")
implementation("org.springframework.boot:spring-boot-starter-jdbc")
implementation("com.github.ben-manes.caffeine:caffeine")
implementation("org.jetbrains.kotlin:kotlin-reflect")
runtimeOnly("org.postgresql:postgresql")
}
1
2
3
4
5
6
7
8
9
# src/main/resources/application.yml
spring:
data:
redis:
host: localhost
port: 6379
app:
cache:
l1-ttl: 10s
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// src/main/kotlin/com/example/cache/TwoTierCache.kt
package com.example.cache
import com.github.benmanes.caffeine.cache.Cache
import com.github.benmanes.caffeine.cache.Caffeine
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.MessageListener
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.data.redis.core.StringRedisTemplate
import org.springframework.data.redis.core.script.RedisScript
import org.springframework.data.redis.listener.ChannelTopic
import org.springframework.data.redis.listener.RedisMessageListenerContainer
import org.springframework.jdbc.core.simple.JdbcClient
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import org.springframework.transaction.support.TransactionTemplate
import java.time.Duration
import java.util.concurrent.ConcurrentHashMap
data class Versioned(val version: Long, val payload: String) {
fun encode() = "$version|$payload"
companion object {
fun decode(raw: String) = raw.indexOf('|').let { Versioned(raw.substring(0, it).toLong(), raw.substring(it + 1)) }
}
}
@Component
class TwoTierCache(
private val redis: StringRedisTemplate,
private val jdbc: JdbcClient,
private val tx: TransactionTemplate,
@Value("\${app.cache.l1-ttl:10s}") l1Ttl: Duration,
) {
val l1: Cache<String, Versioned> = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(l1Ttl) // Upper bound on staleness if Pub/Sub drops a message
.build()
private val latestSeen = ConcurrentHashMap<String, Long>()
fun get(key: String): Versioned? {
l1.getIfPresent(key)?.let { return it }
val loaded = redis.opsForValue().get("l2:$key")?.let(Versioned::decode)
?: loadFromDb(key)?.also { redis.opsForValue().set("l2:$key", it.encode(), Duration.ofMinutes(10)) }
?: return null
// Skip L1 population if a newer invalidation version has already arrived
if (loaded.version >= (latestSeen[key] ?: Long.MIN_VALUE)) l1.put(key, loaded)
return loaded
}
private fun loadFromDb(key: String): Versioned? =
jdbc.sql("select version, payload from config_entry where k = :k").param("k", key)
.query { rs, _ -> Versioned(rs.getLong(1), rs.getString(2)) }.optional().orElse(null)
fun update(key: String, payload: String): Long {
val version = tx.execute {
jdbc.sql("update config_entry set version = version + 1, payload = :p where k = :k returning version")
.param("p", payload).param("k", key).query(Long::class.java).single()
}!!
redis.opsForValue().set("l2:$key", Versioned(version, payload).encode(), Duration.ofMinutes(10))
redis.convertAndSend(CHANNEL, "$key|$version")
return version
}
fun onInvalidate(body: String) {
val (key, version) = body.split('|').let { it[0] to it[1].toLong() }
latestSeen.merge(key, version, ::maxOf)
val cur = l1.getIfPresent(key)
if (cur == null || cur.version < version) l1.invalidate(key)
}
companion object { const val CHANNEL = "cache:invalidate" }
}
@Component
class L1VersionSweeper(private val cache: TwoTierCache, private val redis: StringRedisTemplate) {
private val versions = RedisScript.of(
"local r = {} for i, k in ipairs(KEYS) do local v = redis.call('GET', k) " +
"r[i] = v and string.match(v, '^(%d+)|') or '0' end return r",
List::class.java,
)
// Fallback for dropped Pub/Sub messages: batch-check L1 versions against L2 (@EnableScheduling required)
@Scheduled(fixedDelay = 1000)
fun sweep() {
val keys = cache.l1.asMap().keys.toList().ifEmpty { return }
val remote = redis.execute(versions, keys.map { "l2:$it" }) ?: return
keys.zip(remote).forEach { (k, v) ->
val local = cache.l1.getIfPresent(k)
if (local != null && local.version < v.toString().toLong()) cache.l1.invalidate(k)
}
}
}
@Configuration
class PubSubConfig {
@Bean
fun listenerContainer(cf: RedisConnectionFactory, cache: TwoTierCache) = RedisMessageListenerContainer().apply {
setConnectionFactory(cf)
addMessageListener(MessageListener { m, _ -> cache.onInvalidate(String(m.body)) }, ChannelTopic(TwoTierCache.CHANNEL))
}
}
Propagation latency and message loss
To measure end-to-end invalidation latency, Instance A updated a single key 500 times at 20ms intervals while Instance B polled it continuously and logged the first timestamp it observed each new version. Both JVMs ran on the same host, so wall-clock microsecond timestamps were directly comparable.
| Metric (500 updates, 2 runs) | p50 | p99 | Max |
|---|---|---|---|
| Publish → Instance B receives | 1.0 / 1.6ms | 2.1 / 2.9ms | 6.3 / 9.8ms |
| Instance A commit → Instance B reads new value | 2.6 / 3.1ms | 4.2 / 5.8ms | 13.0 / 18.7ms |
Under healthy conditions, the stale window lasted only a few milliseconds and Instance B saw all 500 updates. End-to-end visibility takes 1–2ms longer than raw Pub/Sub delivery because L2 write, publish, receive, and L2 reload execute in sequence after the DB commit.
Next, I simulated message loss by running CLIENT KILL TYPE pubsub right before an update to sever the subscriber connection. Lettuce reconnects and resubscribes automatically, but any message published during the gap disappears.
| Configuration (5 trials) | Messages dropped | Stale window seen by Instance B |
|---|---|---|
| 10s L1 TTL only | 5 / 5 | 254, 883, 4,004, 7,141, 7,753ms |
| 10s L1 TTL + 1s version sweep | 4 / 5 | 365, 450, 459, 464ms |
With TTL alone, stale values survived for the remaining TTL—up to nearly 7.8 seconds. Adding the 1-second version sweeper cleared all four dropped-message cases in under 500ms. In the fifth trial, Lettuce finished reconnecting before the publish happened, so the message arrived normally.
Decision matrix and production pitfalls
| Data profile | Recommended setup |
|---|---|
| Very read-heavy, a few seconds of staleness acceptable | L1 + L2 + Pub/Sub + short L1 TTL |
| Sub-second staleness target even if Pub/Sub drops | Above + periodic version sweeper |
| Immediate consistency required across all instances | L2 only (skip L1) |
| Guaranteed delivery of invalidation history | Persistent channel such as Redis Streams |
Knowing when not to add L1 saves you from nasty consistency bugs. Never put account balances, inventory counts, or permission checks in a local L1 cache where even one stale read causes incorrect behavior. Write-heavy keys are also a poor fit: you pay for constant invalidation traffic while L1 hit rates stay low. And on memory-constrained containers, leaving Caffeine unbounded without maximumSize increases GC pressure enough to cancel out the latency gains.
Always publish the invalidation message after the DB transaction commits and L2 is updated. Publishing before commit creates a race where another instance evicts L1, immediately reloads the old value from L2 or the DB, and pins that stale value in L1 until its TTL expires. Also note that standard Pub/Sub on Redis Cluster broadcasts every message to all nodes; if you run many instances with high invalidation volume, look at Sharded Pub/Sub (
SPUBLISH) instead.
Checklist
- Can every key stored in L1 tolerate a few seconds of staleness?
- Is the L1 TTL equal to or shorter than the maximum acceptable stale window on message loss?
- Are invalidation messages published only after both the DB commit and the L2 update succeed?
- Do cached values carry a version so late-arriving stale reads cannot repopulate L1?
- Are subscriber reconnect events logged or exported as metrics so silent disconnects show up in monitoring?