Video in progress

Strong Middle ⚡ Redis and caching

When do you need a two-level cache (local Caffeine + Redis), and how do you clear stale data across instances?

When even a trip to Redis on every request is too expensive: for very hot data that rarely changes. L1 lives inside the JVM with a short TTL, and L2 is Redis. On a change, the Redis entry is deleted and a message goes out over Pub/Sub telling all instances to "remove it from L1".

📖 Answer

The numbers: reading from Caffeine takes hundreds of nanoseconds, from Redis 0.3-1 ms with the network, plus deserialization. For settings or a category tree read 20 thousand times per second, that difference shows up in CPU and latency.

Reading:

public Config get(String key) {
    return local.get(key, k -> {
        String json = redis.opsForValue().get("cfg:" + k);
        if (json != null) return mapper.readValue(json, Config.class);
        Config c = repo.load(k);
        redis.opsForValue().set("cfg:" + k, mapper.writeValueAsString(c), Duration.ofMinutes(30));
        return c;
    });
}

Writing:

repo.save(cfg);
redis.delete("cfg:" + cfg.key());
redis.convertAndSend("cfg-invalidate", cfg.key());   // every instance removes it from L1

Problems:

  • a Pub/Sub message can be lost (if an instance is reconnecting at that moment). That's why the L1 TTL is short, 30-60 s, which is the upper bound on inconsistency;
  • the instance that sent the message receives it too, which is harmless;
  • L1 memory is on the heap, so set maximumSize, otherwise you get GC pressure.

Client-side caching in Redis 6+ (CLIENT TRACKING) does this job at the server level: Redis itself notifies you when a key changes. Lettuce supports it partially, but there's no direct integration with Spring Cache.