Video in progress
Which entities should go into the second-level cache and which should not? How do you decide?
Entities that are read a lot, change rarely and are written only through this application: reference data, settings, catalogs. I don't cache anything that changes fast, that other systems also write to, or that involves money.
📖 Answer
The L2 cache is not free: invalidation on every write, synchronization in a cluster, memory. So for each entity I ask three questions.
- What is the read/write ratio? Countries, currencies, course categories are read a thousand times a day and change once a month. Ideal candidates.
- Who else writes to the database? If another service, an ETL job or a DBA runs a manual UPDATE, Hibernate has no idea, and the cache keeps serving stale data.
- How bad is a stale value? Account balances, order status, limits: I never cache those.
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Currency { ... }
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "catalog")
public class Category { ... }
READ_ONLY is for data that never changes at all, and it is the cheapest. READ_WRITE uses a soft lock and prevents stale reads. NONSTRICT_READ_WRITE is for when you can accept brief staleness.
One more thing: the L2 cache only works when loading by ID (find, lazy loading). A JPQL query still goes to the database unless you enable the query cache separately. And the query cache is invalidated entirely on any change to the table, so on a write-heavy table it does more harm than good.
Before deciding, I measure the hit/miss ratio with hibernate.generate_statistics. If the hit ratio is below 50%, I remove the region.
Sign up to mark studied questions and save your progress.