Video in progress

How do you set up Hibernate's second-level cache in an application with several instances, and what consistency problems should you be ready for?

If each instance has a local cache, a change written on one node isn't visible on another. The options are a local cache with invalidation messages (Infinispan invalidation mode), a distributed cache (Hazelcast, JCache over Redis), or using L2 only for immutable data.

📖 Answer

The problem: node A cached Product#5, and node B changed the price. On its next request, A serves the old price for an unlimited time, if there's no TTL.

I see three routes:

  1. Read-only reference data only. Currencies, countries, tariff lists. A local Caffeine/Ehcache, the READ_ONLY strategy, refreshed on deploy. The simplest and safest. In many projects you should stop right here.

  2. Local cache + invalidation. Infinispan's invalidation mode: the node that wrote sends the others a "drop this key" message. Reads run at local speed. But if the message is delayed or lost (a network partition), stale data is visible for a short time. If you use the query cache, the update-timestamps region must be replicated too.

  3. A distributed cache (Hazelcast, Redis through JCache). All nodes see a single source, but every L2 read is now a network request, which may not be much faster than a PK lookup in the database. There's also the cost of serialization.

In every case:

  • L2 doesn't know about writes from outside Hibernate: another service, a migration script, native SQL. If those exist, a TTL is mandatory;
  • fast-changing and money-related entities stay out of the cache;
  • I watch hit/miss per region with hibernate.generate_statistics; a region with a hit rate below 80% usually doesn't pay off.

The conclusion is often that an explicit application-level cache (DTO, key, TTL, invalidation by event) is easier to manage and explain than L2.