Video in progress

Staff 🌱 Spring

Local cache (Caffeine), distributed cache (Redis) or a two-level cache: which would you pick for a service, and by what criteria?

A local cache is the fastest and simplest, but it is inconsistent between instances and duplicated in every pod; Redis is shared and more consistent, but adds network latency and a new point of failure. A two-level cache takes the best of both, but invalidation gets more complex.

📖 Answer

I ask four questions:

  1. How stale can the data be? "A currency rate that is 1 minute old is fine": a local cache with a TTL is enough. "The user was blocked, immediately in every pod": a local cache is risky.
  2. How big is it? 50 MB of reference data fits in every pod easily. 20 GB of sessions and carts: only a distributed cache.
  3. How expensive is the computation, and what happens when the cache is empty? After a deploy, the local caches of 20 pods are empty: 20 times the load on the database. With Redis the cache survives the deploy.
  4. What is the latency budget? Caffeine takes nanoseconds, Redis 0.3–1 ms of network plus serialization. If one request hits the cache 200 times, the difference is noticeable.
Caffeine Redis Two-level
Speed Highest With the network High on a local hit
Consistency between instances No Yes "Almost", with pub/sub invalidation
Failure Together with the pod If Redis is down, you need a fallback Both
Operations None Cluster, memory, monitoring The most

A two-level cache (L1 Caffeine with a short TTL + L2 Redis): hot keys stay local, the rest in Redis. On a change, a "key X is invalid" message is sent to all pods through Redis pub/sub or Kafka. A message can be lost, which is why the L1 TTL must be short (seconds): it is the upper bound on inconsistency.

Extra rules with Redis:

  • When Redis is down the service must keep working: a cache error → read from the database, but with a limit so you don't choke the database. In Spring, CacheErrorHandler handles this.
  • Version the serialization format: during a deploy the old and new code read the same key in different formats.
  • Putting everything in one Redis means that later the "cache", the "rate limiter" and the "sessions" squeeze each other's memory.

I usually start simple: @Cacheable + Caffeine. I add Redis when the need for consistency across many instances or for size has been measured.