Scrivio Interview library
ScenarioAdvanced6 min read · updated 12 November 2026

Teams want to enable the Hibernate second-level cache widely to reduce database load. What would you approve and what would you steer them away from?

I would approve the second-level cache for read-mostly reference data with few writers, such as countries, currencies or product categories, where a short staleness window is acceptable. I would steer teams away from caching frequently updated entities or tables written by several services, which leads to stale data, and towards explicit application caching with Spring Cache at service boundaries where the semantics are clear. Every cache would need hit-ratio and staleness metrics, and before any of it, teams should fix the query problems such as N+1 and missing indexes that create most of the load.

Why this question is asked

When several teams ask to switch on a caching layer at once, the request is usually a symptom: the database is under pressure and caching looks like the quickest relief. A senior engineer's job is to say yes where it is safe, say no where it will create harder problems, and make sure the real cause is addressed. Interviewers ask this scenario to hear how we draw that line and how we make it enforceable. In this answer, we will recap what the second-level cache is good and bad at, look at what to approve, what to steer away from and why, compare it with service-level caching, and set the conditions every cache must meet.

1A Quick Recap of What the Cache Is Good At

Hibernate's second-level cache stores entity state by id, shared across sessions. It speeds up em.find() and association loads by id. It does not speed up ordinary JPQL queries, which still go to the database unless the query cache is also on, and the query cache is invalidated whenever any table in the query changes.

Its main weakness is invalidation. It only knows about writes made through Hibernate in the same application, and with a local provider such as Ehcache, only within the same instance. So it works best when data rarely changes and almost all reads are by id.

2What I Would Approve

I would approve it for read-mostly reference data with few writers: countries, currencies, tax categories, product categories, feature configuration. These tables are small, change a few times a month through an admin screen in the owning service, and are read on almost every request, usually by id through an association. The hit ratio is typically above 99 percent and the staleness risk is low.

The approval comes with settings: READ_ONLY for truly immutable data, READ_WRITE otherwise, a time to live of a few minutes that the business has agreed is an acceptable delay for changes, and a size limit in the provider configuration.

Java
@Entity
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
class Currency { // 180 rows, changes once a year
@Id String code;
int fractionDigits;
}
// Order -> Currency association: each order load resolves currency from the cache, no join or select

3What I Would Steer Teams Away From

I would steer away from frequently updated entities, such as orders, stock levels, prices and account balances. With several instances and local caches, every update risks stale reads elsewhere, and the hit ratio is low anyway because the data keeps changing. I would also refuse caching for tables written by more than one service or by batch jobs and scripts, because those writes bypass Hibernate entirely and leave entries stale until they expire.

And I would be very cautious with the query cache. On any table that changes regularly, it is invalidated constantly, and a hit still loads each entity by id, so it often costs more than it saves.

Approve or steer away
DataDecisionReason
Countries, currencies, categoriesApproveread-mostly, one writer, id lookups
Feature configurationApprove with short TTLrare changes, small, read on every request
Orders, stock, pricesSteer awayfrequent writes, low hit ratio, stale risk
Tables shared by several servicesSteer awaywrites bypass Hibernate
Query cache on busy tablesSteer awayinvalidated on every write to the table

4Why Service-Level Caching Is Often Better

For data that is expensive to compute or read but not reference data, I would point teams to explicit application caching with Spring's cache abstraction at the service boundary. We cache the result of a service method, such as a product page model, in a cache like Redis or Caffeine, with a name, a key and a TTL we chose, and we evict it explicitly in the methods that change the data.

Java
@Cacheable(cacheNames = "productView", key = "#id")
public ProductView productView(long id) { ... } // one cached DTO instead of 6 entity lookups
@CacheEvict(cacheNames = "productView", key = "#cmd.id")
public void updateProduct(UpdateProduct cmd) { ... }

The reason this is clearer is that everything about the cache is visible in the code: what is cached, under which key, for how long and who evicts it. It caches the shaped result the caller needs, so one hit replaces several queries. A shared Redis cache is consistent across instances, and if a batch job also writes the data, it can evict the same key. An ORM-level cache hides all of these decisions in annotations on entities, far away from the code that reads and writes.

5Conditions Every Cache Must Meet

Approval comes with two requirements. First, metrics: hit ratio per region or cache name, size, evictions and, where possible, the age of served entries. Hibernate statistics and Micrometer expose most of this. A cache below an agreed hit ratio, say 80 percent, after a month gets removed. Second, a staleness statement: for each cached type, how stale it may be, agreed with the product owner, and how each write path invalidates it.

Most importantly, before any cache, teams should fix the query problems. In my reviews, most database pressure comes from N+1 queries, missing indexes and over-fetching entities for list screens. A list page that runs 101 queries can be brought to 2 with a fetch join or projection, which reduces load more than any cache and has no staleness at all.

Step throughReview of a team's caching request
  1. Find the top queries by loadpg_stat_statements, statement counts per request
  2. Caused by N+1, missing index or over-fetching?
    YesFix the query firstNoConsider caching
  3. Read-mostly reference data, one writer?
    YesApprove L2 cache with TTLNoUse Spring Cache at the service boundary
  4. Require hit ratio and staleness metricsremove the cache if it does not pay

4 steps in order. Play them, or step through them one at a time.

6Follow-up questions

Why not just use a clustered second-level cache everywhere?

It solves invalidation between instances but not writes from outside Hibernate, and it adds network traffic and operational complexity to every entity update. For frequently changing data the hit ratio stays low, so we would pay that cost for little benefit.

How do you enforce the policy across teams?

A short guideline with the approve and steer-away table, a review step for any new @Cache annotation, and a dashboard of cache hit ratios per service. An ArchUnit rule can flag @Cache on entities not on an approved list.

What metric shows the cache is hurting?

Low hit ratio with high put counts means the cache is churning. Support tickets about stale data, or a rising number of OptimisticLockException failures after enabling the cache, are also signs that cached state is out of date.

7Conclusion

In this answer, we drew the line for second-level caching. We approve it for read-mostly reference data with few writers, with agreed TTLs, and steer teams away from frequently updated entities, tables shared between services and the query cache on busy tables. For other data we prefer explicit Spring Cache at service boundaries, where key, TTL and eviction are visible. Every cache must report hit ratio and staleness, and teams fix N+1 queries and missing indexes first, because that removes most of the load without any staleness.

What to say in the interviewAbout 80 seconds aloud

Open with

I would approve it narrowly. The second-level cache works well for read-mostly reference data with one writer, like countries, currencies, categories or configuration, which is small, read on nearly every request by id and changes rarely.

Then, if they want more

For those I would approve READ_ONLY or READ_WRITE with a short TTL the business agrees to.

I would steer teams away from caching entities that change often, like orders, prices or stock, and from any table written by several services or batch jobs, because those writes bypass Hibernate and with local caches on several instances you get stale reads, usually with a low hit ratio anyway.

I would also be wary of the query cache on busy tables, since any write to the table invalidates it. Where teams need caching beyond reference data, I would point them to Spring Cache at the service boundary, ideally Redis, where the key, TTL and eviction are explicit in the code and every write path can evict.

Any cache must come with hit ratio and staleness metrics, and we remove it if it does not pay. Most importantly, I would first look at the top queries: N+1 patterns, missing indexes and over-fetching usually cause most of the load, and fixing them helps more than a cache without any consistency risk.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Teams want to enable the Hibernate second-level cache widely to reduce database load....": https://scrivio-interview-library.netlify.app/databases/jpa-performance/8bc7fe01cc/