Video in progress

Senior 🌱 Spring

When does enabling Hibernate's second-level cache pay off, and when does it do harm?

It helps for entities that rarely change, are read a lot and are fetched by id (reference data). For data that is written often, that several instances can't keep in sync, or that is changed through native SQL, it gives you stale data and extra complexity.

📖 Answer

The first-level cache is the persistence context, and it lives as long as one transaction. The second-level cache (L2) lives at the SessionFactory level, so it is shared across the whole application. find(Country.class, 5) goes to the database the first time, and later transactions take it from the cache.

Setup (using JCache + Caffeine/Ehcache as an example):

spring:
  jpa:
    properties:
      hibernate.cache.use_second_level_cache: true
      hibernate.cache.region.factory_class: jcache
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
class Country { ... }

When it helps:

  • reference data such as currencies, countries, tariffs: lots of reads, almost no changes;
  • entities loaded a lot through findById or @ManyToOne.

When it's a problem:

  • L2 doesn't cache queries: findByStatus(...) is still SQL. There is a separate query cache for that, but it is invalidated on every write to the table and is often useless.
  • With a local provider (Caffeine, Ehcache) and 3 instances, an entity changed on one stays stale on the others. A clustered provider (Hazelcast, Infinispan) solves this, but adds network and operational load.
  • If another service or a native UPDATE changes the database, Hibernate doesn't know about it.
  • On a frequently written entity the READ_WRITE strategy works with soft locks and costs more than it gives.

In practice I measure first: I look at the hit/miss ratio through Hibernate statistics (hibernate.generate_statistics) or Micrometer. Often the problem isn't a missing L2 but N+1 or a bad query, and that should be fixed first. For reference data, plain @Cacheable at the service level is often easier to understand.