Video in progress

Strong Middle 🧩 Microservices

If every instance has a local cache (Caffeine), how do you keep them in sync when the data changes?

The simplest way is a short TTL and living with staleness. If you need faster updates, the change event is broadcast to all instances through Kafka or Redis pub/sub and they evict the key. If you need strict accuracy, a local cache is the wrong choice.

📖 Answer

3 pods, each with a Caffeine cache for product prices. An admin changed a price: the request hit pod 1, which cleared its own cache. Pods 2 and 3 show the old price until the TTL expires. When a user refreshes the page, the price "jumps", because a different pod answers each time.

Options:

  1. A short TTL (30–60 seconds), with the business accepting it. For most data that is enough.
  2. An invalidation event:
@KafkaListener(topics = "product-changed",
               groupId = "#{T(java.util.UUID).randomUUID().toString()}")
public void evict(ProductChanged evt) {
    productCache.invalidate(evt.productId());
}

Here every pod subscribes with its own unique groupId, so the message reaches all of them, not just one. Many people miss this subtle point. (Every restart leaves a new group behind, so for this kind of "broadcast" Redis pub/sub is often simpler.)

  1. A two-level cache: local (short TTL) + Redis (shared). You update the Redis entry on change, and the local one goes stale quickly.

Don't forget that an invalidation message can get lost (the pod was restarting at that moment). So the event must always come with a TTL too, as the last line of defense.

Keeping things that must be exact, like money, stock and permissions, out of a local cache is the right call.